Recipe 17.5. Adding Logging to Your ApplicationProblemYou want to make your application log events or diagnostic data to a file or stream. You want verbose logging when your application is in development, and more taciturn logging when in production. SolutionUse the In most cases, you'll share a single
You can then call the instance methods of Logger to send messages to the log at various levels of severity. From least to most severe, the instance methods are Logger#debug, Logger#info, Logger#warn, Logger#error, and Logger#fatal. This code uses the application's logger to print a debugging message, and (at a higher severity) as part of error-handling code.
To change the log level, simply assign the appropriate constant to level:
Now our logger will ignore all log messages except those with severity ERROR or FATAL:
DiscussionRuby's standard logging system works like Java's oft-imitated Log4J. The Logger object centralizes all the decisions about whether a particular message is important enough to be written to the log. When you write code, you simply assume that all the messages will be logged. At runtime, you can get a more or a less verbose log by changing the log level. A production application usually has a log level of The DEBUG log level is useful for step-by-step diagnostics of a complex task. The ERROR level is often used when handling exceptions: if the program can't solve a problem, it logs the exception rather than crash and expects a human administrator to deal with it. The FATAL level should only be used when the program cannot recover from a problem, and is about to crash or exit. If your log is being stored in a file, you can have Logger rotate or replace the log file when it get too big, or once a certain amount of time has elapsed:
If the default log entries are too verbose for you, you have a couple of options. The simplest is to set datetime_format to a more concise date format. This code gets rid of the milliseconds:
If that's not enough for you, you can replace the call method that formats a message for the log:
See Also
|
Friday, November 6, 2009
Recipe 17.5. Adding Logging to Your Application
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment