Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4j database appender

I want log4j to log my errors in a MySql database, but the official documentation on this is pretty sparse (why?). Anyway, here's my attempt at a log4j.xml config file:

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="jdbcAppender" class="org.apache.log4j.jdbc.JDBCAppender"> 
    <param name="URL" value="jdbc:mysql://my_host/my_database" /> 
    <param name="Driver" value="com.mysql.jdbc.Driver" /> 
    <param name="User" value="my_user_name" /> 
    <param name="Password" value="my_passwod" /> 
    <layout class="org.apache.log4j.PatternLayout"> 
        <param name="ConversionPattern" 
          value="INSERT INTO errorlogs (Date, log_level, Application, Message, Exception) VALUES (TIMESTAMP(now()),'%p', ?? '%m', '%e' )"
        /> 
    </layout> 
</appender> 

I need the "Application" parameter to be custom. With log4net in C#, in my code I would add it like this:

log4net.GlobalContext.Properties["Application"] = applciation;

and add it like so in my xml config file:

<parameter>
    <parameterName value="?application" />
    <dbType value="String" />
    <size value="50" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%property{Application}" />
    </layout>
  </parameter>

I was wondering how can I do the same thing with log4j?

Thanks!

like image 918
Mathieu Avatar asked Jun 22 '11 18:06

Mathieu


1 Answers

Ok I found how to do this thanks to this post: Log4J Custom Fields

Basically, I use the MDC to add my custom fields, like this:

MDC.put("Application", application);

And in my config file, I use %X{property_name} to get the value. like this:

<layout class="org.apache.log4j.PatternLayout"> 
    <param name="ConversionPattern" 
      value="INSERT INTO errorlogs (Date, log_level, Application, Message, Exception) VALUES (TIMESTAMP(now()),'%p', '%X{Application}' '%m', '%e' )"
    /> 
</layout> 
like image 64
Mathieu Avatar answered Oct 09 '22 18:10

Mathieu