Saving extra values in log4j JDBCAppender

余生长醉 提交于 2019-11-30 18:27:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!