Go语言 如何在slog logger中自动传递结构并使用其字段?

hk8txs48  于 5个月前  发布在  Go
关注(0)|答案(2)|浏览(57)

我使用slog包。我面临的问题是,我必须传递太多的参数给它,而我在一个结构中有这些参数的大部分。
有没有一种方法可以修改处理程序来使用这个结构体?类似于你在python中可以做的,发送一个dict或对象作为额外的,然后从中提取所需的参数。
现在我有了这个:

g.l.Log(
    context.TODO(),
    slog.LevelInfo,
    "Sending request to server.",
    "Destination", m.route.destination,
    "Protocol", m.route.protocol,
    "Service Identifier", m.route.serID,
    "Session ID", m.GetIdentifier(),
    "Client Connection", client.RemoteAddr().String(),
    "Server Connection", destination.RemoteAddr().String(),
)

字符串
我想做的是:

g.l.Log(
    context.TODO(),
    slog.LevelInfo,
    "Sending request to server.",
    "message", m,
    "Client Connection", client.RemoteAddr().String(),
    "Server Connection", destination.RemoteAddr().String(),
)


我该怎么做?

8ehkhllq

8ehkhllq1#

如果你只想记录结构体的字段和值,你也可以使用fmt.Sprintf和%+v动词来打印结构体的字段/值。

vulvrdjw

vulvrdjw2#

我找到了这个问题的答案。
我将slog logger嵌入到我的自定义logger中。

type Logger struct {
    *slog.Logger
}

字符串
我还为我的结构体编写了导出函数,如下所示:

func (m *GatewayMessage) LoggableData() *xlog.RequestData {
    return &xlog.RequestData{
        Request:             m.Request.String(),
        OriginalRequest:     m.OriginalRequest,
    }
}

func (m *GatewayMessage) PopulateGeneralLogData() []any {
    logData := m.LoggableData()
    return []any{
        "Request", logData.Request,
        "OriginalRequest", logData.OriginalRequest,
    }
}


然后我写了一个helper函数,它获取这个Gateway Message作为参数和任意数量的参数,就像slog Logger的Log函数一样。这是debug函数,例如:

func LogDebug(l *xlog.Logger, ctx context.Context, msg string, m *GatewayMessage, args ...any) {
    var generalLogData []any = make([]any, 0)
    if m != nil {
        generalLogData = m.PopulateGeneralLogData()
    }
    args = append(args, generalLogData...)
    l.RuntimeDebug(
        ctx,
        msg,
        args...,
    )
}


我还使用一个名为RuntimeDebug的接收器在所有日志中注入一个名为Scope的参数。

func (l *Logger) RuntimeDebug(ctx context.Context, msg string, args ...any) {
    args = append(args, "Scope", "Runtime")
    l.Logger.Log(
        ctx,
        slog.LevelDebug,
        msg,
        args...,
    )
}

相关问题