如何使golang的Logrus通过多个文件共享相同的配置?

The plain demo code works as they integrated the Logrus's config and the logic of main, as follows

func main() {
    var filename string = "logfile.log"
    f, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
    Formatter := new(log.TextFormatter)
    Formatter.TimestampFormat = "02-01-2006 15:04:05"
    Formatter.FullTimestamp = true
    log.SetFormatter(Formatter)
    if err != nil {
        fmt.Println(err)
    } else {
        log.SetOutput(f)
    }

    log.Info("Some info. Earth is not flat")
    log.Warning("This is a warning")
    log.Error("Not fatal. An error. Won't stop execution")
}

But in real world, the config of logrus should be seperated into individual file, consider the file structure as :

logrusdemo/
├── main.go
└── mylib
    ├── aa.go
    └── bb.go

And I want to share the same config in these files:

The source code of aa.go:

package mylib

// GetTestA testing
func GetTestA() string {
    //log.info("entering aa.go")
    return "001"
}

The source code of bb.go:

package mylib

// GetTestB testing
func GetTestB() string {
    //log.info("entering bb.go")
    return "001"
}

The source code of main.go:

package main

import (
    "fmt"
    "logrusdemo/mylib"
)

func main() {
    //log.info("entering main")
    fmt.Printf("%v", mylib.GetTestA())
    fmt.Printf("%v", mylib.GetTestB())
}

I was wondering how to make logrus works in this situation?

You can do so by passing your logger to your structs / functions.

package main

import (
    "fmt"
    "github.com/sirupsen/logrus"
    "logrusdemo/mylib"
)

func main() {
    log = logrus.New()

    var filename string = "logfile.log"
    f, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)

    Formatter := new(log.TextFormatter)
    Formatter.TimestampFormat = "02-01-2006 15:04:05"
    Formatter.FullTimestamp = true
    log.SetFormatter(Formatter)
    if err != nil {
        fmt.Println(err)
    } else {
        log.SetOutput(f)
    }

    log.Info("Some info. Earth is not flat")
    log.Warning("This is a warning")
    log.Error("Not fatal. An error. Won't stop execution")

    fmt.Printf("%v", mylib.GetTestA(log))
    fmt.Printf("%v", mylib.GetTestB(log))
}

And

package mylib

import (
    "github.com/sirupsen/logrus"
)

// GetTestA testing
func GetTestA(log *logrus.Logger) string {
    log.Info("entering aa.go")
    return "001"
}

If you don't want to pass it as an argument, you can also pass your logger in a context, or use it as a global.