dongwu5318
2017-06-28 06:24 阅读 45
已采纳

无法发送对数输出/ dev / null

I'm using Logrus package for logging on my project.

All is fine but for testing purpose I do not need the logrus output to be displayed.

I looking at logrus.SetOuput for answer.

So basically I want the log to be written to /dev/null

But for some reason I still see the logs on STDOUT

   // This code run right at the start
   if env == "test" {
        fmt.Println("Entering test mode ....")
        logrus.SetOutput(ioutil.Discard)
        return
    }

Here how my logger setup looks like

// logger.go

package logger

import(
    "os"
    "io/ioutil"
    "github.com/Sirupsen/logrus"
)

var log *logrus.Logger

const (
    DEBUG   = 0
    INFO    = 1
    WARNING = 2
    ERROR   = 3
)

func init() {
    env := os.GetEnv("ENV")
    if env != "test" {
        return
    }
    logrus.SetOutput(ioutil.Discard)
}


func Init(logLevl int) {
    log = logrus.New()
    log.Formatter = &logrus.TextFormatter{FullTimestamp: true}
    switch logLevl {
    case DEBUG:
        log.Level = logrus.DebugLevel
    case INFO:
        log.Level = logrus.InfoLevel
    case WARNING:
        log.Level = logrus.WarnLevel
    case ERROR:
        log.Level = logrus.ErrorLevel
    }
}

func Get() *logrus.Logger {
    return log
}

func I(args ...interface{}) {
    log.Info(args)
}

func Df(format string, args ...interface{}) {
    log.Debugf(format, args)
}

func D(args ...interface{}) {
    log.Debug(args)
}

func W(args ...interface{}) {
    log.Warn(args)
}

And here how I use the logger package

import "logger"

func init() {
  logger.Init(0)
}

logger.D("Dummy string")
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    doujia8801 doujia8801 2017-06-28 07:47

    You're using two different logrus.Logger variables in your code. The first, which is called in init() is the global default Logger that gets exported from logrus. Later, in your custom initialization function Init(logLevel int), you're creating a new Logger via logrus.New() which is from then on used for logging — but hasn't been configured to use a different output.

    I'd suggest to get rid of the init() function and do all the initialization in your Init(logLevel int) (please note the different API for setting the output).

    func Init(logLevl int) {
        log = logrus.New()
        log.Formatter = &logrus.TextFormatter{FullTimestamp: true}
        switch logLevl {
        case DEBUG:
            log.Level = logrus.DebugLevel
        case INFO:
            log.Level = logrus.InfoLevel
        case WARNING:
            log.Level = logrus.WarnLevel
        case ERROR:
            log.Level = logrus.ErrorLevel
        }
    
        env := os.Getenv("ENV")
        if env != "test" {
            return
        }
        log.Out = ioutil.Discard
    }
    
    点赞 评论 复制链接分享

相关推荐