【问题标题】:Log4j Dynamic ParameterLog4j 动态参数
【发布时间】:2010-03-23 05:36:04
【问题描述】:

我有一个在 spring 框架上运行并使用 log4j 进行日志记录的 j2ee Web 应用程序。我的 log4j.properties 文件中有这一行。这将在我的数据库中插入日志。如何在消息部分设置动态值,以便以某种方式附加当前登录的用户。包含当前用户信息的 bean 对象位于应用程序上下文中。

log4j.appender.dbLog.sql = 插入 记录(log_date,log_level, 位置,消息)值 ('%d{yyyy/MM/dd HH:mm:ss}', '%-5p', '%C-%L', '%m')

【问题讨论】:

    标签: java dynamic log4j parameters mdc


    【解决方案1】:

    您想使用MDC(映射的诊断上下文)。这是一个link,关于将它与 servlet 一起使用。

    【讨论】:

      【解决方案2】:

      我不完全确定“应用程序上下文”与“用户信息”的位置,但我的网络应用程序使用的是 Struts 和 log4j,我有类似(但可能更简单)的要求,我用代码解决了它像这样:

      public class LogoutAction extends org.apache.struts.action.Action {
      
      private Log log_db = LogFactory.getLog("mysql");
      
      public ActionForward execute(ActionMapping mapping, ActionForm form,
              HttpServletRequest request, HttpServletResponse response)
              throws Exception {
      
          log_db.debug("User: "+request.getRemoteUser()+" logged off");
          request.getSession().invalidate();
          your
      }
      

      }

      然后在我的 log4j 属性文件中,我有一个这样的条目:

      log4j.logger.mysql=DEBUG, mysql
      log4j.appender.mysql=org.apache.log4j.jdbc.JDBCAppender
      log4j.appender.mysql.layout=org.apache.log4j.PatternLayout
      log4j.appender.mysql.URL=jdbc:mysql://localhost:3306/dbname?autoReconnect=true
      log4j.appender.mysql.driver=com.mysql.jdbc.Driver
      log4j.appender.mysql.user=user
      log4j.appender.mysql.password=password
      log4j.appender.mysql.sql=INSERT INTO log (Date, Logger, Priority, Message) VALUES ("%d","%c","%p","%m")
      enter code here
      

      然后结果是我的表行会有这样的数据:

      '2010-03-15 21:49:46,514', 'mysql', 'DEBUG', '用户:本已注销'

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 2014-06-30
        • 2017-06-15
        • 2012-06-21
        • 1970-01-01
        • 2016-12-07
        • 2011-06-03
        • 2012-08-04
        • 2019-11-03
        • 2016-09-15
        相关资源
        最近更新 更多