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.D开发者_C百科river" /> 
    <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!
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> 
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论