gookit / slog

📑 Lightweight, configurable, extensible logging library written in Go. Support multi level, multi outputs and built-in multi file logger, buffers, clean, rotate-file handling.一个易于使用的,轻量级、可配置、可扩展的日志库。支持多个级别,输出到多文件;内置文件日志处理、自动切割、清理、压缩等增强功能
https://pkg.go.dev/github.com/gookit/slog
MIT License
393 stars 25 forks source link

Setting channel name cross multiple loggers #108

Closed nhi-vanye closed 1 year ago

nhi-vanye commented 1 year ago

What is the best approach to tracking which "application subsystem" a message is coming from?

Normally I would create one logger per subsystem and configure its "name" or "channel".

But it seems that channel is only referenced in the record and its using the global DefaultCannelName

in probe.go I have

var probeLogger = slog.NewWithName("probe")

func init() {

    slog.DefaultChannelName = "probe"
    slog.DefaultTimeFormat = "2006-01-02 15:04:05.000"

    h1 := handler.NewConsoleHandler(slog.AllLevels)
    f := slog.AsTextFormatter(h1.Formatter())
    f.SetTemplate(utils.LogTemplate)
    probeLogger.AddHandlers(h1)

    probeLogger.Infof("Probing %s", viper.GetString("read"))
...

where as in root.go I have

var rootLogger = slog.NewWithName("root")

func init() {

    slog.DefaultChannelName = "root"
    slog.DefaultTimeFormat = "2006-01-02 15:04:05.000"

    h1 := handler.NewConsoleHandler(slog.AllLevels)
    f := slog.AsTextFormatter(h1.Formatter())
    f.SetTemplate(utils.LogTemplate)
    rootLogger.AddHandlers(h1)

All of probe.go's messages are using root

I have worked around it by using a subsystem specific template that hardcodes the name, but that seems unclean...

inhere commented 1 year ago

👍 Thanks for your feedback, I will add logger.ChannelName option setting in next version.

var rootLogger = slog.NewWithName("root", func(l *slog.Logger) {
   // l.ChannelName = "root"
   // or 
   l.ChannelName = l.Name()
})

if not sets, will use slog. DefaultChannelName.


The time format can be sets by:

f := slog.AsTextFormatter(h1. Formatter())
f.TimeFormat = "2006-01-02 15:04:05.000"
nhi-vanye commented 1 year ago

Super-big thumbs up...

inhere commented 1 year ago

hi @nhi-vanye released on the v0.5.3