问题
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?
Here's my configuration:
<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>
Thank you
回答1:
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");
}
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}')
来源:https://stackoverflow.com/questions/9923463/saving-extra-values-in-log4j-jdbcappender