Logging

suggest change

Logging provides insight into application behavior, performance, and errors during development and production. Ruby provides a robust, thread-safe Logger class in its standard library (logger) that supports multiple severity levels, log rotation, custom formatting, and lazy block evaluation.


1. The Standard Logger Class

To start logging, require the standard library logger and instantiate a new Logger object:

require 'logger'

# Log to standard output
logger = Logger.new($stdout)

# Or log to a file
# logger = Logger.new('application.log')

Log Severity Levels

Ruby's Logger supports six severity levels (ordered from least to most severe):

Level Method Typical Use Case
DEBUG logger.debug Verbose diagnostic information for developers
INFO logger.info General operational milestones (server boot, background jobs)
WARN logger.warn Recoverable anomalies or deprecated usage
ERROR logger.error Caught exceptions, failed operations
FATAL logger.fatal Critical errors causing system crash or shutdown
UNKNOWN logger.unknown Unclassified information that must always be logged
logger.level = Logger::INFO # Ignores any messages below INFO (e.g. DEBUG)

logger.debug "This debug message will NOT appear"
logger.info  "Application starting up..."
logger.warn  "Slow database query detected: 142ms"
logger.error "Failed to send email to user 42"
logger.fatal "Unable to connect to primary database! Exiting."

Default output format:

I, [2026-10-17T16:50:12.345678 #12345]  INFO -- : Application starting up...
W, [2026-10-17T16:50:12.345890 #12345]  WARN -- : Slow database query detected: 142ms
E, [2026-10-17T16:50:12.346001 #12345] ERROR -- : Failed to send email to user 42
F, [2026-10-17T16:50:12.346123 #12345] FATAL -- : Unable to connect to primary database! Exiting.

2. File Log Rotation

Writing continuously to a single log file will eventually exhaust disk space. Ruby's Logger supports automated log rotation based on time intervals or file size.

Rotation by Time Interval

# Creates new log file daily ('daily', 'weekly', or 'monthly')
logger = Logger.new('production.log', 'daily')

Rotation by Size and File Retention

# Keep at most 10 rotated log files, each up to 10 MB in size
max_files = 10
max_size = 10 * 1024 * 1024 # 10 Megabytes

logger = Logger.new('production.log', max_files, max_size)

3. Custom Formatting and Structured JSON Logs

By default, logs are formatted as plain text strings. In production, structured JSON logs allow log ingestion systems (Datadog, ElasticSearch, AWS CloudWatch) to index and query fields efficiently.

Custom Plain-Text Formatter

logger = Logger.new($stdout)

# datetime is a Time object; datetime_format is ignored by custom formatters
logger.formatter = proc do |severity, datetime, progname, msg|
  "[#{datetime.strftime('%Y-%m-%d %H:%M:%S')}] #{severity.ljust(5)} [#{progname || 'App'}]: #{msg}\n"
end

logger.info("Server") { "Worker pool initialized with 4 processes" }
# Output: [2026-10-17 16:50:12] INFO  [Server]: Worker pool initialized with 4 processes

Structured JSON Logging

require 'logger'
require 'json'

logger = Logger.new($stdout)

logger.formatter = proc do |severity, datetime, progname, msg|
  payload = {
    timestamp: datetime.getutc.iso8601(3),
    severity: severity,
    pid: Process.pid,
    progname: progname
  }

  if msg.is_a?(Hash)
    payload.merge!(msg)
  else
    payload[:message] = msg.to_s
  end

  "#{payload.to_json}\n"
end

logger.info(action: 'user_login', user_id: 104, ip: '192.168.1.15', status: 'success')
# Output: {"timestamp":"2026-10-17T16:50:12.345Z","severity":"INFO","pid":1234,"progname":null,"action":"user_login","user_id":104,"ip":"192.168.1.15","status":"success"}

4. Lazy Evaluation with Blocks for High Performance

Constructing complex log strings (such as JSON dumps or database query summaries) consumes CPU cycles and allocates memory. If the current log level discards the message, computing the string is wasted work.

Always pass expensive log operations inside a block:

# Suboptimal: String interpolation runs regardless of logger.level
logger.debug "Active accounts: #{User.where(active: true).map(&:name).join(', ')}"

# Idiomatic & fast: Block is only executed if logger.debug? is true
logger.debug { "Active accounts: #{User.where(active: true).map(&:name).join(', ')}" }

You can also test the active level directly before executing large diagnostic routines:

if logger.debug?
  raw_dump = inspect_internal_memory_buffers
  logger.debug("MemoryDump") { raw_dump }
end

5. Logging Exceptions

When catching exceptions, always log both the exception message and its backtrace for troubleshooting:

begin
  1 / 0
rescue ZeroDivisionError => e
  logger.error("#{e.class}: #{e.message}\n\t" + e.backtrace.join("\n\t"))
end

Best Practices

  1. Follow the Twelve-Factor App Principle: In modern containerized deployments (Docker, Kubernetes), log to $stdout rather than local files on disk. The container runtime collects and ships logs to centralized platforms.
  2. Scrub Sensitive Information: Ensure passwords, credit card numbers, authorization tokens, and personal health/financial data are redacted before writing to logs.
  3. Use Correlation IDs: When logging across multiple microservices or background jobs, attach a request_id or correlation ID to every log line to trace a request across service boundaries.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents