Does Log4j SyslogAppender support MDC and NDC

3.6k Views Asked by At

Simple really, does Log4j SyslogAppender support MDC and NDC in the sense that the output is structured data i.e. uses the structured data features of the protocol?

Further, are there any limits on what can be put in the MDC and successfully appended to the log?

2

There are 2 best solutions below

2
On BEST ANSWER

MDC nor NDC are part of the Syslog protocol. Thus, log4j does not (nor can it) support MDC/NDC within the structured data of the Syslog protocol. However, nothing prevents you from adding MDC or NDC data in the "message" part of the syslog message by setting the ConversionPattern parameter to include MDC informatation.

Here is an example for an MDC entry with the key "ki" :

log4j.rootLogger=INFO, SYSLOG
log4j.appender.SYSLOG=org.apache.log4j.net.SyslogAppender
log4j.appender.SYSLOG.SyslogHost=a.host.name

# Facility must be one of the case-insensitive strings:
# KERN, USER, MAIL, DAEMON, AUTH, SYSLOG, LPR, NEWS, UUCP, CRON,
# AUTHPRIV, FTP, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6,
# LOCAL7 
log4j.appender.SYSLOG.facility=KERN

log4j.appender.SYSLOG.layout=org.apache.log4j.PatternLayout
log4j.appender.SYSLOG.layout.ConversionPattern=%r %p %c %X{ki} - %m\n

For NDC, you would replace "%X{ki} with just "%x" (note the use of lower case).

As for the second part of your question, there are no limits to the values you can place within MDC or NDC.

2
On

Looking at the source code, I don't see any reason why it shouldn't.

Have you tried successfully writing to syslog, and then writing with something in your NDC/MDC ? Note that you'll have to enable this in the PatternLayout (using %x or %X).

The MDC doesn't appear to have any limitations on what you can insert (again, based on inspecting the source code). I suspect the MDC writing will simply perform a toString() on the contents of the MDC, and so you may be limited simply by how useful/readable your objects are when rendered this way.