The
MarkerFilter compares the configured Marker value against the Marker that is included
in the LogEvent.
For example,
following application define two markers one for ADMIN and other for GENERAL
users.
log4j2.xml
is configured like below.
<MarkerFilter
marker="ADMIN" onMatch="ACCEPT" onMismatch="DENY"
/>
Above
statement logs the events, if the marker is ADMIN, else don’t log the events.
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="DEBUG" monitorInterval="30"> <Appenders> <Console name="my_console_appender" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> <MarkerFilter marker="ADMIN" onMatch="ACCEPT" onMismatch="DENY" /> > </Console> </Appenders> <Loggers> <Root level="trace"> <AppenderRef ref="my_console_appender" /> </Root> </Loggers> </Configuration>
package log4j_tutorial; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; public class HelloWorld { private static final Logger logger = LogManager.getLogger(); private static final Marker ADMIN_USER = MarkerManager.getMarker("ADMIN"); private static final Marker GENERAL_USER = MarkerManager .getMarker("GENERAL"); public static void adminActions() { logger.info(ADMIN_USER, "Admin actions are triggered"); } public static void generalActions() { logger.info(GENERAL_USER, "User actions are triggered"); } public static void main(String args[]) { adminActions(); generalActions(); } }
Output
18:05:36.096 [main] INFO log4j_tutorial.HelloWorld - Admin actions are triggered
Following
are the attributes for Marker filter.
Attribute
|
Type
|
Description
|
marker
|
String
|
The name
of the Marker to compare.
|
onMatch
|
String
|
Action to
take when the filter matches. May be ACCEPT, DENY or NEUTRAL. The default
value is NEUTRAL.
|
onMismatch
|
String
|
Action to
take when the filter does not match. May be ACCEPT, DENY or NEUTRAL. The
default value is DENY.
|
How can you log both ADMIN and GENERAL user
actions?
Update
Marker filter like below.
<MarkerFilter marker="ADMIN" onMatch="ACCEPT" onMismatch="ACCEPT" /> (OR) <MarkerFilter marker="ADMIN" onMatch="ACCEPT" onMismatch="NEUTRAL" /> (OR) <MarkerFilter marker="ADMIN" onMatch="ACCEPT" onMismatch="NEUTRAL" /> <MarkerFilter marker="GENERAL" onMatch="ACCEPT" />
Above
statement accept both ADMIN and GENERAL user log messages. You will get
following statements in console.
18:35:26.861 [main] INFO log4j_tutorial.HelloWorld - Admin actions are
triggered
18:35:26.862 [main] INFO log4j_tutorial.HelloWorld - User actions are
triggered
private static final Marker ADMIN_USER =
MarkerManager.getMarker("ADMIN");
Above
statement retrieves a Marker or create a Marker that has no parent. All Markers
created by MarkerManager are immutable.
No comments:
Post a Comment