views:

1874

answers:

8

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.

A: 

There really is no best practice for logging an error. It basically just needs to follow a consistent pattern (within the software/company/etc) that provides enough information to track the problem down. For Example, you might want to keep track of the time, the method, parameters, calling method, etc.

So long as you dont just print "Error in "

MunkiPhD
+2  A: 

The easiest way to log errors in a consistent format is to use a logging framework such as Log4j (assuming you're using Java). It is useful to include a logging section in your code standards to make sure all developers know what needs to be logged. The nice thing about most logging frameworks is they have different logging levels so you can control how verbose the logging is between development, test, and production.

rich
+1  A: 

A best practice is to use the java.util.logging framework

Then you can log messages in either of these formats

log.warning("..");
log.fine("..");
log.finer("..");
log.finest("..");

Or

log.log(Level.WARNING, "blah blah blah", e);

Then you can use a logging.properties (example below) to switch between levels of logging, and do all sorts of clever stuff like logging to files, with rotation etc.

handlers = java.util.logging.ConsoleHandler

.level = WARNING

java.util.logging.ConsoleHandler.level = ALL

com.example.blah = FINE
com.example.testcomponents = FINEST

Frameworks like log4j and others should be avoided in my opinion, Java has everything you need already.

EDIT

This can apply as a general practice for any programming language. Being able to control all levels of logging from a single property file is often very important in enterprise applications.

adam
+1  A: 

Some suggested best-practices

  • Use a logging framework. This will allow you to:

    • Easily change the destination of your log messages
    • Filter log messages based on severity
    • Support internationalised log messages
  • If you are using java, then slf4j is now preferred to Jakarta commons logging as the logging facade.

  • As stated slf4j is a facade, and you have to then pick an underlying implementation. Either log4j, java.util.logging, or 'simple'.

  • Follow your framework's advice to ensuring expensive logging operations are not needlessly carried out

toolkit
+7  A: 

Apache Commons Logging is not intended for applications general logging. It's intended to be used by libraries or APIs that don't want to force a logging implementation on the API's user.

There are also classloading issues with Commons Logging.

Pick one of the [many] logging api's, the most widely used probably being log4j or the Java Logging API.

If you want implementation independence, you might want to consider SLF4J, by the original author of log4j.

Having picked an implementation, then use the logging levels/severity within that implementation consistently, so that searching/filtering logs is easier.

Ken Gentle
These usually have advanced features such as automatically logging the source and filtering by level OR origination location. This makes debugging much easier. Use one of these! (also check out Chainsaw)
Bill K
A: 

The apache common logging API as mentioned above is a great resource. Referring back to java, there is also a standard error output stream (System.err).

Directly from the Java API:

This stream is already open and ready to accept output data.

Typically this stream corresponds to display output or another output destination specified by the host environment or user. By convention, this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream, the value of the variable out, has been redirected to a file or other destination that is typically not continuously monitored.

John T
+7  A: 

Logging directly to the console is horrendous and frankly, the mark of a bad 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:

matt b
+1  A: 

Aspect-oriented Programming

In Java, I would highly recommend aspect-oriented programming (AOP) to inject logging, with a tool such as AspectJ. Logging and security are two requirements required by most parts of any substantial system (that is, they are cross-cutting concerns). It goes against the DRY principle to litter logging statements throughout the codebase.

Even though aspects can be used for much more than logging and security, I would recommend limiting its use to those until comfort and product maturity have been achieved.

Once the application is using aspects, the "best practices" for logging (in Java) are hidden: you can change how logging is performed throughout the entire application from a single location. Transitioning from System.out.println to java.util.logging.Logger or to Apache's Log4J becomes trivial.

Advantages of Aspect-oriented Programming

From http://ecet.ecs.ru.acad.bg/cst/Docs/proceedings/S2/II-19.pdf:

  • Increased modularity. Separation of cross-cutting concerns in a single class.
  • Less code.Applications may be developed faster.
  • Maintenance. Common code is localized.
  • Code reuse. Localized cross-cutting concerns may be easily reused.
  • Understanding. Since cross-cutting concerns are removed from application source code, it is easier to understand the source.
  • Flexibility. With aspects there are more implementation solutions available.
  • Inheritance. Aspects allow for a simpler class hierarchy.
  • Speed. Applications can be compiled without logging code injected.

Disdvantages of Aspect-oriented Programming

Some problems with AOP include:

  • Magic. Aspects introduce code that executes which is not coupled to the source code.
  • Coupling breaks. Changes to the source code can break intended functionality of aspects.
  • Implicit control flow. Points in a program where control is transferred are implicit in Aspects, but explicit in application code.

Related Websites

There are many websites where you can find more information on AOP in general and AOP as it pertains to Java, such as:

Dave Jarvis