Java Logging - slf4j, log4j

Is there a way to pass a property map to slf4j logger?

for example, I would like to do something like this:

Logger logger = LoggerFactory.getLogger(SomeClass.class);

Map data = new HashMap<String, String>();
data["key1"] = "value1";
data["key2"] = "value2";

logger.info("my info message", data)

      

Then I would like my appender to receive log4j LoggingEvent

with the above parameters, for example:

public class MyAppender extends AppenderSkeleton {
...
...

@Override
protected void append(LoggingEvent event) {
    Map properties = event.getProperties();
    String valueOfKey1 = (String) properties.get("key1");   
    //valueOfKey1 sould be equal to 'value1'
}
...
...    

      

UPDATE:

Is there any java logging framework that supports passing HashMap data (or similar in its interface)

+3


source to share


1 answer


From the SLF4J Guide " Mapped Diagnostic Context" is essentially a map supported by a logging framework where application code provides key-value pairs that can then be embedded in the log structure in log messages. MDC data can also be very useful when filtering messages or triggering certain actions.

SLF4J supports MDC or Mapped Diagnostic Context. If the underlying logging framework offers MDC functionality, SLF4J will delegate the underlying MDC framework. Please note that currently only log4j and logback offer MDC functionality.

As you tagged the question with log4j

, and since your example is quoting classes log4j

, SLF4J will allow you to set values ​​in a thread-based MDC map using the slf4j API. These values ​​will then be available at the level log4j

in LoggingEvent

.

Here is an example adapted from the logging guide provided in the SLF4J manual (as well as @Seelenvirtuose's comment):



public class SimpleMDC {
  static public void main(String[] args) throws Exception {

    // You can put values in the MDC at any time. Before anything else
    // we put the first name
    MDC.put("key1", "value1");

    [ SNIP ]

    Logger logger = LoggerFactory.getLogger(SimpleMDC.class);
    // We now put the last name
    MDC.put("key2", "value2");

    logger.info("Info log message");
  }
}

      

Then, in your custom application, you can get the values ​​easily:

public class MyAppender extends AppenderSkeleton {
...
...

@Override
protected void append(LoggingEvent event) {
    String valueOfKey1 = (String) event.getMDC("key1");   
    //valueOfKey1 should be equal to 'value1'
}
...
... 

      

Of course the same functional feature will be available via Logback ...

+2


source







All Articles