Ruby 2.4 has added additional parameters for Logger#new

Chirag Shah

Chirag Shah

April 10, 2017

This blog is part of our  Ruby 2.4 series.

The Logger class in Ruby provides a simple but sophisticated logging utility.

After creating the logger object we need to set its level.

Ruby 2.3


require 'logger'
logger = Logger.new(STDOUT)
logger.level = Logger::INFO

If we are working with ActiveRecord::Base.logger, then same code would look something like this.


require 'logger'
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.logger.level = Logger::INFO

As we can see in the both the cases we need to set the level separately after instantiating the object.

Ruby 2.4

In Ruby 2.4, level can now be specified in the constructor.


#ruby 2.4
require 'logger'
logger = Logger.new(STDOUT, level: Logger::INFO)

# let's verify it
logger.level      #=> 1

Similarly, other options such as progname, formatter and datetime_format, which prior to Ruby 2.4 had to be explicitly set, can now be set during the instantiation.

#ruby 2.3
require 'logger'
logger = Logger.new(STDOUT)
logger.level = Logger::INFO
logger.progname = 'bigbinary'
logger.datetime_format = '%Y-%m-%d %H:%M:%S'
logger.formatter = proc do |severity, datetime, progname, msg|
  "#{severity} #{datetime} ==> App: #{progname}, Message: #{msg}\n"
end

logger.info("Program started...")
#=> INFO 2017-03-16 18:43:58 +0530 ==> App: bigbinary, Message: Program started...

Here is same stuff in Ruby 2.4.

#ruby 2.4
require 'logger'
logger = Logger.new(STDOUT,
  level: Logger::INFO,
  progname: 'bigbinary',
  datetime_format: '%Y-%m-%d %H:%M:%S',
  formatter: proc do |severity, datetime, progname, msg|
    "#{severity} #{datetime} ==> App: #{progname}, Message: #{msg}\n"
  end
)

logger.info("Program started...")
#=> INFO 2017-03-16 18:47:39 +0530 ==> App: bigbinary, Message: Program started...

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.