slog icon indicating copy to clipboard operation
slog copied to clipboard

需要一个动态设置日志级别的接口

Open konglinglong opened this issue 6 months ago • 0 comments

在程序运行过程,有时候为了定位问题,有动态设置日志级别的需求,但没有找到方便友好的设置接口。 slog.SetLogLevel(lvl)只在std logger上生效。 请问有没有方便友好的动态设置日志级别接口?

package logger

import (
	"github.com/gookit/slog"
	"github.com/gookit/slog/handler"
	"github.com/gookit/slog/rotatefile"
)

var (
	Log1   *slog.Logger
	Log2   *slog.Logger
	AppLog *slog.Record
	CfgLog *slog.Record
)

func init() {
	logTemplate := "[{{datetime}}] [{{level}}] {{message}}\n"

	formatter := slog.NewTextFormatter()
	formatter.TimeFormat = "2006-01-02 15:04:05.000"
	formatter.SetTemplate(logTemplate)
	slog.SetFormatter(formatter)

	h1, _ := handler.NewEmptyConfig(
		handler.WithLogfile("/var/log/rnxt/nas/nas.log"),
		handler.WithRotateTime(rotatefile.EveryDay),
		handler.WithBackupNum(10),
		handler.WithMaxSize(1024*1024*20),
		handler.WithLogLevels(slog.NormalLevels),
	).CreateHandler()
	h1.SetFormatter(formatter)

	h2 := handler.NewConsoleHandler(slog.AllLevels)
	h2.SetFormatter(formatter)

	Log1 = slog.NewWithHandlers(h1, h2)

	AppLog = Log1.WithFields(slog.M{
		"component": "APP",
	})
	CfgLog = Log1.WithFields(slog.M{
		"component": "CFG",
	})
}

func SetLogLevel(level string) {
	lvl, err := slog.Name2Level(level)
	if err != nil {
		AppLog.Fatalln("Failed to parse log level:", err)
	}
	slog.SetLogLevel(lvl)
}

konglinglong avatar Dec 13 '23 08:12 konglinglong