英文:
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 :
<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>
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 = "LogInterceptor", category = "Core", elementType = "rewritePolicy", printObject = true)
public class LoggingMaskingConverter implements RewritePolicy {
protected static final Logger log = LogManager.getLogger(LoggingMaskingConverter.class);
private static final List<String> loggingSetting = Arrays.asList("pin,password".split(","));
private static final String loggingMasking = "1";
private static final List<String> excludePath = Collections.emptyList();
private static final String STR_BODY = "body=[";
Properties prop = new Properties();
@PluginFactory
public static LoggingMaskingConverter createPolicy() {
return new LoggingMaskingConverter();
}
@Override
public LogEvent rewrite(LogEvent event) {
if (event.getLoggerName().contains("com.project")) {
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) && loggingMasking.equalsIgnoreCase("1")) {
if (body != null) {
Collection<String> whitelist = loggingSetting;
Collection<String> 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() + "]");
}
} else {
String json = ow.writeValueAsString(body);
stringBuilder.append(STR_BODY + json + "]");
}
} 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:
<parent_component_prefix>.<arbitrary_id>.type = ComponentType
<parent_component_prefix>.<arbitrary_id>.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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论