1

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

Elad Aharon
  • 405
  • 2
  • 18
  • I am not sure I understand your question. You created two `WrapLogger` instances and if you call `wl1.info("hello")` it will add "hello" twice to syslog? – boaz_shuster Oct 28 '20 at 17:11
  • not exactly @boaz_shuster, I have only 1 log wrapper. My main question: is there a way to control which hooks will be called? Now that I'm thinking about it perhaps I should wrap 2 logrus instances: one with syslog hook and the other w/o. – Elad Aharon Oct 28 '20 at 18:24

1 Answers1

1

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.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
boaz_shuster
  • 2,825
  • 20
  • 26