log4j jdbcappender pass username to database table

2019-08-02 04:25发布

问题:

I have log4j jdbcappender configuration as follows:

 <appender name="jdbcAppender" class="bean.CustomJdbcAppender">
        <param name="jndiDataSource" value="myDS"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                   value="INSERT INTO log_table (level, loc, msg) VALUES ( '%p','%C;%L', '%m' )"/>
        </layout>

How can I pass username to the database table from log4j?

Thanks

回答1:

Use the MDC (Mapped Diagnostic Context), like this example.

So, somewhere you need to map the username, e.g.:

MDC.put("username", username);

In your log4j configuration, you can use it like this:

<param name="ConversionPattern"
      value="INSERT INTO log_table (level, loc, msg, username) VALUES ( '%p','%C;%L', '%m', '%X{username}' )"/>


标签: java log4j