I'm wondering if there's an implementation of slf4j that logs into a JSON format. Where each log messages would be a JSON object, 1 per row.
e.g. each line of the log file would look like something this:
{"severity":"WARN", "ts":12345678, "host":"myhostname.com", "message":"Failed to do something"}
To enable parsing JSON log, you add parse: json to a pipeline in the ClusterLogForwarder CR, as shown in the following example. When you enable parsing JSON logs by using parse: json , the CR copies the JSON-structured log entry in a structured field, as shown in the following example.
Structured logging is the practice of implementing a consistent, predetermined message format for application logs that allows them to be treated as data sets that can be more easily searched and analyzed than text.
What is a JSON file? A JSON file stores data in key-value pairs and arrays; the software it was made for then accesses the data. JSON allows developers to store various data types as human-readable code, with the keys serving as names and the values containing related data.
Ok, this thread needs to be updated a bit since most of the answers are quite old. All modern java log liibraries support json layout out of the box. With log4j2 you don't even need any additional libs, just jackson in your classpath, which you most likely already have.
Of course, you do need to use json layout and specify it explicitly. See example for log4j2 here. Note that default layout might not work as expected with your log collectors of choice. For example, I used FileBeat and it required for logs to be produced one per line. Log4j2 has a tuple of parameters for that:
Use with eventEol=true and compact=true to get one record per line.
My appenders look like this:
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="ACCEPT"/>
<JsonLayout complete="false" compact="true" eventEol="true"/>
</Console>
<Console name="STDERR" target="SYSTEM_ERR">
<ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
<JsonLayout complete="false" compact="true" eventEol="true"/>
</Console>
</Appenders>
If this is not enough, you can also take a look at this repo: https://github.com/savoirtech/slf4j-json-logger
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With