How to format log message in Ruby
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:
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:
severity: The log level of the message (e.g., "DEBUG," "INFO," "WARN," "ERROR," "FATAL").datetime: The timestamp of when the log message is created.progname: The program name, which can be set when logging the message (not used in this example).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:
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.
-
Best Ruby Application Monitoring Tools in 2026
Ruby APM tools collect key data about the performance bottlenecks, errors and unexpected behavior of the application and provide actionable insights in a human-readable manner.
Comparisons -
How to change log level in Ruby
In Ruby, the logging level determines which log messages get recorded based on their severity. Ruby's built-in Logger class provides a simple way to handle logging and allows you to change the log ...
Questions -
Logging in Ruby on Rails
Learn how to start logging with Ruby on Rails and go from basics to best practices in no time.
Guides -
Logging in Ruby
Learn how to start logging with Ruby and go from basics to best practices in no time.
Guides