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

1
2require 'logger'
3logger = Logger.new(STDOUT)
4logger.level = Logger::INFO
5

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

1
2require 'logger'
3ActiveRecord::Base.logger = Logger.new(STDOUT)
4ActiveRecord::Base.logger.level = Logger::INFO
5

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.

1
2#ruby 2.4
3require 'logger'
4logger = Logger.new(STDOUT, level: Logger::INFO)
5
6# let's verify it
7logger.level      #=> 1
8

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.

1#ruby 2.3
2require 'logger'
3logger = Logger.new(STDOUT)
4logger.level = Logger::INFO
5logger.progname = 'bigbinary'
6logger.datetime_format = '%Y-%m-%d %H:%M:%S'
7logger.formatter = proc do |severity, datetime, progname, msg|
8  "#{severity} #{datetime} ==> App: #{progname}, Message: #{msg}\n"
9end
10
11logger.info("Program started...")
12#=> INFO 2017-03-16 18:43:58 +0530 ==> App: bigbinary, Message: Program started...

Here is same stuff in Ruby 2.4.

1#ruby 2.4
2require 'logger'
3logger = Logger.new(STDOUT,
4  level: Logger::INFO,
5  progname: 'bigbinary',
6  datetime_format: '%Y-%m-%d %H:%M:%S',
7  formatter: proc do |severity, datetime, progname, msg|
8    "#{severity} #{datetime} ==> App: #{progname}, Message: #{msg}\n"
9  end
10)
11
12logger.info("Program started...")
13#=> INFO 2017-03-16 18:47:39 +0530 ==> App: bigbinary, Message: Program started...
14

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.