What is going on? Why it is not working like that? This is not expected behavior :(
Sounds familiar?
I am sure every software engineer has been in this situation where they are not able to figure out what is going on in the code?
Well, sometimes an Insignful log statement can come in handy to answers the queries.
Let us go over a few things which I personally have adopted and feel are decent enough for others to follow for effective and insightful logging.
Note: While writing this, log4j has been kept in mind.
Some commonly used log levels: FATAL, ERROR, WARN, INFO, DEBUG, TRACE
Simple interpretation can be taken as :
- FATAL: Something terribly wrong has happened, that must be investigated immediately.
- ERROR: Something wrong has happened. Someone should take a look.
- WARN: The process might be continued, but take extra caution.
- INFO: Important business process has changed state/finished. We should be able to understand INFO messages and quickly find out what the application is doing.
- DEBUG: Developer help notes.
- TRACE: Very detailed information, intended only for development. Generally, this is for temporary items.
Things to keep in mind
- Have data models with a toString() method. This will be helpful in putting important data in the log. Gson is also there to create JSON for your object(preferable smaller data model)
- Each logging statement should contain both data and description.
- Log method arguments and return values as DEBUG log. This would work as a debugger during the development cycle as well as comes in handy for investigation purposes.
- Make sure when calling external API/services, all things are logged. This would help to identify which side issues occurred. Did we made mistake calling it or API processing it made mistake?
- Make sure the same exception is not logged twice. This could lead to a misunderstanding of error.
- Logs should be easy to read.
- Use log context for better traceability of a request.
Things to avoid
- Avoid use of
log.isDebugEnabled()
for straight forward logs. Use these only when some computation is needed for logging. - Do not use String concatenation with +, use replacement with {}.
- Do not use
obj.getAttribute()
without confirming if obj is null or not. This may lead to NPE. - Avoid printing too big objects. Ex:
List<Object>
should not be printed in a single log. Better to get a list of objectID and log that. - Do not log PII data. It is very important that no personal information gets logged. This may cause GDPR violations.
- Do not log Password, Secret Keys, etc. The information which is not available to the whole team, should not be logged.
Logs should help out software engineers to figure out Where, What and Why something went wrong. If the developer is able to find issues just from logs, your logging is good.
Happy Logging. :)