Search code examples
gosysloglogrus

Logrus hooks with syslog by demand


I'm using golang logrus for logging and I'm having a wrapper with all the regular functions like Info(..),Infof(..) e.t.c I want to implement a wrapper function Audit(..) for logging to syslog. I noticed logrus syslog hooks problem is, once it got hooked every log function is logging to syslog, also Infof(..) which I don't want them to.

Is there a way I can call syslog by demand? other than:

func (l *WrapLogger) Audit(msg string) {
       l.logger.AddHook(syslogHook)
       l.logger.Info(msg)
       l.logger.ReplaceHooks(logrus.LevelHooks) // removing somehow the hook
}

Thanks


Solution

  • If you're trying to delegate what message to send by its log level then you can do it by setting the log levels the hook accepts.

    For example:

    log.AddHook(&writer.Hook{
        Writer: os.Stderr,
        LogLevels: []log.Level{ log.WarnLevel },
    })
    log.AddHook(lSyslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, ""))
    log.Info("This will go to syslog")
    log.Warn("This will go to stderr")
    

    If you want to route this no according to the log level then what you suggested may work but it feels odd and may have race-conditions.

    What I suggest you to do is create your own hook that gets hook list and route to the right hook(s) according to the message or to the fields that are passed when calling Info, Warn and etc.