Error log in Java application

Asked

Viewed 2,960 times

6

We developers when we code, we have a way to track the process of running software through the output of the IDE, but when the software goes into production and we no longer have the development environment, how can we map an error that happened during some system process.

As you would record in a log?

  • I believe that normally if you are using Java in some application the JVM itself is in charge of saving a log if a NullPointerException, for example. Anything you can create a file .txt to save errors.

  • 2

    Clayton, I use the LOG4J, you have an answer from me here how to use and configure

  • I was unaware of Wellington, thank you for your reply.

2 answers

6


It is difficult to make a full tutorial, would escape the focus of the site.

You should have a class that takes care of it for you. The ideal is to use one that already does all the work without much worry. A known class will save you a lot of headache than trying to do it yourself. There is following the documentation.

In essence you must invoke the log whenever you think you should. That is, when something you can validate and error or when exceptions occur. Remembering that what log and what to leave out is a programmer’s decision. The most common is log when exceptions occur. But since the Java culture is causing exceptions even when there is no error in fact and can recover, it is not always interesting log all exceptions. You can have different levels of "error".

Another example of what you should decide is whether to go log momentary and that errors are recovered such as in accessing files or network that fail, for example.

Therefore within catch is the place where the log. You probably have something like that in your main():

static Logger log = Logger.getLogger(ClassePrincipal.class);
try {
    chamaAplicacao();
} catch (Exception ex) { //o único lugar onde capturar Exception faz sentido
    log.error("um erro ocorreu: " + ex.getMessage()); //talvez um printStackTrace() tb
}

I put in the Github for future reference.

I believe the library of log most used is the Log4j.

This is just a basic example using it, of course the full usage needs to be accompanied by good reading in the manual.

Elsewhere, avoid capturing Exception, capture the most specific exception possible.

If you think you should do something of your own, study this library to come up with something similar. But I wouldn’t advise.

  • 1

    Only one addendum need not call . getName(); log4j accepts ClassePrincipal.class

  • 1

    @Wellingtonavelino cool, improved. Thank you.

2

The log configuration part in Java has a history that may seem a bit confusing at first.

The log option that comes by default with Java is in the package java.util.logging. You can just use it making:

private static final Logger LOGGER = Logger.getLogger(ClassName.class.getName());

It provides various types of log levels. As an example, when capturing an exception:

try {
    // codigo com erro
} catch( Exception ex ) {
    LOGGER.log(Level.SEVERE, ex.toString(), ex);
}

However, this implementation of Java had its limitations when it was launched. This made room for other alternatives to emerge.

Thus arose the The Simple Logging Facade for Java (SLF4J). It creates an abstraction for different Java log implementations, such as java.util.logging, logback and log4j.

With SLF4J, you can use it in your code as follows:

private static final Logger LOGGER = LoggerFactory.getLogger(ClassName.class);

Example:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloWorld {
  public static void main(String[] args) {
    Logger logger = LoggerFactory.getLogger(HelloWorld.class);
    logger.info("Hello World");
  }
}

And then determine which log implementation you want by adding the desired library to classpath of its application. The most common option currently seems to be the Logback.

In a "normal" project, these libraries are added using Maven or Gradle. In Maven, you can add Logback in the following way:

<dependency> 
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback-classic</artifactId>
  <version>1.2.3</version>
</dependency>

That it will bring logback-core (implementation) and slf4j-api (interface) to your project.

How to log well for production?

In a production environment we cannot always count on detailed monitoring of the execution of internal processes. However, the good use of the log can bring us almost all the information we need to diagnose problems.

There are several tips for this. Some important points to note:

  • Do not log the same error several times. This causes a lot of confusion when trying to understand the origin of the error and distinguish one error from the other.
  • Try to log in several information of what is happening in the important steps of the main processes of your application. This will help you greatly to understand what data is being used and what paths your software is going through.
  • Set the correct severity level of the log. For information that may be useful to those viewing the log, how to track the execution of a particular item, use INFO. For warnings that may be important, use WARN. For error cases, use ERROR.
  • Do not log sensitive or personal information (CPF, email, etc) without at least masking the information. A LGPD enters into force in 2020 and we have to be careful with user information.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.