Logrus: Logger.SetLevel

Created on 14 Mar 2017  路  7Comments  路  Source: sirupsen/logrus

It appears that we can't (safely) configure the loglevels of loggers except for the standard logger.

For the standard logger, we can use the logrus.SetLevel method, which protects the level with a mutex, but this mutex is unexported. So if we set var log = logrus.New() in our application (which is recommended in the docs), we actually can't configure the log level.

The only other thing we can do is to call SetLevel on the standard logger and then assigning it:

var log *logrus.Logger

func init(){
    logrus.SetLevel(logrus.DebugLevel)
    log = logrus.StandardLogger()
}

but that's a bit clumsier, and it also means we're restricted to just using the standard logger.

Am I missing an alternative?

Most helpful comment

This has shipped 馃帀

All 7 comments

:+1: Had a similar situation.

Perhaps instead logrus.New() try instantiating logger on your own:

&log.Logger{
    Out: os.Stderr,
    Formatter: new(log.TextFormatter),
    Hooks: make(log.LevelHooks),
    Level: log.DebugLevel,
}

Unfortunately that doesn't work for us, because we need to be able to set the log level based on the configuration file that's passed. The only way to do that and also preserve the var log *logrus.Logger declaration as a drop-in replacement for the standard library log is to have SetLevel. Otherwise, it still introduces a race condition.

@sirupsen I'm happy to put together a PR for this if it's something you're interested in adding.

Yes, that's still a limitation - can't change the log level after it has been set,.

Would be interested in testing out your PR too.

This makes sense, feel free to propose a PR upstream.

@ChimeraCoder @sirupsen
because #512 had been merged - maybe it will make sense to change from func (logger *Logger) setLevel(level Level) to func (logger *Logger) SetLevel(level Level) { to make this method publicly available? Any downsides?

This has shipped 馃帀

馃帀

Was this page helpful?
0 / 5 - 0 ratings

Related issues

drewwells picture drewwells  路  3Comments

Integralist picture Integralist  路  3Comments

taherv picture taherv  路  4Comments

anotherGoogleFan picture anotherGoogleFan  路  3Comments

SergeiVasilenko picture SergeiVasilenko  路  3Comments