Custom loggers in Ruby and Rails

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')

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'
Henning Koch About 9 years ago