Log4j数据库附加器 [英] Log4j database appender
问题描述
我希望log4j将我的错误记录在MySql数据库中,但是关于此的官方文档非常稀疏(为什么?). 无论如何,这是我尝试的log4j.xml配置文件:
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>
我需要自定义应用程序"参数.在C#中使用log4net,在我的代码中,我会这样添加它:
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;
并将其添加到我的xml配置文件中:
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>
我想知道如何用log4j做同样的事情?
I was wondering how can I do the same thing with log4j?
谢谢!
推荐答案
Ok I found how to do this thanks to this post: Log4J Custom Fields
基本上,我使用MDC添加我的自定义字段,如下所示:
Basically, I use the MDC to add my custom fields, like this:
MDC.put("Application", application);
在我的配置文件中,我使用%X {property_name}来获取值.像这样:
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>
这篇关于Log4j数据库附加器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!