How to format log message in Ruby

Better Stack Team
Updated on August 25, 2023

In Ruby, you can format log messages using the built-in Logger class. The Logger class provides various options for customizing the log message format. You can include timestamps, log levels, and other relevant information in the log message format. Here's how you can format log messages:

 
require 'logger'

# Create a logger instance and specify the log file
logger = Logger.new('application.log')

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

# Set the log level (e.g., INFO)
logger.level = Logger::INFO

# Log some messages
logger.debug("This is a debug message")   # This won't be printed because the log level is set to INFO
logger.info("This is an info message")    # This will be printed with the custom format
logger.warn("This is a warning message")  # This will be printed with the custom format
logger.error("This is an error message")  # This will be printed with the custom format
logger.fatal("This is a fatal message")   # This will be printed with the custom format

In this example, we create a logger instance and set it to log messages to a file called application.log. The logger.formatter attribute is assigned a proc (a block of code) that customizes the log message format. The proc takes four arguments:

  1. severity: The log level of the message (e.g., "DEBUG," "INFO," "WARN," "ERROR," "FATAL").
  2. datetime: The timestamp of when the log message is created.
  3. progname: The program name, which can be set when logging the message (not used in this example).
  4. msg: The actual log message.

In the proc, we use datetime.strftime to format the timestamp in the desired way. %Y-%m-%d %H:%M:%S represents the format "year-month-day hour:minute:second." You can customize the format according to your preferences.

The logger.level is set to Logger::INFO, which means only messages with severity INFO and above will be printed. If you want to include DEBUG level messages in the log, you can change the log level to Logger::DEBUG.

The resulting log messages will be formatted as follows:

 
2023-07-28 12:34:56 [INFO] This is an info message
2023-07-28 12:34:57 [WARN] This is a warning message
2023-07-28 12:34:58 [ERROR] This is an error message
2023-07-28 12:34:59 [FATAL] This is a fatal message

You can modify the logger.formatter block to customize the log message format further as per your requirements.

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 →