Skip to content

Commit

Permalink
Initial version
Browse files Browse the repository at this point in the history
  • Loading branch information
bmc committed Apr 12, 2012
0 parents commit a3fe019
Show file tree
Hide file tree
Showing 8 changed files with 580 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
@@ -0,0 +1,2 @@
*.gem
rdoc
31 changes: 31 additions & 0 deletions LICENSE.md
@@ -0,0 +1,31 @@
Grizzled Rails Logger is released under a **BSD license**, adapted from
<http://opensource.org/licenses/bsd-license.php>

Copyright &copy; 2012 Brian M. Clapper.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

* Neither the names "clapper.org", "Grizzled Rails Logger", nor the names of
any contributors may be used to endorse or promote products derived from this
software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
190 changes: 190 additions & 0 deletions README.md
@@ -0,0 +1,190 @@
# grizzled-rails-logger

*Grizzled Rails Logger* is a Ruby gem that provides an add-on for the stock
Rails 3 logger.

The `Grizzled::Rails::Logger` module augments the Rails 3
`ActiveSupport::BufferedLogger` class, providing some additional
capabilities, including:

* Configurable colorized logging (colorized by severity).
* Simple timestamp configuration.
* The ability to include the PID in each message.
* The ability to flatten the log output, removing spurious newlines, so that
each message occupies only one line.
* An `exception` message that dumps an exception backtrace to the log

## Installation for Rails 3

Add the following to your `Gemfile`, and run `bundle install`:

gem 'grizzled-rails-logger'

If you want the development version of the gem, use:

gem 'grizzled-rails-logger', :git => 'git://github.com/bmc/grizzled-rails-logger.git'

## Configuration

Becaue *Grizzled Rails Logger* merely adds to the standard Rails logger,
you can continue to all the usual capabilities of the Rails logger (such as,
for instance, tagged logged).

To Configure *Grizzled Rails Logger*, add a section like the following to your
`config/application.rb` file or your individual environment file:

Grizzled::Rails::Logger.configure do |cfg|
# Configuration data goes here
end

The default configuration is equivalent to the following:

Grizzled::Rails::Logger.configure do |cfg|
cfg.flatten = true
cfg.format = '%[T] (%S) %P %M'
cfg.timeformat = '%Y/%m/%d %H:%M:%S'
cfg.colorize = true
cfg.colors = {
:debug => Term::ANSIColor.cyan,
:warn => Term::ANSIColor.yellow + Term::ANSIColor.bold,
:fatal => Term::ANSIColor.red + Term::ANSIColor.bold,
:error => Term::ANSIColor.red
}
end

Each configuration option is described in more detail, below.

### Colorization

By default, *Grizzled Rails Logger* colorizes logging output, using ANSI
terminal escape sequences (as defined by the [term-ansicolor][] gem).

You can disable colorization by setting the `colorize` option to `false`:

Grizzled::Rails::Logger.configure do |cfg|
cfg.colorize = false
end

You can also change the colors associated with each severity. Suppose, for
instance, that you want INFO messages (which normally aren't colorized) to be
white, and you wanted DEBUG messages (which are normally cyan) to be bold blue.
You'd simply reconfigure those values, as shown below:

Grizzled::Rails::Logger.configure do |cfg|
cfg.colors[:debug] = Term::ANSIColor.bold + Term::ANSIColor.blue
cfg.colors[:info] = Term::ANSIColor.white
end

`Term::ANSIColor` is automatically included for you.

**WARNING** *Grizzled Rails Logger* does not verify that the values you
store in the color settings are legal ANSI sequences. The following is
perfectly legal, though probably not what you want:

Grizzled::Rails::Logger.configure do |cfg|
cfg.colors[:debug] = "red"
end

With that setting, a debug message that normally looks like this:

[2012/04/12 14:43:22] (DEBUG) 9816 My debug message

will, instead, look like this:

red[2012/04/12 14:43:22] (DEBUG) 9816 My debug message

### Exception logging

*Grizzled Rails Logger* adds an `exception()` method, providing an easy way
to dump a rescued exception and its backtrace:

begin
# Some dangerous operation
rescue Exception => ex
logger.exception("Error while doing dangerous thing", ex)
end

The method takes three parameters, one of which is optional:

* `message` - a message to be displayed along with the exception. Can be nil,
but must be supplied.
* `exception` - the exception to be dumped.
* `progname` - program name. Optional; defaults to nil.

The exception is dumped at severity level ERROR.

Regardless of the setting of `flatten` (see below), the exception's backtrace
is always displayed on multiple lines.

### Flattening

The default Rails logger includes lots of newlines in its log messages. For
example:

[2012/04/12 14:59:48] (INFO) 10102 [659d08c8cbcf3ddf543ca3710cee2771]

Started GET "/about" for 127.0.0.1 at 2012-04-12 14:59:48 -0400

*Grizzled Rails Logger* automatically flattens log messages to a single line:

[2012/04/12 14:59:48] (INFO) 10102 [659d08c8cbcf3ddf543ca3710cee2771] Started GET "/about" for 127.0.0.1 at 2012-04-12 14:59:48 -0400

If you prefer *not* to flatten log messages, disable the `flatten` setting:

Grizzled::Rails::Logger.configure do |cfg|
cfg.flatten = false
end

**NOTE:** Exception backtraces are *never* flattened.

### Formatting

Two settings control formatting.

`format`

The `format` setting controls overall message formatting. Four escape
sequences control how the message is assembled:

* "%T" - Any "%T" sequences in the format are replaced by the current time.
The format of the time is controlled by `timeformat` (see below).
* "%P" - Any "%P" sequences are replaced with the process ID of the Rails
instance that's emitting the message.
* "%S" - Any "%S" sequences are replaced with an upper case string
representation of the message's severity (e.g., "ERROR", "WARN").
* "%M" - Any "%M" sequences are replaced by the message, including any
tags inserted via tagged logging.

Any other characters, including blanks, are emitted verbatim.

It's legal (but probably silly) to include a sequence multiple times. If you
don't want a specific value to be logged, simply omit its escape sequence
from the format.

The default format is: `[%T] (%S) %P %M`.

For example, to change the log format to omit the PID, use:

Grizzled::Rails::Logger.configure do |cfg|
cfg.format = '[%T] (%S) %M'
end


`timeformat`

The `timeformat` setting controls how the current time (see "%T", above) is
formatted. `timeformat` is a [strftime][] format string.

The default time format is: `%Y/%m/%d %H:%M:%S`

## Alternatives

Alternatives to this gem include:

* Paul Dowman's [better_logging][] gem
* [itslog][]

[better_logging]: https://github.com/pauldowman/better_logging
[itslog]: https://github.com/johnnytommy/itslog
[term-ansicolor]: https://github.com/flori/term-ansicolor
[strftime]: http://strftime.net/
118 changes: 118 additions & 0 deletions Rakefile
@@ -0,0 +1,118 @@
#
#
# NOTE: Man pages use the 'ronn' gem. http://rtomayko.github.com/ronn/

require 'rake/clean'
require 'pathname'

PACKAGE = 'grizzled-rails-logger'
GEMSPEC = "#{PACKAGE}.gemspec"
RDOC_OUT_DIR = 'rdoc'
GH_PAGES_DIR = File.join('..', 'gh-pages')
RDOC_PUBLISH_DIR = File.join(GH_PAGES_DIR, 'apidocs')
RUBY_SRC_DIR = 'lib'
RUBY_FILES = FileList[File.join(RUBY_SRC_DIR, '**', '*.rb')]

def load_gem(spec)
eval File.open(spec).readlines.join('')
end

def gem_name(spec)
gem = load_gem(spec)
version = gem.version.to_s
"#{PACKAGE}-#{version}.gem"
end

GEM = gem_name(GEMSPEC)
CLEAN << [RDOC_OUT_DIR, GEM]

# ---------------------------------------------------------------------------
# Tasks
# ---------------------------------------------------------------------------

task :default => :build

desc "Build everything"
task :build => [:test, :gem, :doc]

desc "Synonym for 'build'"
task :all => :build

desc "Build the gem (#{GEM})"
task :gem => GEM

file GEM => RUBY_FILES + ['Rakefile', GEMSPEC] do |t|
require 'rubygems/builder'
if !defined? Gem
raise StandardError.new("Gem package not defined.")
end
spec = eval File.new(GEMSPEC).read
Gem::Builder.new(spec).build
end

desc "Build the documentation, locally"
task :doc => :rdoc

file 'rdoc' => RUBY_FILES do |t|
require 'rdoc/rdoc'
puts('Running rdoc...')
mkdir_p File.dirname(RDOC_OUT_DIR) unless File.exists? RDOC_OUT_DIR
r = RDoc::RDoc.new
r.document(['-U', '-m', "#{RUBY_SRC_DIR}/grizzled.rb", '-o', RDOC_OUT_DIR,
RUBY_SRC_DIR])
end

desc "Install the gem"
task :install => :gem do |t|
require 'rubygems/installer'
puts("Installing from #{GEM}")
Gem::Installer.new(GEM).install
end

desc "Publish the gem"
task :publish => :gem do |t|
sh "gem push #{GEM}"
end

desc "Publish the docs. Not really of use to anyone but the author"
task :pubdoc => [:pubrdoc, :pubchangelog]

task :pubrdoc => :doc do |t|
target = Pathname.new(RDOC_PUBLISH_DIR).expand_path.to_s
cd RDOC_OUT_DIR do
mkdir_p target
cp_r '.', target
end
end

desc "Synonym for 'pubchangelog'"
task :changelog

desc "Publish the change log. Not really of use to anyone but the author"
task :pubchangelog do |t|
File.open(File.join(GH_PAGES_DIR, 'CHANGELOG.md'), 'w') do |f|
f.write <<EOF
---
title: Change Log for Grizzled Ruby
layout: default
---
EOF
f.write File.open('CHANGELOG.md').read
f.close
end
end

task :pub

desc "Alias for 'docpub'"
task :docpub => :pubdoc

desc "Run the unit tests"
task :test do |t|
FileList[File.join('test', '**', 't[cs]_*.rb')].each do |tf|
cd File.dirname(tf) do |dir|
ruby File.basename(tf)
end
end
end
30 changes: 30 additions & 0 deletions grizzled-rails-logger.gemspec
@@ -0,0 +1,30 @@
Gem::Specification.new do |s|

s.name = 'grizzled-rails-logger'
s.version = '0.1.0'
s.date = '2012-04-12'
s.summary = 'A custom Rails 3 logger'
s.authors = ['Brian M. Clapper']
s.license = 'BSD'
s.email = 'bmc@clapper.org'
s.homepage = 'http://software.clapper.org/grizzled-rails-logger'

s.description = <<-ENDDESC
A custom Rails 3 logger
ENDDESC

s.require_paths = ['lib']

s.add_dependency('term-ansicolor', '>= 1.0.7')

# = MANIFEST =
s.files = Dir.glob('[A-Z]*')
s.files += Dir.glob('*.gemspec')
s.files += Dir.glob('lib/**/*')
s.files += Dir.glob('rdoc/**/*')

# = MANIFEST =
s.test_files = Dir.glob('test/**/tc_*.rb')
end


0 comments on commit a3fe019

Please sign in to comment.