Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does SLF4J support structured logging [closed]

Anyone knows how structured logging is usually implemented with SLF4J?

Is there any open source already out there handling this?

like image 718
Alfred Avatar asked May 25 '16 07:05

Alfred


People also ask

How does SLF4J binding work?

Bindings are basically implementations of a particular SLF4J class meant to be extended to plug in a specific logging framework. By design, SLF4J will only bind with one logging framework at a time. Consequently, if more than one binding is present on the classpath, it will emit a warning.

Does SLF4J use Commons Logging?

SLF4J based implementation of commons-logging wrapper APIs.

How is SLF4J different from log4j?

Unlike log4j, SLF4J (Simple Logging Facade for Java) is not an implementation of logging framework, it is an abstraction for all those logging frameworks in Java similar to log4J. Therefore, you cannot compare both. However, it is always difficult to prefer one between the two.

Does SLF4J use log4j internally?

So essentially, SLF4J does not replace log4j; they both work together. It removes the dependency on log4j from your application and makes it easy to replace it in the future with the more capable library.


2 Answers

If you use SLF4J in conjunction with Logback and Logstash, structured logging is supported with StructuredArguments. You can find documentation about this on the logstash logback encoder page on Github.

A simple example of how it works. This log line..

log.debug("Retrieved file {}", StructuredArguments.value("filename", upload.getOriginalFilename()))

..yields the following log json output:

{
  "filename": "simple.zip",
  "@timestamp": "2019-02-12T14:31:31.631+00:00",
  "severity": "DEBUG",
  "service": "upload",
  "thread": "http-nio-9091-exec-1",
  "logger": "some.great.ClassName",
  "message": "Retrieved file simple.zip"
}
like image 103
Fritz Duchardt Avatar answered Oct 12 '22 00:10

Fritz Duchardt


Slf4j added support for structured logging (and fluent API) with v2.0.0 (Alpha as of Oct 2019):

  • http://www.slf4j.org/api/org/slf4j/event/KeyValuePair.html
  • http://www.slf4j.org/api/org/slf4j/event/LoggingEvent.html
  • http://www.slf4j.org/apidocs/org/slf4j/spi/LoggingEventBuilder.html

    int newT = 15;
    int oldT = 16;
    
    // using classical API
    logger.debug("oldT={} newT={} Temperature changed.", newT, oldT);
    
    // using fluent API
    logger.atDebug()
            .addKeyValue("oldT", oldT)
            .addKeyValue("newT", newT)
            .log("Temperature changed.");          
    
like image 26
gavenkoa Avatar answered Oct 12 '22 02:10

gavenkoa