搜索
首页后端开发Golang在运行时更改 Go lang slog 的日志级别

在运行时更改 Go lang slog 的日志级别

php小编草莓在这里为大家介绍一种在运行时更改 Go lang slog 的日志级别的方法。Go lang slog 是一个常用的日志记录库,但在开发过程中,我们可能需要在不重启应用程序的情况下更改日志的级别。本文将介绍一种简单有效的方法,让您在运行时轻松地更改日志级别,以满足不同的需求。无论您是初学者还是有经验的开发者,这个技巧都将对您的项目有所帮助。

问题内容

使用 Go slog 日志记录包("log/slog"),我正在寻找一种在运行时更改记录器日志级别的方法?

是否可以? 我花了几个小时玩它,但找不到办法做到这一点。

更新 1 - 运行具有 3 个记录器的应用并使用 HTTP 更改级别

下面是我根据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)
}

更新 2 - 基本示例

下面的代码按预期工作。

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中文网其他相关文章!

声明
本文转载于:stackoverflow。如有侵权,请联系admin@php.cn删除
初始功能和副作用:平衡初始化与可维护性初始功能和副作用:平衡初始化与可维护性Apr 26, 2025 am 12:23 AM

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

开始GO:初学者指南开始GO:初学者指南Apr 26, 2025 am 12:21 AM

goisidealforbeginnersandsubableforforcloudnetworkservicesduetoitssimplicity,效率和concurrencyFeatures.1)installgromtheofficialwebsitealwebsiteandverifywith'.2)

进行并发模式:开发人员的最佳实践进行并发模式:开发人员的最佳实践Apr 26, 2025 am 12:20 AM

开发者应遵循以下最佳实践:1.谨慎管理goroutines以防止资源泄漏;2.使用通道进行同步,但避免过度使用;3.在并发程序中显式处理错误;4.了解GOMAXPROCS以优化性能。这些实践对于高效和稳健的软件开发至关重要,因为它们确保了资源的有效管理、同步的正确实现、错误的适当处理以及性能的优化,从而提升软件的效率和可维护性。

进行生产:现实世界的用例和示例进行生产:现实世界的用例和示例Apr 26, 2025 am 12:18 AM

Goexcelsinproductionduetoitsperformanceandsimplicity,butrequirescarefulmanagementofscalability,errorhandling,andresources.1)DockerusesGoforefficientcontainermanagementthroughgoroutines.2)UberscalesmicroserviceswithGo,facingchallengesinservicemanageme

go中的自定义错误类型:提供详细的错误信息go中的自定义错误类型:提供详细的错误信息Apr 26, 2025 am 12:09 AM

我们需要自定义错误类型,因为标准错误接口提供的信息有限,自定义类型能添加更多上下文和结构化信息。1)自定义错误类型能包含错误代码、位置、上下文数据等,2)提高调试效率和用户体验,3)但需注意其复杂性和维护成本。

使用GO编程语言构建可扩展系统使用GO编程语言构建可扩展系统Apr 25, 2025 am 12:19 AM

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建筑物内currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

有效地使用Init功能的最佳实践有效地使用Init功能的最佳实践Apr 25, 2025 am 12:18 AM

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用辅助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

INIT函数在GO软件包中的执行顺序INIT函数在GO软件包中的执行顺序Apr 25, 2025 am 12:14 AM

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具