This automatically works in Log4j if you follow the naming convention for registrars. In your code, declare the registrars with their class name:
Logger logger = LogManager.getLogger(MyClass.class);
The registrar is automatically assigned the name fully.qualified.class.name.of.MyClass . Now in your configuration you can use this fully qualified name (either the name of the package or the first part of the package) for filtering and routing:
Filtration
The following example shows how to filter log events based on a package of a logging class: all DEBUG and TRACE level log events by class in com.other.company will be ignored, and for classes only in com.another.project ERROR and FATAL records included.
<Configuration status="warn"> <Appenders> <File name="MyFile" fileName="logs/my.log"> <PatternLayout pattern="%d %p %c{1.} [%t] %m%n" /> </File> </Appenders> <Loggers> <Logger name="com.other.company" level="INFO" /> <Logger name="com.another.project" level="ERROR" /> <Root level="trace"> <AppenderRef ref="MyFile"/> </Root> </Loggers> </Configuration>
Routing
The following example shows how to route log events to separate log files based on a class package that performs logging: all class entries in the com.other.company package com.other.company not be written to my.log only on other.log .
<Configuration status="warn"> <Appenders> <File name="MyFile" fileName="logs/my.log"> <PatternLayout pattern="%d %p %c{1.} [%t] %m%n" /> </File> <File name="OtherFile" fileName="logs/other.log"> <PatternLayout pattern="%d %p %c{1.} [%t] %m%n" /> </File> </Appenders> <Loggers> <Logger name="com.other.company" additivity="false"> <AppenderRef ref="OtherFile"/> </Logger> <Root level="trace"> <AppenderRef ref="MyFile"/> </Root> </Loggers> </Configuration>
source share