Default log4j MDC value
Asked Answered
G

2

7

Does anyone know how to specify a default value for a missing entry in the MDC using log4j's config xml? I have an appender defined in my XML file like so:

<appender name="DBAppender" class="org.apache.log4j.jdbc.JDBCAppender"> 
    <param name="URL" value="jdbc:sqlserver://phenom\\MSSQLSERVER_2012\;databaseName=pickmax_express" /> 
    <param name="Driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" /> 
    <param name="User" value="user" /> 
    <param name="Password" value="password" /> 
    <layout class="org.apache.log4j.PatternLayout"> 
        <param name="ConversionPattern" 
          value="INSERT INTO LOG (source, message, order_id, log_level) VALUES ( 'TESTSOURCE','%m', %X{orderID}, 0)" 
        /> 
    </layout> 
</appender> 

The part in question is the order ID from the MDC (%X{orderID}). I searched around and only found duplicates of the same thread saying something along the lines of $${orderID:-DefaultValue}, but this doesnt work in this context. I need to be able to default the value to 0 or -1 or some other sentinal value when log messages are received in contexts which wont have an order ID

Gilford answered 25/4, 2014 at 17:52 Comment(0)
V
3

If you access the MDC object in your java code, you can initialize the value for orderId by adding the following in some startup area (for example, a servlet init() method):

import org.apache.log4j.MDC;

public void blammyStartupMethod()
{
    MDC.put("orderId", "sentinal value");
}

Edit: It seems likely that you will need to set this default every time you write a log message that does not have an orderId value and after each MDC.remove(). AOP seems like an option here.

Virginium answered 25/4, 2014 at 18:3 Comment(1)
Thanks for this. While this wont work my problem, after playing around with it I learned a bit more about the MDC, so +1.Gilford
T
0

Also you can define default value in the layout pattern like %X{orderID:-Def value}

<param name="ConversionPattern" 
          value="INSERT INTO LOG (source, message, order_id, log_level) VALUES ( 'TESTSOURCE','%m', %X{orderID:-Def value}, 0)" 
        />
Teneshatenesmus answered 10/4, 2017 at 13:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.