1.1 Introduction to logs

The log is a list of events that have occurred. Almost like a nautical journal or diary. Well, accordingly, a logger is an object with which you can log. In programming, it is customary to log almost everything. And in Java, everything is like that and even a little more.

logger java

The fact is that Java programs are very often large server applications without a UI, console, and so on. They process requests from thousands of users at the same time and often various errors occur. Especially when different threads begin to interfere with each other.

And, in fact, the only way to find rarely reproduced errors and failures in such a situation is to write to the log / file everything that happens in each thread.

Most often, information is written to the log about the parameters of the method with which it was called, all the intercepted errors, and a lot of intermediate information. The more complete the log, the easier it is to restore the sequence of events and trace the causes of a failure or error.

But the larger the log, the more difficult it is to work with it. Sometimes the logs reach several gigabytes per day. This is fine.

1.2 Failed logs

As the first logs, the developers used simply output to the console . It is convenient to do this during application debugging - when all important information and variable values ​​are written to the console. But such a log is completely inapplicable during the normal operation of the application.

Firstly, the application may want to output something to the console itself, and the user does not want to see the service information intended for the programmer at all.

Secondly, the size of the console buffer is limited, you can't write much there.

And finally, thirdly, information about program errors that is collected over a long period of time should be sent to the program developers. And it is most convenient to write all this information at once to a file.

The developers quickly solved the first problem - they came up with another output stream - System.err. You can write messages to it and they will be sent to a separate thread, and not to the standard console.

And even the problem with writing to a file was solved:

// Define the file to which we will write the log
System.setErr(new PrintStream(new File("log.txt")));
// Display messages
System.err.println("Message 1");
System.err.println("Message 2");
// Display an error message
try {
    throw new Exception("Error message");
} catch (Exception e) {
    e.printStackTrace();
}

But even in this form, it did not solve the whole problem, so it was decided to create a special library that would write log messages to a file. She did it in a smart way and allowed the flexibility to configure filters for logged events and data.

The whole logging process, in fact, consists of three parts:

  • The first part is information gathering .
  • The second part is the filtering of the collected information.
  • The third part is the recording of the selected information.

1.3 Introduction to the log4j logger

The first popular logger in the Java community was the log4j. Including it in the project is very simple, for this you need to add just a couple of lines to your pom.xml

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>2.2.17</version>
</dependency>

The interaction of your program with such a logger would look something like this:

class Manager {
   private static final Logger logger = LoggerFactory.getLogger(Manager.class);

   public boolean processTask(Task task) {
        logger.debug("processTask id = " + task.getId());
        try {
            task.start();
            task.progress();
            task.complete();
            return true;
        } catch (Exception e) {
            logger.error("Unknown error", e);
            return false;
        }
    }
}

Three things happen here:

The creation of the object is highlighted in green Logger . Its object is stored in a static variable for convenient further work with it. And also getLogger()information about the class in which the information is collected is passed to the method.

The line highlighted in blue is where we log information of value only during debugging . For this, a special method is used -debug()

And finally, the line where we save the exception that has arisen to the log is highlighted in red . Exceptions are potential errors, so the error().