如何将Log4j.xml转换为Log4j2.properties(重写策略)

huangapple go评论76阅读模式
英文:

How to convert Log4j.xml to Log4j2.properties (Rewrite Polici)

问题

我想使用“Rewrite Policy”来处理日志中的某些条件,比如掩码,然后我在log4j2.xml中找到了解决方案,但我们通常使用log4j2.properties来进行基本配置,我已经尝试配置了,但重写仍然不起作用。

其他配置如下:

<Configuration status="warn" name="MyApp" packages="">
  <Properties>
    <Property name="LOG_DIR">/logs</Property>
  </Properties>

  <Appenders>
    <RollingFile
      name="rollingFile"
      fileName="D:/logs/omnichannel/application.log"
      filePattern="D:/logs/omnichannel/application.%i.log.gz"
      ignoreExceptions="false">
      <PatternLayout>
          <Pattern>%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n</Pattern>
      </PatternLayout>
      <Policies>
          <SizeBasedTriggeringPolicy size="10MB" />
      </Policies>
      <DefaultRolloverStrategy max="5">
        <Delete basePath="D:/logs/" maxDepth="2">
          <IfFileName glob="*/app-*.log.gz" />
          <IfLastModified age="P30D" />
        </Delete>
      </DefaultRolloverStrategy>
    </RollingFile>
     <Console name="STDOUT" target="SYSTEM_OUT" ignoreExceptions="false">
      <PatternLayout pattern="%m%n"/>
    </Console>
    <Rewrite name="Rewrite">
      <LogInterceptor />
      <AppenderRef ref="rollingFile"/>
    </Rewrite>
  </Appenders>

  <Loggers>
    <Root level="info">
      <AppenderRef ref="Rewrite"/>
    </Root>
  </Loggers>
</Configuration>

而我的配置如下:

status = warn
name= PropertiesConfig

# 指定存储日志文件的目录路径
property.basePath = D://logs//

appenders = rolling, console, Rewrite 

appender.Rewrite.type = Rewrite
appender.Rewrite.name = Rewrite
appender.Rewrite.layout.type = LogInterceptor
appender.Rewrite.layout.RewriteAppender = fileLogger

# ConsoleAppender 会将日志打印到控制台
appender.console.type = Console
appender.console.name = consoleLogger
appender.console.target = SYSTEM_OUT
appender.console.layout.type = PatternLayout
# 指定日志的格式
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %highlight{[%-5level]}{TRACE=magenta} %mask %logger{36}.%M(%L) : %msg%n%throwable
appender.console.layout.disableAnsi=false

# RollingFileAppender 会将日志记录到文件中,并根据时间或大小进行轮换
appender.rolling.type = RollingFile
appender.rolling.name = fileLogger
appender.rolling.fileName = ${basePath}${hostName}.log
appender.rolling.filePattern = ${basePath}${hostName}_%d{yyyy-MM-dd}-%i.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern =  %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%-5level] %logger{36}.%M(%L) : %msg%n%throwable
appender.rolling.policies.type = Policies

# 每天轮换日志文件,并保留30天的日志
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.action.type = Delete
appender.rolling.strategy.action.basePath = ${basePath}
appender.rolling.strategy.action.maxDepth = 1
appender.rolling.strategy.action.ifLastModified.type = IfLastModified
appender.rolling.strategy.fileIndex = nomax

loggers = application, httpclient, Client

# 指定要记录的包名。此包及其子包中的类将使用ConsoleAppender和RollingFileAppender记录日志
logger.application.name = com.project
logger.application.level = info
logger.application.appenderRefs = rolling
logger.application.appenderRef.rolling.ref = fileLogger

logger.httpclient.name = org.apache.http
logger.httpclient.level = info
logger.httpclient.appenderRefs = rolling
logger.httpclient.appenderRef.rolling.ref = fileLogger

logger.Client.name = com.sun.jersey.api
logger.Client.level = info
logger.Client.appenderRefs = rolling
logger.Client.appenderRef.rolling.ref = fileLogger

rootLogger.level = info
rootLogger.appenderRefs = Rewrite
rootLogger.appenderRef.Rewrite.ref = Rewrite

请注意,重写策略在上述配置中使用了<Rewrite>标签,而您的配置使用了appender.Rewrite来定义它。您需要确保您的配置文件与示例中的格式一致,才能使重写策略正常工作。希望这有助于解决您的问题。如果您仍然遇到问题,请提供更多详细信息以便进一步帮助您。

英文:

i want to use Rewrite Policy for some condition in logging like masking, and then I found the solution but in log4j2.xml, however we use log4j2.properties for base config, I already try to config but the rewrite still not working.

here other config compare to my config

Other Config :

&lt;Configuration status=&quot;warn&quot; name=&quot;MyApp&quot; packages=&quot;&quot;&gt;
  &lt;Properties&gt;
    &lt;Property name=&quot;LOG_DIR&quot;&gt;/logs&lt;/Property&gt;
  &lt;/Properties&gt;

  &lt;Appenders&gt;
    &lt;RollingFile
      name=&quot;rollingFile&quot;
      fileName=&quot;D:/logs/omnichannel/application.log&quot;
      filePattern=&quot;D:/logs/omnichannel/application.%i.log.gz&quot;
      ignoreExceptions=&quot;false&quot;&gt;
      &lt;PatternLayout&gt;
          &lt;Pattern&gt;%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n&lt;/Pattern&gt;
      &lt;/PatternLayout&gt;
      &lt;Policies&gt;
          &lt;SizeBasedTriggeringPolicy size=&quot;10MB&quot; /&gt;
      &lt;/Policies&gt;
      &lt;DefaultRolloverStrategy max=&quot;5&quot;&gt;
        &lt;Delete basePath=&quot;D:/logs/&quot; maxDepth=&quot;2&quot;&gt;
          &lt;IfFileName glob=&quot;*/app-*.log.gz&quot; /&gt;
          &lt;IfLastModified age=&quot;P30D&quot; /&gt;
        &lt;/Delete&gt;
      &lt;/DefaultRolloverStrategy&gt;
    &lt;/RollingFile&gt;
     &lt;Console name=&quot;STDOUT&quot; target=&quot;SYSTEM_OUT&quot; ignoreExceptions=&quot;false&quot;&gt;
      &lt;PatternLayout pattern=&quot;%m%n&quot;/&gt;
    &lt;/Console&gt;
    &lt;Rewrite name=&quot;Rewrite&quot;&gt;
      &lt;LogInterceptor /&gt;
      &lt;AppenderRef ref=&quot;rollingFile&quot;/&gt;
    &lt;/Rewrite&gt;
  &lt;/Appenders&gt;

  &lt;Loggers&gt;
    &lt;Root level=&quot;info&quot;&gt;
      &lt;AppenderRef ref=&quot;Rewrite&quot;/&gt;
    &lt;/Root&gt;
  &lt;/Loggers&gt;

&lt;/Configuration&gt;

And my config here :

status = warn
name= PropertiesConfig

# Give directory path where log files should get stored
property.basePath = D://logs//

appenders = rolling, console, Rewrite 

appender.Rewrite.type = Rewrite
appender.Rewrite.name = Rewrite
appender.Rewrite.layout.type = LogInterceptor
appender.Rewrite.layout.RewriteAppender = fileLogger

# ConsoleAppender will print logs on console
appender.console.type = Console
appender.console.name = consoleLogger
appender.console.target = SYSTEM_OUT
appender.console.layout.type = PatternLayout
# Specify the pattern of the logs
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %highlight{[%-5level]}{TRACE=magenta} %mask %logger{36}.%M(%L) : %msg%n%throwable
appender.console.layout.disableAnsi=false

# RollingFileAppender will print logs in file which can be rotated based on time or size
appender.rolling.type = RollingFile
appender.rolling.name = fileLogger
appender.rolling.fileName = ${basePath}${hostName}.log
appender.rolling.filePattern = ${basePath}${hostName}_%d{yyyy-MM-dd}-%i.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern =  %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%-5level] %logger{36}.%M(%L) : %msg%n%throwable
appender.rolling.policies.type = Policies

# Rotate log file each day and keep 30 days worth
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.action.type = Delete
appender.rolling.strategy.action.basePath = ${basePath}
appender.rolling.strategy.action.maxDepth = 1
appender.rolling.strategy.action.ifLastModified.type = IfLastModified
appender.rolling.strategy.fileIndex = nomax

# For hibernate tracing query parameter, make this default not opened
#loggers = application, hibernate
loggers = application, httpclient, Client


# Mention package name here. Classes in this package or sub packages will use ConsoleAppender and RollingFileAppender for logging         
logger.application.name = com.project
logger.application.level = info
logger.application.appenderRefs = rolling
logger.application.appenderRef.rolling.ref = fileLogger

logger.httpclient.name = org.apache.http
logger.httpclient.level = info
logger.httpclient.appenderRefs = rolling
logger.httpclient.appenderRef.rolling.ref = fileLogger

logger.Client.name = com.sun.jersey.api
logger.Client.level = info
logger.Client.appenderRefs = rolling
logger.Client.appenderRef.rolling.ref = fileLogger

# For hibernate tracing query parameter, make this default not opened
#logger.hibernate.name = org.hibernate.type
#logger.hibernate.level = trace
#Logger.hibernate.Additivity = false

# Configure root logger for logging error logs in classes which are in package other than above specified package
rootLogger.level = info
rootLogger.appenderRefs = Rewrite
rootLogger.appenderRef.Rewrite.ref = Rewrite

my function rewrite :

@Plugin(name = &quot;LogInterceptor&quot;, category = &quot;Core&quot;, elementType = &quot;rewritePolicy&quot;, printObject = true)
public class LoggingMaskingConverter implements RewritePolicy {
	
	protected static final Logger log = LogManager.getLogger(LoggingMaskingConverter.class);

	private static final List&lt;String&gt; loggingSetting = Arrays.asList(&quot;pin,password&quot;.split(&quot;,&quot;));
	
	private static final String loggingMasking = &quot;1&quot;;
	
	private static final List&lt;String&gt; excludePath = Collections.emptyList();
	
	private static final String STR_BODY = &quot;body=[&quot;;
	
	Properties prop = new Properties();
	
	 @PluginFactory
	 public static LoggingMaskingConverter createPolicy() {
		 return new LoggingMaskingConverter();
	 }
	 
	 @Override
	 public LogEvent rewrite(LogEvent event) {
		 if (event.getLoggerName().contains(&quot;com.project&quot;)) {
			 
			 Message outputMessage = logInfoMasking(event.getMessage());

		     return new Log4jLogEvent.Builder(event).setMessage(outputMessage).build();
		 } else {
			 return new Log4jLogEvent.Builder(event).build();
		 }
		
	 }
	 
	 public Message logInfoMasking(Message message) {
		 StringBuilder stringBuilder = new StringBuilder();
		 try {
			 String body = message.getFormattedMessage();
			 ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
			 if (StringUtils.isNotBlank(loggingMasking) &amp;&amp; loggingMasking.equalsIgnoreCase(&quot;1&quot;)) {
				 if (body != null) {
					 Collection&lt;String&gt; whitelist = loggingSetting;
					 Collection&lt;String&gt; excludeKeys = excludePath;
					 JsonMasker masker = new JsonMasker(whitelist, excludeKeys);
						
					 JsonNode jsonNode = new ObjectMapper().readTree(body);
					 JsonNode masked =  masker.mask(jsonNode);
					 stringBuilder.append(STR_BODY + masked.toString() + &quot;]&quot;);
				 }
			 } else {
				 String json = ow.writeValueAsString(body);
				 stringBuilder.append(STR_BODY + json + &quot;]&quot;);
			 }
				
		 } catch (JsonProcessingException e) {
			 log.error(e, e);
		 }
		 return new ObjectMessage(stringBuilder.toString());
	}
}

i spend my time around one day to solve this. until this day. the rewrite still not working in logs file but in my function rewrite going well

答案1

得分: 1

配置Log4j2组件的一般格式是通过属性进行配置的:

<parent_component_prefix>.<arbitrary_id>.type = ComponentType
<parent_component_prefix>.<arbitrary_id>.property1 = value1
...

因此,在您的情况下,您需要:

appender.$0.type = Rewrite
appender.$0.name = Rewrite

appender.$0.$1.type = LogInterceptor

appender.$0.$2.type = AppenderRef
appender.$0.$2.ref = fileLogger
英文:

The general format to configure a Log4j2 component via properties is:

&lt;parent_component_prefix&gt;.&lt;arbitrary_id&gt;.type = ComponentType
&lt;parent_component_prefix&gt;.&lt;arbitrary_id&gt;.property1 = value1
...

So in your case you need:

appender.$0.type = Rewrite
appender.$0.name = Rewrite

appender.$0.$1.type = LogInterceptor

appender.$0.$2.type = AppenderRef
appender.$0.$2.ref = fileLogger

huangapple
  • 本文由 发表于 2023年2月8日 13:04:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75381552.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定