Filter by class name in log4j2

I am using log4j2 and I do not know how I can filter by class name. I tried with RegexFilter, but it only filters the text message. In old log4j, it was enough with the tag 'filter'

<filter class="aaaa.bbbb.cccc.ClassName"> 

Does anyone know how to do this now?

Thank you in advance!

Update:

Ok, I did it! I need to define a registrar and set the class name in the 'name' attribute:

 <loggers> <logger name="aaaa.bbbb.cccc.ClassName" additivity="false" level="info"> <appender-ref ref="RollingFile" /> </logger> <root level="error"> <appender-ref ref="RollingFile" /> </root> </loggers> 
+6
source share
1 answer

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> <!-- drops all DEBUG and TRACE logging done by any class in this package --> <Logger name="com.other.company" level="INFO" /> <!-- log only ERROR and FATAL logging by classes in this package --> <Logger name="com.another.project" level="ERROR" /> <!-- by default, all log events are written to MyFile --> <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> <!-- all logging from this package and subpackages goes to OtherFile --> <!-- Note: set additivity=false or logging will also go to the root logger --> <Logger name="com.other.company" additivity="false"> <AppenderRef ref="OtherFile"/> </Logger> <Root level="trace"> <AppenderRef ref="MyFile"/> </Root> </Loggers> </Configuration> 
+2
source

Source: https://habr.com/ru/post/946497/


All Articles