【问题标题】:log4j2 patternlayout for columnmapping not working列映射的 log4j2 模式布局不起作用
【发布时间】:2018-12-18 04:09:27
【问题描述】:

我对 JDBC appender 的 log4j2 配置有问题。 我有一个很好的工作示例,带有用于快速测试的简单驱动程序管理器连接。

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

从 java 代码我做这样的事情:

//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));

一切正常,地图条目保存到数据库中的匹配列。但是后来,我尝试了另一种配置,改变了

<ColumnMapping name="user_id" />

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

正如我从文档(JDBCAppenderPatternLayout docs)中了解到的那样 - 按键获取 MapMessage 的值,在大括号之间指定。但是这种类型的配置看起来不起作用,因为在 DB 中,我在“user_id”列中只收到空字符串。我在配置中打开了跟踪模式,并在日志中看到在准备 sql 语句时 JDBCAppender 确实将空字符串作为“user_id”列的值。但我打破了我的头,试图理解为什么。特别是考虑到,最初配置为pattern="%d{UNIX_MILLIS}" 的“date_time”列映射接收到正确的时间戳值。

【问题讨论】:

    标签: java log4j2


    【解决方案1】:

    自己找到了解决方案。当我开始使用 MapMessage 的特定实现时,一切都开始按预期工作,例如:

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

    【讨论】:

      【解决方案2】:

      在你的xml配置文件中,写成:

      <ColumnMapping name="db_column1" pattern="${msg1}"/>
      

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

      在你的java代码中,写成:

      StringMapMessage map = new StringMapMessage();
      map.put("msg1", "db column value");
      logger.debug(map);
      

      应该没问题。

      【讨论】:

        猜你喜欢
        • 2018-12-19
        • 1970-01-01
        • 1970-01-01
        • 2021-08-19
        • 1970-01-01
        • 2014-04-22
        • 1970-01-01
        • 1970-01-01
        • 2018-09-15
        相关资源
        最近更新 更多