Logrus 转义符号字符

Logrus escaping ampersand character

我正在使用 Logrus,我遇到了在其日志中显示 & 字符的问题:

logger.WithFields(logrus.Fields{
        "value": "value&value",
}).Info("GET")

这会打印 value\u0026value& 的十六进制值而不是 & 本身

有人知道如何解决这个问题吗?

如果可能有帮助,下面是记录器的初始化方式:

    import (
       "log"

       "github.com/getsentry/sentry-go"
       sentry_hook "github.com/onrik/logrus/sentry"
       "github.com/pkg/errors"
       "github.com/sirupsen/logrus"
    )

    func newLogger() *logrus.Entry {
        log := logrus.StandardLogger()
    
        log.SetFormatter(&logrus.JSONFormatter{})
    
        level, err := logrus.ParseLevel(config.LogLevel)
        if err != nil {
            log.Fatalf("%+v", errors.WithStack(err))
        }
        log.SetLevel(level)
    
        hook := newSentryHook()
        log.AddHook(hook)
    
        entry := logrus.NewEntry(log)
    
        return entry
    }
    
    func newSentryHook() *sentry_hook.Hook {
        if err := sentry.Init(sentry.ClientOptions{Dsn: config.SentryDSN}); err != nil {
            log.Fatalf("%+v", errors.WithStack(err))
        }
        hook, err := sentry_hook.NewHook(sentry_hook.Options{Dsn: config.SentryDSN}, logrus.PanicLevel, logrus.FatalLevel, logrus.ErrorLevel)
        if err != nil {
            log.Fatalf("%+v", errors.WithStack(err))
        }
        return hook
    }

This is the default behavior of the json package:

The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e to avoid certain safety problems that can arise when embedding JSON in HTML.

In non-HTML settings where the escaping interferes with the readability of the output, SetEscapeHTML(false) disables this behavior.

Logrus 在 JSONFormatter.DisableHTMLEscape field 中公开了此设置。 要禁用 HTML 转义,请将其设置为 true:

log.SetFormatter(&logrus.JSONFormatter{
    DisableHTMLEscape: true,
})