Java NewRuleAction-class And Method Code Example


The NewRuleAction class from the logback.core package can be used in a configuration file for Logback, a logging framework for Java, to add new rules to the configuration.

Here is an example of how the NewRuleAction class could be used to add a new rule that sets the log level of any logger whose name starts with "com.example" to DEBUG:

<configuration>
  <newRule pattern="com.example.*" actionClass="ch.qos.logback.core.util.LevelChangePropagator$LevelChangeRule">
    <level>DEBUG</level>
  </newRule>

  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>mylog.log</file>
    <encoder>
      <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="info">
    <appender-ref ref="FILE" />
  </root>

</configuration>

In this example, <newRule> element tells Logback to add a new rule that matching pattern is "com.example.*" and action class is LevelChangePropagator$LevelChangeRule. And the level is set to DEBUG.

The newRule element is used to configure a new log level change rule. Inside the element, the pattern attribute specifies a regular expression that is used to match against the logger name, while the actionClass attribute specifies the class that implements the rule. In this case the action class is ch.qos.logback.core.util.LevelChangePropagator$LevelChangeRule .And inside it takes the level where it needs to change.

Please note that you need to include logback core library in your classpath.