Search code examples
javaregexlog4jlog4j2

One regex for all class in package and another regex for the one class inside the same package with Log4j2 configuration


Following project structure is present in java application with log4j2 xml configuration .

com.app.package.one

  • class1.java
  • class2.java
  • class3.java
  • class4.java

com.app.package.two

  • class5.java
  • class6.java
  • class7.java
  • class8.java

whole application to print the loggers on following all three conditions to be matched

condition1-> print the error mode logger for all the classes

condition2-> print if the logging statement has "exception" in part of logging statement

condition3-> for package 2's class 7 alone it needs exclusion that to display if the logging statement contains exception or sometext

i have added the following log4j2 xml configuration which is satisfying the condition1 and condition2 . but cannot able to achieve the condition 3 in the same configuration .

working configuration for condition 1 and 2

<Logger name="com.app.package" level="error">
<RegexFilter regex=".*(?i)exception(?-i).*" onMatch="ACCEPT" onMismatch="DENY"/>
</Logger>

not working for condition 3

<Logger name="com.app.package" level="error">
     <RegexFilter regex=".*(?i)exception(?-i).*" onMatch="ACCEPT" onMismatch="DENY"/>
</Logger>

<Logger name="com.app.package.two.class7" level="error">
     <RegexFilter regex=".*(?i)exception(?-i).* | .*(?i)sometext(?-i).*" onMatch="ACCEPT" onMismatch="DENY"/>
</Logger>

is this possible to do a package level filter and as well class level filter both at a time for same class ?

any input on this will be help full,

thanks in advance... :-)


Solution

  • For condition 3

    there were two problem on the logging configuration

    1)appender information to be added

    2)on regex space before and after pipe | symbol

    the altered configuration working for all there condition is looks below

    <Logger name="com.app.package" level="error">
    <RegexFilter regex=".*(?i)exception(?-i).*" onMatch="ACCEPT" onMismatch="DENY"/>
    <AppenderRef ref="LogToConsole"/>  
    </Logger>
    <Logger name="com.app.package.two.class7" level="error">
     <RegexFilter regex=".*(?i)exception(?-i).*|.*(?i)sometext(?-i).*" onMatch="ACCEPT" onMismatch="DENY"/>
    <AppenderRef ref="LogToConsole"/>
    </Logger>