You’ve used the Ruby Logger if you’ve ever built a Rails app, or even started up a development server and watched the output scroll by. But because Rails provides logging out of the box, it’s not often necessary to think about it.

If you’re building a plain old ruby app, however, logging is something you might think about implementing at some point. When that time comes, Ruby’s built-in Logger class has your back.

Instantiating a Ruby Logger

require 'logger'

logger = Logger.new($stdout)

That’s all there is to it.

Of course instead of writing to stdout, you could also write to stderr, a file (and optionally set up rotation of log files) or even a custom class that implements write and close.

The custom class option is useful if you want to log to both stdout and a file, want to create a dummy log for testing, or if you are using something like highline to do your IO.

Configuring your Log

Severity threshold

Logger has the following severity levels from least to most severe:

Logger::DEBUG, Logger::INFO, Logger::WARN, Logger::ERROR, Logger::FATAL, and Logger::UNKNOWN

These are the constants you can set the severity threshold to. (They correspond to 0, 1, 2, 3, 4, and 5 respectively, but use the constants whenever possible.) Anything below the severity threshold will be ignored.

Set the threshold like so:

logger.level = Logger::WARN

Better yet, set environment-specific values in the environment’s dotenv file.

App name

logger.progname = 'MyApp'

Formatter

logger.formatter = Formatter.new

The default is an instance of the Formatter class. If you want to specify your own, you can subclass Formatter, or use a proc. The following example would print only the message, ignoring everything else.

logger.formatter = proc { |severity, time, progname, msg| msg }

Sending messages to the Ruby Logger

The Ruby Logger has a method for each of the error levels

logger.info "Doing things now!"
#...
logger.error "Failed to complete task"

For more information, check out the documentation.