런타임 시 Go lang slog의 로그 수준 변경

王林
풀어 주다: 2024-02-09 10:18:08
앞으로
387명이 탐색했습니다.

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

php editor Strawberry는 런타임에 Go lang slog의 로그 수준을 변경하는 방법을 소개하기 위해 왔습니다. Go lang slog는 일반적으로 사용되는 로깅 라이브러리이지만 개발 중에 애플리케이션을 다시 시작하지 않고 로그 수준을 변경해야 할 수도 있습니다. 이 기사에서는 다양한 요구 사항에 맞게 런타임 시 로그 수준을 쉽게 변경할 수 있는 간단하고 효과적인 방법을 소개합니다. 당신이 초보자이든 숙련된 개발자이든 이 팁은 당신의 프로젝트에 도움이 될 것입니다.

질문 내용

Go slog 로깅 패키지("log/slog")를 사용하여 런타임 시 로거 로그 수준을 변경하는 방법을 찾고 있나요?

가능합니까? 나는 그것을 가지고 몇 시간을 보냈지만 이것을 할 수 있는 방법을 찾을 수 없습니다.

업데이트 1 - 3개의 로거로 앱 실행 및 HTTP를 사용하여 레벨 변경

아래는 Peter의 답변을 바탕으로 제가 작성한 코드입니다. HTTP 호출을 합니다. http://localhost:8080/changeLogLevel?logger=TCP&level=ERROR.

으아악

업데이트 2 - 기본 예

아래 코드는 예상대로 작동합니다.

으아악

출력

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)
}
로그인 후 복사

Solution

내장 핸들러의 생성자는 모두 HandlerOptions 매개변수를 사용합니다. HandlerOptions에는 레벨을 동적으로 변경하는 데 사용할 수 있는 Level 필드가 있습니다.

으아악

그러므로 로거를 생성할 때 LevelVar를 설정하세요.

으아악

자신만의 핸들러를 구현하는 경우 Enabled 메서드가 로그 수준을 결정하므로 LevelVar도 쉽게 사용할 수 있습니다.

으아악

위 내용은 런타임 시 Go lang slog의 로그 수준 변경의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:stackoverflow.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!