[slf4j-dev] Benefits of Message objects?

John Vasileff john.lists at gmail.com
Thu Sep 8 21:11:27 CEST 2011


I put together the following examples to help net out benefits of supporting "Map supplementalData" arguments in Logger methods in addition to Message object support.

Support for supplementalData does not replace Message objects, but is perhaps more of a shortcut for common usage scenarios.  In the end, a Message object is always created by either the application writer or SLF4J.


Scenario #1: Working with a domain object "posting" that implements java.util.Map.  A 1.6.2 error log may look like:

logger.error("error parsing markdown '{}'", badString, e);

but we want to add all details of the "posting" domain object without including them in the message.  Using the supplementalData log methods:

// just add the data
Logger logger = LoggerFactory.getLogger(MyClass.class);
logger.error(posting, "error parsing markdown '{}'", badString, e);

// add the data, but also allow named parameter formatting
Logger logger = LoggerFactory.getLogger(MyClass.class).formatWith(NamedParamFormatter.getInstance());
logger.error(posting, "error parsing markdown for posting {id} '{}'", badString, e);

// just add the data, and format using java.util.formatter
Logger logger = LoggerFactory.getLogger(MyClass.class).formatWith(JavaUtilFormatter.getInstance());
logger.error(posting, "error parsing markdown '%s'", badString, e);

If we used Message objects:

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

// just add the data
logger.error(new DefaultMessage(posting, "error parsing markdown '{}'", badString, e));

// add the data, but also allow named parameter formatting
logger.error(new NamedParamFormattingMessage(posting, "error parsing markdown for posting {id} {}", badString, e));

// just add the data, and format using java.util.formatter
logger.error(new JavaUtilFormatterMessage(posting, "error parsing markdown for posting %s", badString, e));


Scenario #2: Support for StructuredData.  The StructuredData object may augment a log message, or both augment the message and provide the message with toString().

Using SupplementalData methods, where SD implements Map

StructuredData sd = new StructuredData(...);
logger.error(sd);
logger.error(sd, "some log message"); 

Using Message object methods, where SD implements Message

StructuredData sd = new StructuredDataMessage(...);
logger.error(sd);
StructuredData sd = new StructuredDataMessage(..., "some log message");
logger.error(sd);


John


More information about the slf4j-dev mailing list