Spring中如何通过Logback将指定日志输出到文本文件
Got it, let's adjust your Logback configuration to capture that specific integrity violation log into a file while keeping all other logs going to the console as before. Here's the modified config:
<configuration debug="true"> <!-- Keep your existing console appender for all logs --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>Hello %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <!-- New appender to write only the ProxyICA violation logs to a file --> <appender name="PROXY_ICA_VIOLATION" class="ch.qos.logback.core.FileAppender"> <!-- Set your desired file path/name here --> <file>proxy-ica-integrity-violations.log</file> <encoder> <!-- Use the same pattern as console, or customize it --> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> <!-- Filter to only keep logs matching your specific message pattern --> <filter class="ch.qos.logback.core.filter.EvaluatorFilter"> <evaluator class="ch.qos.logback.classic.boolex.JaninoEventEvaluator"> <!-- Match logs where the message follows your specific format; regex ensures precision --> <expression>message.matches("ProxyICA .* has an integrity violation.*")</expression> </evaluator> <OnMATCH>ACCEPT</OnMATCH> <OnMISMATCH>DENY</OnMISMATCH> </filter> </appender> <!-- Root logger sends all logs to console, and filtered violation logs to the file --> <root level="debug"> <appender-ref ref="STDOUT" /> <appender-ref ref="PROXY_ICA_VIOLATION" /> </root> </configuration>
Key Details:
- The
PROXY_ICA_VIOLATIONappender uses aJaninoEventEvaluatorto target exactly your log entries. The regex ensures only logs matching your "ProxyICA integrity violation" pattern get written to the file. - You can modify the
<file>tag to set your preferred storage path and filename for the violation logs. - Dependency Note: Janino is required for the expression-based filtering. If using Maven, add this to your
pom.xml:<dependency> <groupId>org.codehaus.janino</groupId> <artifactId>janino</artifactId> <version>3.1.9</version> <!-- Use the latest stable version available --> </dependency> - All regular logs will continue outputting to the console as usual, while your targeted violation logs will be duplicated to the specified file.
If you ever wanted the violation logs to only go to the file (and not the console), you could add a reverse filter to the STDOUT appender to deny those entries—but based on your request, the above config keeps them in both places as needed.
内容的提问来源于stack exchange,提问作者zakpruitt
相关产品推荐
相关产品推荐

