Logging

Logger stdlib

Logger lives in the standard library, so no gems are needed for basic logging.

Create a logger with a destination such as STDOUT and write a message with info. Run the script and the line appears in the terminal with a timestamp and a severity label.

require "logger" log = Logger.new($stdout) log.info("server started")

Levels

Levels filter noise by importance. Set level to INFO to hide debug messages while keeping warnings and errors.

Each message method matches a level, from debug for small details to fatal for crashes that stop the program.

require "logger" log = Logger.new($stdout) log.level = Logger::INFO log.debug("hidden detail") log.warn("visible warning")

Custom formatter

The default line format is readable but often too long. Replace formatter with a proc to control every line.

The block receives severity, time, progname, and message. Return a string with a newline at the end.

require "logger" log = Logger.new($stdout) log.formatter = proc do |severity, time, progname, msg| "#{time} #{severity}: #{msg}\n" end log.info("ready")

Rotate logs

Long running programs must not grow one file forever. Pass a rotation policy when the log points at a file.

With daily rotation Ruby keeps one file per day and starts a fresh file at midnight automatically.

require "logger" log = Logger.new("app.log", "daily") log.info("rotated daily")

Next: What is inside a gem

Article author: Arthur Isaev