Ruby Logging

The Logger class in the Ruby standard library, helps write log messages to a file or stream. It supports time- or size-based rolling of log files. Messages can be assigned severities, and only those messages at or above the logger's current reporting level will be logged.

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 Logger::INFO or Logger::WARN. From least to most severe, the instance methods are Logger.debug,, Logger.warn, Logger.error, and Logger.fatal.

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 gets too big, or once a certain amount of time has elapsed:

The code below, uses the application's logger to print a debugging message, and (at a higher severity) as part of error-handling code.

The contents of the file log_file.log is:

Now try to call the method by:

The contents of the file log_file.log is:

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. The contents of the file log_file.log is:

Note: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various Ruby Gurus), my acknowledgment and thanks to all of them. Much of the material on and in the course at is drawn primarily from the Programming Ruby book, available from The Pragmatic Bookshelf.