How to change log level in Ruby

Better Stack Team
Updated on August 25, 2023

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 level dynamically. Here's how you can change the log level:

 
require 'logger'

# Create a logger instance
logger = Logger.new(STDOUT)

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

# Log some messages at different levels
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
logger.warn("This is a warning message")  # This will be printed
logger.error("This is an error message")  # This will be printed
logger.fatal("This is a fatal message")   # This will be printed

# Change the log level to a different level (e.g., DEBUG)
logger.level = Logger::DEBUG

# Log some messages again
logger.debug("This is a debug message")   # This will be printed now
logger.info("This is an info message")    # This will be printed
logger.warn("This is a warning message")  # This will be printed
logger.error("This is an error message")  # This will be printed
logger.fatal("This is a fatal message")   # This will be printed

In the example above, we create a logger instance and set its log level to Logger::INFO, which means only messages with severity INFO and above (WARNING, ERROR, FATAL) will be printed. If you change the log level to Logger::DEBUG, it will include all log messages, including DEBUG level messages.

You can set the log level to any of the following constants:

  • Logger::DEBUG
  • Logger::INFO
  • Logger::WARN
  • Logger::ERROR
  • Logger::FATAL

Choose the appropriate log level based on the desired verbosity of your application's logs. It's a good practice to set the log level according to the environment or configuration to control the amount of logging information displayed in different scenarios.

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 →