Tomasz Dzięcielewski
Tomasz Dzięcielewski

Reputation: 3907

Log4j2 MDC configuration for JDBC appender

I have log4j2.xml file:

<Console name="Console" target="SYSTEM_OUT">
   <PatternLayout
            pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %X{userId} %-5level %logger{36}: %msg%n" />
</Console>

and there is %X{userId} part which allows me to display something from MDC (Thread Context).

I have similar configuration for JDBC:

<JDBC name="sqlServer" tableName="dbo.application_log">
        <ConnectionFactory
            class="mbms.configuration.Log4j2ConnectionFactory"
            method="getConnection" />
        <Column name="eventDate" isEventTimestamp="true" />
        <Column name="level" pattern="%level" />
        <Column name="logger" pattern="%logger" />
        <Column name="user" pattern="%X{userId}" />
        <Column name="message" pattern="%message" />
        <Column name="exception" pattern="%ex{full}" />
</JDBC>

And it's not working. When I comment out user, logs are stored in database, but when it's there I got exception:

Caused by: java.sql.BatchUpdateException: Incorrect syntax near the keyword 'user'.
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeBatch(SQLServerPreparedStatement.java:2065)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(NewProxyPreparedStatement.java:2544)
at org.apache.logging.log4j.core.appender.db.jdbc.JdbcDatabaseManager.commitAndClose(JdbcDatabaseManager.java:532)
... 108 more

Do you know how I can use %X{userId} to store this information in MS SQL database?

Upvotes: 0

Views: 1038

Answers (2)

Tomasz Dzięcielewski
Tomasz Dzięcielewski

Reputation: 3907

I've found a solution: user and level are SQL reserved keywords, changing it from user to usr and level to lvl solved the issue and now I've got logs in database.

Upvotes: 1

A Le Dref
A Le Dref

Reputation: 452

I guess you push in the DB upon each log ? Then when you push it is possible that it does not goes into the local thread to find the user id value ?

Are you pushing manually to the DB ?

Upvotes: 0

Related Questions