Error log in Java application

4

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

How would you log into a log ?

    
asked by anonymous 31.08.2015 / 20:30

1 answer

5

It's hard to do a full tutorial, it would run out of focus.

You must have a class that treats this for you. The ideal is to use one that already does all the work without major concerns. A well-known class will save you a lot of headache than trying to do it yourself. Then follow the documentation.

In essence you should invoke log whenever you feel you should. That is, when something that can validate and give error or when exceptions occur. Remembering that logging and what to leave out is a decision of the programmer. The most common logging when exceptions occur. But as Java's culture is to cause exceptions even when there is no actual error and can recover, it is not always interesting to logging all exceptions. It can have different levels of "error".

Another example of what you should decide is whether you will log and momentary errors that are retrieved, such as access to failed files or network, for example.

So within catch is the place where log will do the most. You probably have something like this 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 believe the log library most often used is Log4J .

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

At other sites, avoid capturing Exception , capture the most specific exception possible .

If you think you should do something of your own, study this library to craft something similar. But I do not advise.

    
31.08.2015 / 20:43