我是java的新手,需要使用slf4j放置日志,我需要将敏感数据日志放入不同的文件中。
示例:
package in.com.my.service.here
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
public static void main( args[] ) {
Logger log = LoggerFactory.getLogger(POSServiceImpl.class);
log.info("log without MDC");
MDC.put('isEncrypted',"true");
log.info("log line 1");
log.info("log line 2");
log.info("log line 3");
MDC.clear();
log.info("log again without MDC");
}
重要提示:请提供logback.xml配置,以便当isEncrypted值为true时,MDC下的日志存储在不同的文件中。
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<timestamp key="bySecond" datePattern="yyyy-MM-dd_HHmmss" />
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n
</pattern>
</encoder>
</appender>
<appender name="ROLLING"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.folder}/terminal-${bySecond}.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${log.folder}/Archive-%d{yyyy-MM-dd}.%i.log
</fileNamePattern>
<maxFileSize>10MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>1GB</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>My ID [%X{myId}] %d{HH:mm:ss.SSS} [%thread]
%-5level %logger{5} - %msg%n</pattern>
</encoder>
</appender>
<logger name="in.com.my.service" level="debug"
additivity="false">
<appender-ref ref="ROLLING" />
<appender-ref ref="STDOUT" />
</logger>
<!-- By default, the level of the root level is set to DEBUG -->
<root level="info">
<appender-ref ref="ROLLING" />
<appender-ref ref="STDOUT" />
</root>
</configuration>
答案 0 :(得分:2)
这看起来像是Logback的SiftingAppender,javadoc的候选人。例如:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="SIFTER" class="ch.qos.logback.classic.sift.SiftingAppender">
<discriminator>
<key>encryptedStatus</key>
<defaultValue></defaultValue>
</discriminator>
<sift>
<appender name="FILE${encryptedStatus}" class="ch.qos.logback.core.FileAppender">
<file>File${encryptedStatus}.log</file>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>...</pattern>
</layout>
</appender>
</sift>
</appender>
<root level="ALL">
<appender-ref ref="SIFTER" />
</root>
</configuration>
encryptedStatus
的值将替换为日志文件名。因此,包含MDC值encryptedStatus=Sensitive
的日志事件将写入FileSensitive.log
,并且不包含名为encryptedStatus
的MDC属性的日志事件将写入File.log
。< / p>
您可能希望更改文件名的值和敏感文件的后缀等,但上面的摘录显示了如何根据MDC属性将日志事件定向到特定的日志文件。