本文介绍了在 log4j JDBCAppender 中保存额外的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在我的日志表中存储额外的值,例如将用户 ID 存储在单独的列中.有人知道我该怎么做吗?
I would like to store extra values in my log table, for example storing the user ID in a separate column. Does anybody have any idea how I can do this?
这是我的配置:
<appender name="jdbcAppender" class="org.apache.log4j.jdbc.JDBCAppender">
<param name="URL" value="jdbc:sqlite:D:/download/mapLogic/sf_log.db" />
<param name="user" value="" />
<param name="password" value="" />
<param name="driver" value="org.sqlite.JDBC" />
<param name="sql"
value="INSERT INTO sf_log(Message,Priority,Logger,Date) VALUES ('%m','%p','%c','%d{ABSOLUTE}')" />
</appender>
谢谢
推荐答案
您可以在 MDC 然后把它用在你的插入语句中.
You could maintain the user in an MDC and then put use it in your insert statement.
MDC.put("user", userid);
try {
doTheActualWorkWhichWillUseLogger();
} finally {
// need to remove this to avoid causing leaks
MDC.remove("user");
}
注意,您不必为每个 logger
调用执行此操作,只需一次,但我放入了 remove
以说明如果要使用它在 Servlet 中,您必须在完成调用后再次清除 MDC
.
Note, you wouldn't have to do this for each logger
call, just once, but I put in the remove
to illustrate that if this were to be used in a Servlet, you'd have to clear the MDC
again once you're finished with the call.
然后对于您的插入语句:
And then for your insert statement:
INSERT INTO sf_log (Message,Priority,Logger,Date, user)
VALUES ('%m','%p','%c','%d{ABSOLUTE}', '%X{user}')
这篇关于在 log4j JDBCAppender 中保存额外的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!