How to log to file and console in Ruby

Better Stack Team
Updated on August 25, 2023

To log to both a file and the console (standard output) in Ruby, you can create two logger instances: one for the file and another for the console. Both loggers will be configured to log messages at the desired log level and will use different log files for file logging and the console for console logging. Here's an example of how to achieve this:

 
require 'logger'

# Create a logger instance for file logging
file_logger = Logger.new('application.log', 'daily')  # Log will be rotated daily
file_logger.level = Logger::INFO

# Customize the log message format for file_logger (optional)
file_logger.formatter = proc do |severity, datetime, progname, msg|
  "#{datetime.strftime('%Y-%m-%d %H:%M:%S')} [#{severity}] #{msg}\n"
end

# Create a logger instance for console logging
console_logger = Logger.new(STDOUT)
console_logger.level = Logger::DEBUG

# Customize the log message format for console_logger (optional)
console_logger.formatter = proc do |severity, datetime, progname, msg|
  "#{severity} - #{msg}\n"
end

# Log some messages
file_logger.info("This is an info message")   # Will be logged to the file
file_logger.warn("This is a warning message") # Will be logged to the file

console_logger.debug("This is a debug message")   # Will be logged to the console
console_logger.info("This is another info message")   # Will be logged to the console

In this example, we create two logger instances: file_logger and console_logger. The file_logger is configured to log messages to a file named 'application.log', and the log file will be rotated daily.

The console_logger is set to log messages to the console using STDOUT. This means log messages sent to console_logger will be displayed on the standard output (usually the terminal or console window).

Each logger can have its own log level and log message format, allowing you to customize the behavior for each destination independently.

Please note that the log message format and log rotation settings are optional and can be adjusted based on your specific requirements. The above example is a basic illustration of how to log to both a file and the console in Ruby.

To learn more about logging in Ruby, visit Better Stack Community.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →