将动态值传递到log4j2 xml配置

j13ufse2  于 6个月前  发布在  其他
关注(0)|答案(2)|浏览(58)

我正在尝试使用log4j2编写一个日志模块,需要将日志以json的形式写入控制台STDOUT。
为此,我尝试使用JSON格式的PatternLayout,如下所示。
我在将值从代码动态传递到log4j2.xml配置文件以在运行时编写日志时替换它们时遇到了一些困难。
我尝试使用StructuredDataMessage和MapMessages来替换https://logging.apache.org/log4j/2.0/manual/lookups.html中提到的Map中的值。
我也试过Stringdom和ContextMaplookup,但到目前为止还没有成功。
下面是我的xml配置

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


如果您看到lastvalue系统属性没有通过从代码值替换而按预期反映。

rbpvctlc

rbpvctlc1#

我认为你对log4j 2有一些基本的误解。与其我试图列出我在你的代码中看到的所有问题,我认为最好的办法是我提供一些示例代码并解释输出。我想当你看到一些工作代码时,你会明白你错在哪里。
为了这个例子的目的,我简化了log4j 2配置文件,删除了看起来工作正常的元素,并专注于那些不工作的元素。我将PatternLayout更改为以下内容:

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

字符串
我还修改了你提供的App类:

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);,它将一个名为mapMsgMapMessage的示例传递给info方法。由于消息是MapMessage的示例,并且它包含一个名为name的键,因此map查找将用它在这就是为什么只有第一行输出显示'nameFromMapMsg' : 'arun'-其他输出行是从不是MapMessage示例的消息生成的。
类似地,请注意在输出的第二行中,我们看到了'typeFromStructMsg' : 'string'。这是因为日志是从StructuredDataMessage生成的,StructuredDataMessage定义为“string”类型:
StructuredDataMessage structMsg = new StructuredDataMessage("1", "name", "string");
在输出的其他行中,我们没有传递StructuredDataMessage,所以在这些行中,我们看到'typeFromStructMsg' : '${sd:type}'是因为log4j 2找不到该类型的值。
最后,请注意在所有输出行中我们都看到了这个:'mySysProperty' : 'sys prop value'。这是因为系统属性mySysProperty不依赖于传递给记录器的消息的类型。这个查找总是能够找到系统属性mySysProperty的值,因为我们定义了它:

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


并且,正如我之前所说的,系统属性独立于消息(它们不存储在消息中)。
'contextValue' : 'myContextValue'也是如此-ThreadContext独立于消息,因为我们为这个键定义了一个值:

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


无论发送到记录器的消息的种类如何,查找总是能够找到该值。
我希望这个示例代码有助于说明如何使用一些查找以及如何设计log4j 2的架构。祝你好运!

mpbci0fu

mpbci0fu2#

在xml文件中编辑PatternLayout本身是不可行的,如果值是静态的并且保持不变,那么它就可以工作,否则你需要通过扩展内置方法来实现自定义模式,然后相应地格式化你的消息。下面的链接将让你知道同样的事情。
https://blog.10pines.com/2020/03/02/log-custom-json-with-log4j2/

相关问题