Custom loggers in Ruby and Rails

Posted About 9 years ago. Visible to the public.

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
Last edit
Over 3 years ago
Emanuel
Keywords
thread, safe
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2015-04-01 15:35)