mangusta
mangusta

Reputation: 3544

Logrus escaping ampersand character

I'm using Logrus and I have encountered an issue with displaying & character in its logs:

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

This prints value\u0026value i.e. hex value of & instead of & itself

Anyone knows how to fix this?

If it might be helpful, here's how the logger is being initialized:

    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
    }

Upvotes: 3

Views: 1572

Answers (1)

Peter
Peter

Reputation: 31691

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 exposes this setting in the JSONFormatter.DisableHTMLEscape field. To disable HTML escaping, set it to true:

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

Upvotes: 6

Related Questions