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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)