Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

Technology is introduced

Logback is what?

  • Logback was created to replace Log4j. Logback was designed by Ceki Gulcu, founder of Log4j. Based on more than a decade of experience designing industrial-grade recording systems, logBacks have been created that are faster and consume fewer resources than any existing recording system (except log4J2), sometimes by a significant margin.

  • Logback provides unique and useful features such as markers, parameterized record statements, conditional stack traces, and powerful event filtering capabilities.

  • The above list is just a few of the useful features of LogBack. For its own error reporting, Logback relies on Status objects, which greatly simplify fault finding.

  • Logback-core comes with Joran, a powerful, universal configuration system that you can use in your own projects

  • Joran is used to great effect.

Installation of structures,

A necessary condition for

Logback-classic relies on slf4J-api.jar and logback-core-.jar. Now let’s start experimenting with Logback.

Example: Document the basic template
  • logback-examples/src/main/java/chapters/introduction/HelloWorld1.java
package chapters.introduction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HelloWorld1 {
public static void main(String[] args) {
	Logger logger = LoggerFactory .getLogger("chapters.introduction.HelloWorld1");
	logger.debug("Hello world."); }}Copy the code
  1. The HelloWorld1 class imports the Logger class and the LoggerFactory class defined by the SLF4J API, or more specifically, the two classes defined in the org.slf4J package.

    • In the first line of the main method, we call the static method getLogger of the LoggerFactory class to get an instance of Logger, assign it to the variable Logger, Logger is named “chapters. The introduction. HelloWorld1”.

    • The main method continues to call the Logger’s debug method with the argument “Hello world”. The main method we call contains a logging statement with a message of “Hello world” and a level of DEBUG.

Note: The above example does not reference any logback classes. In most cases, you only need to reference SLF4J’s classes when it comes to recording. So in most cases, your class will import only SLF4J’s API and basically ignore logback.

Logbacks can report their internal state through a built-in state system, and the StatusManager component provides access to important events that occur during the Logback’s lifetime.

We can call the print() method of the StatusPrinter class to print the internal state of logBack.

Example: Print Logger status
package chapters.introduction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext; 
import ch.qos.logback.core.util.StatusPrinter;
public class HelloWorld2 {
public static void main(String[] args) { 
    Logger logger = LoggerFactory.getLogger("chapters.introduction.HelloWorld2");
    logger.debug("Hello world.");
    // print internal stateLoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); StatusPrinter.print(lc); }}Copy the code
Log output
12:49:22. 203. [the main] the DEBUG chapters. The introduction. HelloWorld2 - Hello world. 12:49:22, | - INFO in 078 Ch. Qos. Logback. Classic. LoggerContext [default] - Could NOT find the resource logback - test. XML 12:49:22, | - INFO in 093 Ch. Qos. Logback. Classic. LoggerContext [default] - Could NOT find the resource [logback. XML] ": 22093 | - INFO in c h.qos.logbac k.c lassic .LoggerContext[default] - Setting up default configuration.Copy the code
  1. Logback says it didn’t find the configuration files logback-test.xml and logback.xml, so it configured them using the default policy, which is a basic ConsoleAppender.

  2. The Appender class can be considered for the output destination.

    • Appenders contain many different types of destinations:
      • The console
      • file
      • Syslog
      • TCP socket
      • JMS
      • other
    • Users can easily customize appenders.
  3. When an error occurs, LogBack automatically prints its internal state on the console.

The two examples above are fairly simple, and the actual logging in a large program is not that different.

  • The basic mode of the recording system does not change, but the configuration process. You may want to customize or configure logBacks to suit your needs, which will be discussed in a later section.

  • We call the statusprinter.pring () method to print the internal state of logback. Logback internal state information can be very useful when diagnosing logback-related problems.

Use the basic three elements of Logback

The three necessary steps to enable logging in an application are as follows:

  1. Configure the Logback environment.
  2. In each class that needs to record, call the getLogger() method of org.slf4j.LoggerFactory to get a Logger instance, taking either the current class name or the class itself as an argument.
  3. Call the printout methods of the obtained logger instance, debug(), info(), WARN (), and error(), and output the records to the appenders in the configuration.

architecture

Logback architecture

The basic structure of Logback is general enough to be used in a variety of environments. Currently, LogBack is divided into three modules: Core, Classic, and Access.

  • The Core module is the foundation of the other two modules.
  • The Classic module extends the core module and represents a significantly improved version of Log4J.
    • Logback-classic implements the SLF4J API directly, so you can easily switch between Logback and other logging systems such as log4j and java.util.logging (JUL).
  • Access module is integrated with Servlet container to provide HTTP Access record function.

It’s safe to say that what we call “logback” stands for the Logback-classic module.

Logger, Appender, and Layout

  • Logbacks are built on top of three main classes :Logger, Appender, and Layout. These three components work together to allow developers to record messages by message type and level, and to control the format and destination of the output messages during the program’s lifetime.

  • The Logger class is part of the Logback-classic module, while the Appender and Layout interfaces come from logback-core, which as a multipurpose module does not contain any Loggers.

The Logger context

The first and most important advantage of any logging API that is more advanced than System.out.println is the ability to disable certain logging statements without blocking the output of other statements.

This capability stems from record isolation (SPACE) — the isolation of all the various record statements — which is classified according to the criteria chosen by the developer.

  • In Logback-Classic, this classification is inherent in logger.

  • Each logger is associated with a LoggerContext, which is responsible for creating loggers and arranging them in a tree structure.

Logger is a named entity. Their names are case-sensitive and follow the following hierarchical naming rules:

Paternal succession
  • If logger’s name is prefixed with the name of another logger with a dot, the former is called the ancestor of the latter.

  • If there is no other ancestor between a Logger and its offspring, then the former is called the father of the child Logger.

For example, a logger named “com.foo” is a parent named” com.foo.Bar “. In the same way, “Java” is the father of “java.util” and the ancestor of” java.util.Vector “.

ROOT logger

The root Logger is located at the top of the Logger hierarchy and is unique in that it is the common ancestor of each hierarchy. Like every other logger, the root logger can be obtained by its name, as follows:

Logger rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); 
Copy the code

All other loggers are also obtained through the static method getLogger of the org.slf4j.LoggerFactory class. The getLogger method takes the logger name as an argument. Some basic methods of Logger interfaces are listed as follows:

package org.slf4j;
   public interface Logger {
	// Printing methods:
	public void trace(String message); 
	public void debug(String message);
	public void info(String message);
	public void warn(String message); 
	public void error(String message);
}
Copy the code
The effective Level is Level inheritance

Loggers can be assigned levels. Level include: TRACE, DEBUG, INFO, WARN, and the ERROR, defined in ch. Qos. Logback. Classic. Level class.

Note: In logback, the Level class is final and cannot be inherited, and Marker objects provide more flexibility.

If logger is not assigned a level, it inherits the level from the nearest ancestor that has the assigned level. More formally:

  • Logger L has a valid level equal to the first non-null level in its hierarchy, starting from L and working up to the root Logger.

  • To ensure that all loggers can eventually inherit a level, the root logger always has a level, which by default is DEBUG.

The next article will cover logback for level analysis!