Logback:如何为FileAppender配置AUDIT Marker实现日志分流
Answer
Great question! You’re right that EventEvaluator implementations (like OnMarkerEvaluator) are primarily intended for appenders such as SMTPAppender that need conditional triggering logic. For FileAppender, the standard approach to filter logs by marker is to use Logback’s Filter mechanism instead.
Here’s the corrected configuration that will route only logs tagged with the AUDIT marker to your dedicated audit file:
<appender name="AUDIT_FILE" class="ch.qos.logback.core.FileAppender"> <!-- Filter to only accept logs with the AUDIT marker --> <filter class="ch.qos.logback.classic.filter.MarkerFilter"> <marker>AUDIT</marker> <onMatch>ACCEPT</onMatch> <!-- Keep events with the AUDIT marker --> <onMismatch>DENY</onMatch> <!-- Reject all other events --> </filter> <file>${USER_HOME}/audit.log</file> <encoder> <pattern>%msg%n</pattern> </encoder> </appender>
How this works:
- The
MarkerFilteris a built-in Logback filter that checks if a log event contains the specified marker. - Setting
onMatch="ACCEPT"ensures any log with theAUDITmarker is processed by this appender. onMismatch="DENY"tells the appender to ignore all other log events, so only audit logs end up inaudit.log.
Quick note on using the marker in code:
Make sure you’re correctly attaching the AUDIT marker to your log statements in your application code:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.Marker; import org.slf4j.MarkerFactory; public class AuditExample { private static final Logger logger = LoggerFactory.getLogger(AuditExample.class); private static final Marker AUDIT_MARKER = MarkerFactory.getMarker("AUDIT"); public void performAuditableAction() { logger.info(AUDIT_MARKER, "User {} performed action X", "john_doe"); } }
内容的提问来源于stack exchange,提问作者morsor
相关产品推荐
相关产品推荐

