What are the best practices to log an error?

2020-02-23 06:59发布

问题:

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.

回答1:

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.



回答2:

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


回答3:

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.



回答4:

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.



回答5:

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



回答6:

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 "



回答7:

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.



回答8:

Aside from technical considerations from other answers it is advisable to log a meaningful message and perhaps some steps to avoid the error in the future. Depending on the errors, of course.

You could get more out of a I/O-Error when the message states something like "Could not read from file X, you don't have the appropriate permission."

See more examples on SO or search the web.