php小編草莓在這裡為大家介紹一種在運行時更改 Go lang slog 的日誌等級的方法。 Go lang slog 是一個常用的日誌記錄庫,但在開發過程中,我們可能需要在不重新啟動應用程式的情況下更改日誌的等級。本文將介紹一種簡單有效的方法,讓您在運行時輕鬆地更改日誌級別,以滿足不同的需求。無論您是初學者還是有經驗的開發者,這個技巧都將對您的專案有所幫助。
使用 Go slog 日誌記錄包("log/slog"
),我正在尋找一種在運行時更改記錄器日誌等級的方法?
是否可以? 我花了幾個小時玩它,但找不到辦法做到這一點。
下面是我根據Peter的回答所寫的程式碼。
我做 HTTP 呼叫
http://localhost:8080/changeLogLevel?logger=TCP&level=ERROR
。
package main import ( "log" "log/slog" "net/http" "os" "strings" "time" ) func main() { // Create a LevelVar variable and initialize it to DEBUG. // Create the template logger with info tcpLvl := new(slog.LevelVar) tcpLvl.Set(slog.LevelDebug) dbLvl := new(slog.LevelVar) dbLvl.Set(slog.LevelDebug) mqLvl := new(slog.LevelVar) mqLvl.Set(slog.LevelDebug) tcpLogger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ Level: tcpLvl, })) mqLogger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ Level: mqLvl, })) // Create the MQLogger. dbLogger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ Level: dbLvl, })) // Create a goroutine that prints debug messages to the 3 loggers. go func() { levels := map[string]slog.Level{ "DEBUG": slog.LevelDebug, "WARN": slog.LevelWarn, "INFO": slog.LevelInfo, "ERROR": slog.LevelError, } for { for levelStr, numericLevel := range levels { log.Printf("Is: %s enabled for tcpLogger? %v \n", levelStr, tcpLogger.Enabled(nil, numericLevel)) } dbLogger.Debug("This is a debug message from the DBLogger.") tcpLogger.Debug("This is a debug message from the TCPLogger.") mqLogger.Debug("This is a debug message from the MQLogger.") log.Println("----------------------------------------------------") time.Sleep(10 * time.Second) } }() // Create an HTTP server. http.HandleFunc("/changeLogLevel", func(w http.ResponseWriter, r *http.Request) { // Get the logger name from the request. log.Println("----- Got HTTP call -------") loggerName := r.URL.Query().Get("logger") // Get the new log level from the request. newLogLevelStr := r.URL.Query().Get("level") var level slog.Level log.Printf("Incoming log level is %v\n", newLogLevelStr) switch strings.ToUpper(newLogLevelStr) { case "DEBUG": level = slog.LevelDebug case "WARNING": level = slog.LevelWarn case "ERROR": level = slog.LevelError case "INFO": level = slog.LevelInfo default: { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("Invalid level name")) return } } log.Printf("Incoming logger name is %v\n", loggerName) switch strings.ToUpper(loggerName) { case "DB": dbLvl.Set(level) case "TCP": log.Printf("Going to set the TCP logger level to %v\n", level) tcpLvl.Set(level) case "MQ": mqLvl.Set(level) default: w.WriteHeader(http.StatusBadRequest) w.Write([]byte("Invalid logger name")) return } w.WriteHeader(http.StatusOK) }) // Start the HTTP server. http.ListenAndServe(":8080", nil) }
下面的程式碼按預期工作。
package main import ( "log" "log/slog" "os" ) func main() { log.Println("slog chaqnge level demo") lvl := new(slog.LevelVar) lvl.Set(slog.LevelInfo) logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ Level: lvl, })) logger.Info("Info msg") logger.Debug("Debug msg - you will NOT see me") lvl.Set(slog.LevelDebug) logger.Debug("Debug msg - you will see me") }
輸出
2009/11/10 23:00:00 slog chaqnge level demo time=2009-11-10T23:00:00.000Z level=INFO msg="Info msg" time=2009-11-10T23:00:00.000Z level=DEBUG msg="Debug msg - you will see me"
內建處理程序的建構子都採用 HandlerOptions 參數。 HandlerOptions 有一個 Level 字段,您可以使用它動態更改等級。
type HandlerOptions struct { // Level reports the minimum record level that will be logged. // The handler discards records with lower levels. // If Level is nil, the handler assumes LevelInfo. // The handler calls Level.Level for each record processed; // to adjust the minimum level dynamically, use a LevelVar. Level Leveler // ... }
因此,只要在建立記錄器時設定一個 LevelVar 即可:
lvl := new(slog.LevelVar) lvl.Set(slog.LevelInfo) logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ Level: lvl, })) // later ... lvl.Set(slog.LevelDebug)
如果您正在實作自己的處理程序,則 Enabled 方法決定日誌級別,您也可以輕鬆使用 LevelVar:
type MyHandler struct { level slog.Leveler } func (h *MyHandler) Enabled(_ context.Context, level slog.Level) bool { return level >= h.level.Level() }
以上是在運行時更改 Go lang slog 的日誌級別的詳細內容。更多資訊請關注PHP中文網其他相關文章!