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

Mark W
  • 2,791
  • 1
  • 21
  • 44

2 Answers2

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.

DwB
  • 37,124
  • 11
  • 56
  • 82
  • Thanks for this. While this wont work my problem, after playing around with it I learned a bit more about the MDC, so +1. – Mark W Apr 25 '14 at 18:37
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)" 
        />
Aarish Ramesh
  • 6,745
  • 15
  • 60
  • 105