Re: Feature Request: Named Arguments for Structured Logging such as JSON
Ralph Goers <[email protected]> Sun, 7 Apr 2024 11:46:13 -0700
| Newsgroups | gmane.comp.jakarta.log4j.user |
|---|---|
| Message-ID | <[email protected]> |
I wasn’t aware GoLang had a “standard” logger. Last time I checked GoLang’s logging library was awful.
Log4j 2 has supported what you want ever since Json Template Layout was added. See https://logging.apache.org/log4j/2.x/manual/json-template-layout.html.
To get what you want just specify a pattern (See PatterLayout) to the JsonTemplateLayout configuration.
In addition, you can also include the Map fields as individual attributes.
Here is an example configuration for the message
"message": {
"$resolver": "pattern",
"pattern": “%K"
},
Ralph
> On Apr 7, 2024, at 9:28 AM, Clayton Wohl <[email protected]> wrote:
>
> The Golang standard library lets you do this:
>
> slog.Info("showing named arguments with structured logging",
> slog.Bool("some-bool", true),
> slog.Int("some-int", 123),
> slog.Float64("some-float64", 1.234),
> slog.String("some-string", "xyz"))
>
> which outputs the following at runtime:
>
> {"time":"2024-04-07T11:10:04.925291-05:00","level":"INFO","msg":"showing
> named arguments with structured
> logging","some-bool":true,"some-int":123,"some-float64":1.234,"some-string":"xyz"}
>
> I'd like to do this in Java. This seems to be a fairly common use
> case. Log4j's API doesn't seem to offer this. The closest I can get
> is:
>
> Logger logger = LogManager.getLogger();
>
> logger.info(new MapMessage()
> .with("someInt", 123)
> .with("someFloat", 1.23456)
> .with("someBool", true)
> .with("someString", "abc"));
>
> which outputs the following at runtime. Notice that it just converted
> the MapMessage to a string and put that in the JSON message field.:
>
> {"@timestamp":"2024-04-07T16:26:21.232Z","ecs.version":"1.2.0","log.level":"INFO","message":"someBool=\"true\"
> someFloat=\"1.23456\" someInt=\"123\"
> someString=\"abc\"","process.thread.name":"main","log.logger":"demo.Main"}
>
> Is it possible that log4j3 offer something like what Golang's slog does?
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: [email protected]
> For additional commands, e-mail: [email protected]
>