2010-03-23 58 views
0

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

log4j.appender.dbLog.sql = INSERT INTO 测井(LOG_DATE,LOG_LEVEL, 位置,消息)VALUES ( '%d {YYYY/MM/DD hh:mm:ss的}',“% -5p”, '%C-%L', '%M')

回答

1

我并不完全确定“应用程序上下文”与我的“用户信息”的位置,但我的Web应用程序使用的是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:46514', 'mysql的', 'DEBUG', '用户名:奔注销'

我希望这有助于

2

要使用的MDC(映射诊断上下文)。以下是关于在servlet中使用它的link