java - 将动态值传递给 log4j2 xml 配置

标签 java logging log4j log4j2

我正在尝试使用 log4j2 编写一个日志记录模块,该模块需要将日志以 json 的形式写入控制台 STDOUT。

为此,我尝试使用 JSON 形式的 PatternLayout,如下所示。

在编写日志时,将代码中的值动态传递到 log4j2.xml 配置文件以在运行时替换它们时遇到一些困难。

我尝试使用 StructuredDataMessage 和 MapMessages 来替换 https://logging.apache.org/log4j/2.0/manual/lookups.html 中提到的 Map 中的值。 .

我也尝试过 StrLookup 和 ContextMaplookup,但到目前为止没有成功。

Below is my xml config

    <?xml version="1.0" encoding="UTF-8"?>
    <Configuration status="WARN" name="App" packages="com.test.common.logging">
        <Properties>
            <Property name="filename">target/rolling1/rollingtest.log</Property>
            <Property name="maptype">$${map:type}</Property>

        </Properties>

        <ThresholdFilter level="debug"/>

        <Appenders>
            <Console name="Console" target="SYSTEM_OUT">
              <PatternLayout pattern="%highlight{{'logged time': '%d{dd MMM yyyy HH:mm:ss}', 
            'LEVEL' : '%level',
            'CLASS' : '%c{-1}',
            'Module' : '[%t]',
            'message' : '%m',
            'error' : '%exception',
            'class' : '%C',
            'threadid' : '%tid',
            'threadname' : '%thread',
            'whatisthis' : '${filename}',
            'processid' : '%pid', 
            'logdir' : '$${sd:type}'
            'location' : '${log4j:configLocation}'
            'systemproperty' : '$${ctx:key-}'
            }}%n"/>
            </Console>
        </Appenders>

        <Loggers>
            <Root level="trace">
                <AppenderRef ref="Console"/>
            </Root>
        </Loggers>

    </Configuration>

下面是我的代码,我尝试使用结构化数据消息、strlookup 和 mapmessage 传递动态值

public class App 
{


    public static void main( String[] args )
    {
        Logger logger = LogManager.getLogger(App.class);

//      ConfigurationBuilder<BuiltConfiguration> builder
//       = ConfigurationBuilderFactory.newConfigurationBuilder();
//      
//      LayoutComponentBuilder standard 
//        = builder.newLayout("PatternLayout");
//      standard.
//      
        System.out.println( "Hello World!" );
        StructuredDataMessage message = new StructuredDataMessage("1", "name", "string");
        message.put("1", "nme");
       // MapMessage mapm = new MapMessage(map)
        MapMessage map = new MapMessage();
        map.put("type", "value");
        map.put("key", "value");
        map.put("name", "arun");
        StrLookup strlook = new StrLookup() {

            public String lookup(LogEvent event, String key) {
                // TODO Auto-generated method stub
                return null;
            }

            public String lookup(String key) {
                // TODO Auto-generated method stub

                return "value";
            }
        };
        ContextMapLookup lookup = new ContextMapLookup();
        System.out.println(lookup.lookup("key"));
        System.out.println(strlook.lookup("key"));

       // MapLookup.setMainArguments(args);

        System.setProperty("log_dir", App.class.getSimpleName());;
        logger.trace("trace log message");
        logger.debug("Debug log message");
        logger.info("Info log message");
        logger.error("Error log message");
        logger.fatal("Fatal log message");
        logger.info("Info log message[]");
        logger.error("null exception[]", new NullPointerException());

        // Lay

    }
}

我的输出:

Hello World!
null
value
[36m{'logged time': '24 Aug 2018 12:32:51',    'LEVEL' : 'DEBUG',   'CLASS' : 'test.common.logging.App',   'Module' : '[main]',   'message' : 'Debug log message',   'error' : '',   'class' : 'com.test.common.logging.App',   'threadid' : '1',   'threadname' : 'main',   'whatisthis' : 'target/rolling1/rollingtest.log',   'processid' : 'DEBUGid',    'logdir' : '${sd:type}'   'location' : '/Users/parunkarthick/ferry-commons/common/logging/target/classes/log4j2.xml'   'systemproperty' : '${ctx:key}'   [m}
[32m{'logged time': '24 Aug 2018 12:32:51',    'LEVEL' : 'INFO',   'CLASS' : 'test.common.logging.App',   'Module' : '[main]',   'message' : 'Info log message',   'error' : '',   'class' : 'com.test.common.logging.App',   'threadid' : '1',   'threadname' : 'main',   'whatisthis' : 'target/rolling1/rollingtest.log',   'processid' : 'INFOid',    'logdir' : '${sd:type}'   'location' : '/Users/parunkarthick/ferry-commons/common/logging/target/classes/log4j2.xml'   'systemproperty' : '${ctx:key}'   [m}
[1;31m{'logged time': '24 Aug 2018 12:32:51',    'LEVEL' : 'ERROR',   'CLASS' : 'test.common.logging.App',   'Module' : '[main]',   'message' : 'Error log message',   'error' : '',   'class' : 'com.test.common.logging.App',   'threadid' : '1',   'threadname' : 'main',   'whatisthis' : 'target/rolling1/rollingtest.log',   'processid' : 'ERRORid',    'logdir' : '${sd:type}'   'location' : '/Users/parunkarthick/ferry-commons/common/logging/target/classes/log4j2.xml'   'systemproperty' : '${ctx:key}'   [m}
[1;31m{'logged time': '24 Aug 2018 12:32:51',    'LEVEL' : 'FATAL',   'CLASS' : 'test.common.logging.App',   'Module' : '[main]',   'message' : 'Fatal log message',   'error' : '',   'class' : 'com.test.common.logging.App',   'threadid' : '1',   'threadname' : 'main',   'whatisthis' : 'target/rolling1/rollingtest.log',   'processid' : 'FATALid',    'logdir' : '${sd:type}'   'location' : '/Users/parunkarthick/ferry-commons/common/logging/target/classes/log4j2.xml'   'systemproperty' : '${ctx:key}'   [m}
[32m{'logged time': '24 Aug 2018 12:32:51',    'LEVEL' : 'INFO',   'CLASS' : 'test.common.logging.App',   'Module' : '[main]',   'message' : 'Info log message[]',   'error' : '',   'class' : 'com.test.common.logging.App',   'threadid' : '1',   'threadname' : 'main',   'whatisthis' : 'target/rolling1/rollingtest.log',   'processid' : 'INFOid',    'logdir' : '${sd:type}'   'location' : '/Users/parunkarthick/ferry-commons/common/logging/target/classes/log4j2.xml'   'systemproperty' : '${ctx:key}'   [m}
[1;31m{'logged time': '24 Aug 2018 12:32:51',    'LEVEL' : 'ERROR',   'CLASS' : 'test.common.logging.App',   'Module' : '[main]',   'message' : 'null exception[]',   'error' : ' java.lang.NullPointerException
    at com.test.common.logging.App.main(App.java:69)
',   'class' : 'com.test.common.logging.App',   'threadid' : '1',   'threadname' : 'main',   'whatisthis' : 'target/rolling1/rollingtest.log',   'processid' : 'ERRORid',    'logdir' : '${sd:type}'   'location' : '/Users/parunkarthick/ferry-commons/common/logging/target/classes/log4j2.xml'   'systemproperty' : '${ctx:key}'   [m}

如果您看到最后一个值系统属性未按预期通过代码值替换来反射(reflect)。

最佳答案

我认为您对 log4j2 有一些根本性的误解。我认为最好的做法是提供一些示例代码并解释输出,而不是尝试列出我在代码中看到的所有问题。我想当你看到一些工作代码时你就会明白哪里出了问题。

出于本示例的目的,我通过删除看似有效的元素并重点关注那些无效的元素来简化您的 log4j2 配置文件。我改变了PatternLayout到以下内容:

<PatternLayout pattern="{'LEVEL' : '%level', 'typeFromStructMsg' : '${sd:type}', 'contextValue' : '${ctx:myContextKey}', 'nameFromMapMsg' : '${map:name}', 'mySysProperty' : '${sys:mySysProperty}'}%n" />

我还修改了App您提供的类(class):

package example;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
import org.apache.logging.log4j.message.MapMessage;
import org.apache.logging.log4j.message.StringFormattedMessage;
import org.apache.logging.log4j.message.StringMapMessage;
import org.apache.logging.log4j.message.StructuredDataMessage;


public class App {

    private static final Logger logger = LogManager.getLogger();

    public static void main( String[] args )
    {
        ThreadContext.put("myContextKey", "myContextValue");

        StructuredDataMessage structMsg = new StructuredDataMessage("1", "name", "string");

        StringMapMessage mapMsg = new StringMapMessage();
        mapMsg.put("name", "arun");

        System.setProperty("mySysProperty", "sys prop value");

        logger.info(mapMsg);
        logger.warn(structMsg);

        logger.error("Error log message");
    }
}

App运行类后,会生成以下控制台输出:

{'LEVEL' : 'INFO', 'typeFromStructMsg' : '${sd:type}', 'contextValue' : 'myContextValue', 'nameFromMapMsg' : 'arun', 'mySysProperty' : 'sys prop value'}
{'LEVEL' : 'WARN', 'typeFromStructMsg' : 'string', 'contextValue' : 'myContextValue', 'nameFromMapMsg' : '${map:name}', 'mySysProperty' : 'sys prop value'}
{'LEVEL' : 'ERROR', 'typeFromStructMsg' : '${sd:type}', 'contextValue' : 'myContextValue', 'nameFromMapMsg' : '${map:name}', 'mySysProperty' : 'sys prop value'}

请注意,在输出的第一行中我们看到:'nameFromMapMsg' : 'arun'而在其他行中我们看到: 'nameFromMapMsg' : '${map:name}'

第一行输出是由这行代码生成的:logger.info(mapMsg);它传递 MapMessage 的实例叫mapMsginfo方法。由于该消息是 MapMessage 的实例它包含一个名为 name 的 key map 查找将替换 ${map:name}以及它为 name 找到的值消息中的键。这就是为什么只有第一行输出显示 'nameFromMapMsg' : 'arun' - 其他输出行是从不是 MapMessage 实例的消息生成的。 .

同样,请注意在输出的第二行中我们如何看到 'typeFromStructMsg' : 'string' 。这是因为日志是从 StructuredDataMessage 生成的。 ,它是用“字符串”类型定义的:

StructuredDataMessage structMsg = new StructuredDataMessage("1", "name", "string");

在输出的其他行中,我们没有传递 StructuredDataMessage所以在这些行中我们看到 'typeFromStructMsg' : '${sd:type}'因为 log4j2 找不到该类型的值。

最后,请注意在所有输出行中我们如何看到:'mySysProperty' : 'sys prop value' 。这是因为系统属性查找不依赖于传递给记录器的消息类型。此查找始终能够找到系统属性 mySysProperty 的值。因为我们定义了它:

System.setProperty("mySysProperty", "sys prop value");

而且,正如我之前所说,系统属性独立于消息(它们不存储在消息中)。

'contextValue' : 'myContextValue' 也是如此。 - ThreadContext与消息无关,因为我们为此键定义了一个值:

ThreadContext.put("myContextKey", "myContextValue");

无论发送到记录器的消息类型如何,查找始终能够找到该值。

我希望这个示例代码有助于说明如何使用一些查找以及如何设计 log4j2 的架构。祝你好运!

关于java - 将动态值传递给 log4j2 xml 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52001302/

相关文章:

linux - 在 Linux 中 : Print last line of log file that starts with

java - 错误无法实例化类 [org.apache.log4j.rolling.RollingFileAppender]

java - 无法在 Linux 服务器上启动或停止 Tomcat

java - 为什么 Log4j 需要类名?

java - Spring Controller 未创建为单例

java - 属性文件中的 @TestPropertySource 和 UTF-8 支持

azure - 如何将秒转换为格式 HH :mm:ss in Kusto

python - 如何通知python日志记录处理程序可能发生崩溃并应刷新日志?

java - 从camel属性占位符填充java.util.Properties

java - 带有嵌套字段的Spring数据查询(连接其他列)