duangu9173 2015-05-15 10:48
浏览 330
已采纳

Golang Logrus-如何进行集中配置?

I am using logrus in a Go app. I believe this question is applicable to any other logging package (which doesn't offer external file based configuration) as well.

logrus provides functions to setup various configuration, e.g. SetOutput, SetLevel etc.

Like any other application I need to do logging from multiple source files/packages, it seems you need to setup these options in each file with logrus.

Is there any way to setup these options once somewhere in a central place to be shared all over the application. That way if I have to make logging level change I can do it in one place and applies to all the components of the app.

  • 写回答

2条回答 默认 最新

  • doupa1883 2015-05-15 13:55
    关注

    You don't need to set these options in each file with Logrus.

    You can import Logrus as log:

    import log "github.com/Sirupsen/logrus"
    

    Then functions like log.SetOutput() are just functions and modify the global logger and apply to any file that includes this import.

    You can create a package global log variable:

    var log = logrus.New()
    

    Then functions like log.SetOutput() are methods and modify your package global. This is awkward IMO if you have multiple packages in your program, because each of them has a different logger with different settings (but maybe that's good for some use cases). I also don't like this approach because it confuses goimports (which will want to insert log into your imports list).

    Or you can create your own wrapper (which is what I do). I have my own log package with its own logger var:

    var logger = logrus.New()
    

    Then I make top-level functions to wrap Logrus:

    func Info(args ...interface{}) {
        logger.Info(args...)
    }
    
    func Debug(args ...interface{}) {
        logger.Debug(args...)
    }
    

    This is slightly tedious, but allows me to add functions specific to my program:

    func WithConn(conn net.Conn) *logrus.Entry {
        var addr string = "unknown"
        if conn != nil {
            addr = conn.RemoteAddr().String()
        }
        return logger.WithField("addr", addr)
    }
    
    func WithRequest(req *http.Request) *logrus.Entry {
        return logger.WithFields(RequestFields(req))
    }
    

    So I can then do things like:

    log.WithConn(c).Info("Connected")
    

    (I plan in the future to wrap logrus.Entry into my own type so that I can chain these better; currently I can't call log.WithConn(c).WithRequest(r).Error(...) because I can't add WithRequest() to logrus.Entry.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了