Search code examples
javadynamiclog4jparametersmdc

Log4j Dynamic Parameter


i have a j2ee web application running on spring framework and using log4j for logging. I have this line in my log4j.properties file. 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.

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')


Solution

  • 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:

    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.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'

    I hope this helps