Rajas Rajas - 1 year ago 344
Java Question

Apache Log4j2 package specific logging using log4j2.xml

I am using log4j2. But the problem that I am facing is that it logs all logs. I want to ... log from specific package to a specific file & other package to another file. I am using log4j2.xml for configuration.
Please can someone help?


<?xml version="1.0" encoding="UTF-8"?>

<Root level="DEBUG" additivity="false">
<AppenderRef level="DEBUG" ref="CONSOLE" />
<AppenderRef level="DEBUG" ref="fileAppender" />
<Logger name="com.pkg.test.logging.method" level="DEBUG"
<Appender-ref ref="fileAppender" level="DEBUG" />



<Console name="CONSOLE" target="SYSTEM_OUT">
pattern="%highlight{[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} %c{1}: %L - %msg%n%throwable}" />

<RollingFile name="fileAppender" fileName="./log.log"
pattern="%highlight{[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} %c{1}: %L - %msg%n}" />
<TimeBasedTriggeringPolicy interval="1"
modulate="true" />

Answer Source

From Log4J Manual:

Adding a specific logger for a class: (you can refer to packages here too)

<Logger name="org.apache.logging.log4j.test2" level="debug" additivity="false">
  <AppenderRef ref="File"/>

Adding a specific appender:

<Appender type="File" name="File" fileName="${filename}">
  <Layout type="PatternLayout">
    <Pattern>%d %p %C{1.} [%t] %m%n</Pattern>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download