What is the best practice in using log4j levels while coding. I mean when do we use INFO logging, when do we use DEBUG logging / ERROR logging etc.
The best way to learn is by example. Read source of some open source things, like, oh, Tomcat or whatever is in your application area, and see what you see.
ERROR logging should always be on.
INFO + DEBUG should be on when tracking down problems/bugs.
In general, I follow these guidelines:
- DEBUG : low level stuff. cache hit, cache miss, opening db connection
- INFO : events that have business meaning - creating customer, charging cc...
- WARN : could be a problem but doesn't stop your app. email address not found / invalid
- ERROR : unexpected problem. couldn't open db connection. etc...
My baseline is always that INFO level is equivalent to System.out, and ERROR is equivalent to System.err.
DEBUG - Here you put all your tracing information, and specifically information that you don't want to see when your "comfort level" is system.out.
INFO - use this one for general messages, progress messages, for application related messages, but not for tracing.
WARN - provide alerts that something is wrong, perhaps unexpected, or that a workaround is used, but the application can still continue (socket timeout/retries, invalid user input, etc.).
ERROR - alerts about problems that prevent your app from continuing normally, e.g. database is down, missing bootstrap configuration.
A common mistake when writing libraries is to use ERROR level to indicate problems with the calling application (the code that uses the library) instead of indicating real errors within the library itself. See for example this hibernate bug -> http://opensource.atlassian.com/projects/hibernate/browse/HHH-3731
This is really annoying because messages from ERROR level are really difficult to suppress, so use them only to indicate problems with your own code.
All - I don't really use this one, it is practically the same as DEBUG or TRACE.
To what others mentioned, I'd add TRACE and FATAL levels, the former is good for very verbose logging, the later is to indicate total show stopper. There are general guide lines on how you use levels, as mentioned by other above. However, the most important is how YOU will use it and how your USERS will interpret them. You need levels to focus on problems, so decide what is the problem in your case. Your users will hardly ever need trace or debug statements, but they will definitely want to nail problems and report them to you.