Read more

Custom loggers in Ruby and Rails

Henning Koch
April 01, 2015Software engineer at makandra GmbH

File logger

If you need to log to a file you can use Ruby's Logger class:

require 'logger'

log = Logger.new('log/mylog.log')
log.info 'Some information'
log.debug 'Debugging hints'
log.error StandardError.new('Something went wrong')
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Logger does a number of things well:

  • Message type (info / debug / error) is logged
  • Log entries are timestamped
  • Writing log output is synchronized between threads
  • Logged errors are printed with full backtraces

If you don't like the output format, you can define a custom formatter.

I haven't found a nice way to make Logger auto-flush after every line, but there are hacks.

Stdout logger

require 'logger'

log = Logger.new(STDOUT)
log.info 'Some information'
Posted by Henning Koch to makandra dev (2015-04-01 17:35)