Differentiating Error Level Log Output in Terminal and Hook
Closed this issue · 1 comments
willywartono14 commented
I'm currently working with the zerolog library in my Go application, and I'm facing a requirement where I need to differentiate the output of log messages based on their log level:
- I want log messages of ERROR level to be displayed only in the terminal/console.
- All log messages, regardless of their level (DEBUG, INFO, WARNING, ERROR), should be sent to a hook for further processing.
This is my Code :
func InitLogger(ctx context.Context, cfg *config, mc *mongo.Client) *zerolog.Logger {
once.Do(func() {
var multi zerolog.LevelWriter
consoleWriter := zerolog.ConsoleWriter{Out: os.Stdout, NoColor: true, TimeFormat: time.RFC3339}
multi = zerolog.MultiLevelWriter(consoleWriter)
logger := zerolog.New(multi).Level(zerolog.TraceLevel).With().Timestamp().Logger()
logger = logger.Hook(&ZerologHook{
mClient: mc,
})
zLog = &logger
})
return zLog
}
type ZerologHook struct {
mClient *mongo.Client
}
func (zh *ZerologHook) Run(e *zerolog.Event, level zerolog.Level, message string) {
wg.Add(1)
go func() {
logData := LogData{}
_ = zh.sendLogToMongoDB(e.GetCtx(), message, logData)
wg.Done()
}()
}
Is there a way to configure zerolog such that ERROR level log messages are shown only in the terminal while still allowing all log messages to be sent to the hook for further processing?
rs commented
Please check LevelWriter.