Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the best practices to log an error?

Many times I saw logging of errors like these:

System.out.println("Method aMethod with parameters a:"+a+" b: "+b);
print("Error in line 88");

so.. What are the best practices to log an error?

EDIT:

This is java but could be C/C++, basic, etc.

like image 307
Agusti-N Avatar asked Nov 17 '08 16:11

Agusti-N


People also ask

What is a common error log?

In computer science, an error log is a record of critical errors that are encountered by the application, operating system or server while in operation. Some of the common entries in an error log include table corruption and configuration corruption.


1 Answers

Logging directly to the console is horrendous and frankly, the mark of an inexperienced developer. The only reason to do this sort of thing is 1) he or she is unaware of other approaches, and/or 2) the developer has not thought one bit about what will happen when his/her code is deployed to a production site, and how the application will be maintained at that point. Dealing with an application that is logging 1GB/day or more of completely unneeded debug logging is maddening.

The generally accepted best practice is to use a Logging framework that has concepts of:

  1. Different log objects - Different classes/modules/etc can log to different loggers, so you can choose to apply different log configurations to different portions of the application.
  2. Different log levels - so you can tweak the logging configuration to only log errors in production, to log all sorts of debug and trace info in a development environment, etc.
  3. Different log outputs - the framework should allow you to configure where the log output is sent to without requiring any changes in the codebase. Some examples of different places you might want to send log output to are files, files that roll over based on date/size, databases, email, remoting sinks, etc.
  4. The log framework should never never never throw any Exceptions or errors from the logging code. Your application should not fail to load or fail to start because the log framework cannot create it's log file or obtain a lock on the file (unless this is a critical requirement, maybe for legal reasons, for your app).

The eventual log framework you will use will of course depend on your platform. Some common options:

  • Java:
    • Apache Commons Logging
    • log4j
    • logback
    • Built-in java.util.logging
  • .NET:
    • log4net
  • C++:
    • log4cxx
like image 153
matt b Avatar answered Oct 11 '22 16:10

matt b