Friday, 25 February 2022

Logback: Logging levels

Logger can be assigned levels. Following levels are supported by most of the logging libraries.

a.   TRACE

b.   DEBUG

c.    INFO

d.   WARN and

e.   ERROR

 

'ch.qos.logback.classic.Level' defined the logging levels for a logback logger. Logback root logger is assigned with DEBUG logging level by default.

 


What if I do not set the logging level of a logger?

It inherits the logging level from its closest ancestor. For example, if you do not set logging level to the logger L1, it inherit the first non-null logging level in its naming hierarchy.

 

Below tables summarize different examples on logging levels.

 

Example 1: Logging is not set for individual loggers

LoggerName

Assigned Level

Effective Level

root

ERROR

ERROR

A

None

ERROR

A.B

None

ERROR

A.B.C

None

ERROR

 

 

Example 2: All loggers set logging level explicitly

LoggerName

Assigned Level

Effective Level

root

ERROR

ERROR

A

INFO

INFO

A.B

DEBUG

DEBUG

A.B.C

WARN

WARN

 

Example 3: Loggers root, A and A.B.C are assigned the levels DEBUG, INFO and ERROR respectively. Logger A.B inherits its level value from its parent A.

LoggerName

Assigned Level

Effective Level

root

ERROR

ERROR

A

INFO

INFO

A.B

None

INFO

A.B.C

ERROR

ERROR

 

Example 4: Loggers root and A and are assigned the levels DEBUG and WARN respectively. The loggers A.B and A.B.c inherit their level from their nearest parent A.

LoggerName

Assigned Level

Effective Level

root

ERROR

ERROR

A

WARN

WARN

A.B

None

WARN

A.B.C

None

WARN

 

How the information printed based on logging levels?

A logging statement is enabled, if its level is higher than or equal to the effective level of its logger. Logging level orders are like TRACE < DEBUG < INFO <  WARN < ERROR.

 

For example, if a logger’s effective level is set to INFO, then info, warning and error level messages are enabled.

 

For example,

 

LoggingSelectionRuleDemo.java

package com.sample.app;

import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Level;

public class LoggingSelectionRuleDemo {

	public static void main(String[] args) {
		ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory
				.getLogger(LoggingLevelsDemo.class);
		logger.setLevel(Level.INFO);

		logger.trace("Trace message");
		logger.debug("Debug message");
		logger.info("Info message");
		logger.warn("Warning message");
		logger.error("Error message");

	}
}

 

Output

12:19:40.905 [main] INFO com.sample.app.LoggingLevelsDemo - Info message
12:19:40.907 [main] WARN com.sample.app.LoggingLevelsDemo - Warning message
12:19:40.907 [main] ERROR com.sample.app.LoggingLevelsDemo - Error message

 

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment