Reputation: 170
I have a java app using log4j2 that connects to two different mysql instances (one storing encrypted data, one storing decrypted data), each using multiple schemas. I'm trying to implement the Log4J2 JDBC Appender to log errors with a particular marker to the relevant database schema.
I've run into a roadblock however, trying to dynamically assign the schema name to the logger. Here's my log4j2.xml config:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" dest="out" name="default">
<Appenders>
...
<JDBC name="decryptedMySQLDatabase" tableName="LogTable">
<DriverManager connectionString="jdbc:mysql://decryptedmysqldb.testdomain.com/${ctx:migration.encrypted-connection:-n/a}" driverClassName="com.mysql.jdbc.Driver" userName="${env:MYSQL_USERNAME:-sometestuser}" password="${env:MYSQL_PW:-sometestpass}" />
<Filters>
<MarkerFilter marker="TEST_MARKER_DECRYPTED" onMatch="ACCEPT" onMismatch="DENY"/>
</Filters>
<Column name="level" pattern="%level" />
<Column name="logger" pattern="%logger" />
<Column name="message" pattern="%message" />
<Column name="exception" pattern="%ex{full}" />
<Column name="lastUpdated" isEventTimestamp="true" />
</JDBC>
<JDBC name="encryptedMySQLDatabase" tableName="LogTable">
<DriverManager connectionString="jdbc:mysql://encryptedmysqldb.testdomain.com/${ctx:migration.encrypted-connection:-n/a}" driverClassName="com.mysql.jdbc.Driver" userName="${env:MYSQL_UNAME:-sometestuser}" password="${env:MYSQL_PASSWORD:-sometestpass}" />
<Filters>
<MarkerFilter marker="TEST_MARKER_ENCRYPTED" onMatch="ACCEPT" onMismatch="DENY"/>
</Filters>
<Column name="level" pattern="%level" />
<Column name="logger" pattern="%logger" />
<Column name="message" pattern="%message" />
<Column name="exception" pattern="%ex{full}" />
<Column name="lastUpdated" isEventTimestamp="true" />
</JDBC>
</Appenders>
<Loggers>
<Root level="${env:LOG_LEVEL:-info}" additivity="false">
<AppenderRef ref="console" />
<AppenderRef ref="decryptedMySQLDatabase" />
<AppenderRef ref="encryptedMySQLDatabase" />
</Root>
</Loggers>
I've added the values to the ThreadContext in a way that is working for other ctx keys in this template, but I can't get it to pick up this specific value in the connectionString property of the DriverManager config. Is there something stupid I'm missing here?
Upvotes: 1
Views: 571
Reputation: 9141
The appenders are going to be created when the log4j configuration is read when logging is initialized and try to establish a connection to the database at that time. Unless you are controlling the logging initialization, using the ThreadContextLookup is not going to work since the ThreadContext will not have any data in it during initialization.
You could try using the RoutingAppender for this but you need to be careful with this as it could result in many database connections being created to the database.
Upvotes: 2