简体   繁体   English

Log4j动态参数

[英]Log4j Dynamic Parameter

i have a j2ee web application running on spring framework and using log4j for logging. 我有一个运行在spring框架上并使用log4j进行记录的j2ee Web应用程序。 I have this line in my log4j.properties file. 我的log4j.properties文件中有这一行。 this will insert the logs in my database. 这会将日志插入到我的数据库中。 How do I set a dynamic value in the message part so that I can somehow append the currently logged in user. 如何在消息部分中设置动态值,以便可以以某种方式附加当前登录的用户。 The bean object containing info for the current user is in the application context. 包含当前用户信息的Bean对象位于应用程序上下文中。

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

You want to use the MDC (Mapped diagnostic context). 您要使用MDC (映射的诊断上下文)。 Here's a link about using it with servlets. 这是有关将其与servlet一起使用的链接

I'm not entirely certain on the "application context" vs the location of my "user info" but my web app was using Struts and log4j and I had a similar (but maybe simpler) requirement, I solved it with code like this: 我不确定“应用程序上下文”和“用户信息”的位置,但是我的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
}

} }

And then in my log4j properties file I had an entry like this: 然后在我的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

And then the result was that my my table row would have data like this: 然后结果是我的表行将具有如下数据:

'2010-03-15 21:49:46,514', 'mysql', 'DEBUG', 'User: ben logged off' '2010-03-15 21:49:46,514','mysql','DEBUG','User:ben注销

I hope this helps 我希望这有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM