log4j2 patternlayout for columnmapping not working

喜你入骨 提交于 2019-12-11 06:58:42

问题


I have a problem with log4j2 configuration of JDBC appender. I have very well working example with simple driver manager connection for quick tests.

<JDBC name="DBLogger" tableName="db_logs" ignoreExceptions="false">
    <DriverManager
         connectionString="jdbc:mysql://localhost:3306/twib"
         userName="****"
         password="****"
         driverClassName="com.mysql.jdbc.Driver"
         />

    <ColumnMapping name="date_time" pattern="%d{UNIX_MILLIS}" />
    <ColumnMapping name="user_id" />
    <ColumnMapping name="session_id" />
    <ColumnMapping name="user_ip" />
    <ColumnMapping name="user_agent" />
    <ColumnMapping name="device_info" />
    <ColumnMapping name="device_id" />
    <ColumnMapping name="device_mac" />
    <ColumnMapping name="device_imei" />
    <ColumnMapping name="device_imsi" />
    <ColumnMapping name="request_name" />
    <ColumnMapping name="request_xml" />
    <ColumnMapping name="response_xml" />
    <MessageLayout />
</JDBC>

From java code I do something like that:

//get logger instance
Logger dbLogger = LogManager.getLogger("DBLogger");
//create map for map message 
HashMap map = new HashMap();
//fill in map with values
map.put("user_id", "...");
//...here go other map fields
map.put("response_xml", "...");
//log the map message with logger to DB
dbLogger.debug(new MapMessage(map));

Everything works fine, map entries are saved to matching columns in DB. But then, I try another configuration, changing

<ColumnMapping name="user_id" />

to

<ColumnMapping name="user_id" pattern="%K{user_id}"/>

which as I understood from the docs (JDBCAppender, PatternLayout docs) works similar - takes value of MapMessage by key, specified between braces. But this type of configuring looks like not working, because in DB I receive only empty strings in "user_id" column. I turned on trace mode on configuration, and see in logs that when preparing sql statement JDBCAppender really puts empty string as value for "user_id" column. But I broke my head, trying to understand why. Especially considering, that "date_time" column mapping, which was at first configured with pattern="%d{UNIX_MILLIS}", receives correct timestamp value.


回答1:


Found the solution myself. All started working as expected when I began using specific implementation of MapMessage, for example:

StringMapMessage map = new StringMapMessage();
map.put("user_id", "...");
//...here go other map fields
map.put("response_xml", "...");
//log the map message with logger to DB
dbLogger.debug(map);


来源:https://stackoverflow.com/questions/51263090/log4j2-patternlayout-for-columnmapping-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!