Skip to content

Instantly share code, notes, and snippets.

@tamouse
Created June 16, 2014 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamouse/951ef62d65e959715741 to your computer and use it in GitHub Desktop.
Save tamouse/951ef62d65e959715741 to your computer and use it in GitHub Desktop.
Setting up log4r the way I like it for simple ruby apps.

Log4r Setup

One day I was sitting around trying to get some logging and output done on a rakefile, and getting tired of doing log.info("blah blah").tap{|t| puts t}, so I looked into log4r, and decided to use it. So here we are.

Set up log4r the way I like:

  • Info Messages to stdout with no decoration
  • All other messages to stderr
  • Formatted messages to log/APP.log

Logging object is available on the constant Log.

Installation

Download and copy the gist of log4r_setup.rb into your project's load path someplace (like lib/).

Add this line to your application's Gemfile:

gem 'log4r'

And then execute:

$ bundle

Or install it yourself as:

$ gem install log4r

Usage

Change the log4r_setup.rb file to your personal tastes.

Add the following to your code:

require 'log4r-setup'

Then use the following to log things:

Log.info "blah blah"
Log.error "WHOOPS!"

Contributing

Whatever, it's a gist, use it how you'd like. No license, no restrictions.

require 'pathname'
ROOT ||= Pathname.pwd
APP = ROOT.basename.to_s
LOGDIR = File.join(ROOT,"log")
LOGFILENAME = File.join(LOGDIR,"#{APP.to_s}.log")
require 'fileutils'
FileUtils.mkdir_p(LOGDIR.to_s)
require 'log4r'
require 'log4r/outputter/iooutputter'
require 'log4r/formatter/patternformatter'
Log4r::Logger.root.level = Log4r::DEBUG
Log = Log4r::Logger.new(APP.to_s)
Log.trace = true
Log.add Log4r::IOOutputter.new('stdout',
$stdout,
:formatter => Log4r::PatternFormatter.new(:pattern => "%m"))
Log.add Log4r::FileOutputter.new(APP,
:filename => LOGFILENAME.to_s,
:formatter => Log4r::PatternFormatter.new(:pattern => "%d %-6l %m (%t)"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment