├── .gitignore ├── Gemfile ├── Gemfile.lock ├── README.textile ├── Rakefile ├── better_logging.gemspec └── lib ├── better_logging.rb └── better_logging └── better_logging.rb /.gitignore: -------------------------------------------------------------------------------- 1 | pkg/ 2 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'http://rubygems.org' 2 | gem 'rake' 3 | gemspec 4 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | PATH 2 | remote: . 3 | specs: 4 | better_logging (1.0.0) 5 | 6 | GEM 7 | remote: http://rubygems.org/ 8 | specs: 9 | rake (0.9.2.2) 10 | 11 | PLATFORMS 12 | ruby 13 | 14 | DEPENDENCIES 15 | better_logging! 16 | rake 17 | -------------------------------------------------------------------------------- /README.textile: -------------------------------------------------------------------------------- 1 | h1. "Better Logging" Rails plugin 2 | 3 | NOTE: I'm not maintaining this project any more, but @foodforarabbit is maintaining an active fork which I recommend: 4 | 5 | "https://github.com/foodforarabbit/better_logging/":https://github.com/foodforarabbit/better_logging/ 6 | 7 | This is a Rails plugin that improves the log format, and adds an optional "Exception" parameter to the warn() and error() methods to print a stack trace automatically. 8 | 9 | h2. Improved log format 10 | 11 | It adds severity level (with colour, if colour is enabled), time (in "ISO8601 format":http://en.wikipedia.org/wiki/ISO_8601), hostname and process ID to each log line, and it and adds warn() and exception() methods that take an exception as an argument and print the stack trace. 12 | 13 | For example, here's how the Rails log looks normally, without the better_logging plugin installed: 14 | 15 |
16 | Session ID: 7eeb00aa62b395698a28bf033e56b7c5 17 | Parameters: {"action"=>"show", "id"=>"1", "controller"=>"people"} 18 | User Load (0.4ms) SELECT * FROM `users` WHERE (id = '1') LIMIT 1 19 | User Columns (2.1ms) SHOW FIELDS FROM `users` 20 | Rendering template within layouts/application 21 | Rendering people/show 22 | Rendered layouts/_head (3.1ms) 23 | Rendered layouts/_navigation (2.2ms) 24 | Adding Cache-Control header 25 | Completed in 164ms (View: 116, DB: 21) | 200 OK [http://localhost/people/1] 26 |27 | 28 | Here's how the same thing would look with the better_logging plugin installed in development mode. Note that the severity (INFO, WARN, ERROR, etc), is printed in colour (if colour is enabled for the log, which it is by default in development mode). 29 | 30 |
31 | INFO Session ID: 7eeb00aa62b395698a28bf033e56b7c5 32 | INFO Parameters: {"action"=>"show", "id"=>"1", "controller"=>"people"} 33 | DEBUG User Load (0.4ms) SELECT * FROM `users` WHERE (id = '1') LIMIT 1 34 | DEBUG User Columns (2.1ms) SHOW FIELDS FROM `users` 35 | INFO Rendering template within layouts/application 36 | INFO Rendering people/show 37 | DEBUG Rendered layouts/_head (3.1ms) 38 | DEBUG Rendered layouts/_navigation (2.2ms) 39 | INFO Adding Cache-Control header 40 | INFO Completed in 164ms (View: 116, DB: 21) | 200 OK [http://localhost/people/1] 41 |42 | 43 | And here's how it would look with the better_logging plugin installed in production mode, on a host named "akash", with process id 27471: 44 | 45 |
46 | akash.27471 2011-10-14T15:39:17.063613-04:00 INFO Session ID: 7eeb00aa62b395698a28bf033e56b7c5 47 | akash.27471 2011-10-14T15:39:17.063613-04:00 INFO Parameters: {"action"=>"show", "id"=>"1", "controller"=>"people"} 48 | akash.27471 2011-10-14T15:39:17.063613-04:00 INFO Rendering template within layouts/application 49 | akash.27471 2011-10-14T15:39:17.063613-04:00 INFO Rendering people/show 50 | akash.27471 2011-10-14T15:39:17.063613-04:00 INFO Adding Cache-Control header 51 | akash.27471 2011-10-14T15:39:17.063613-04:00 INFO Completed in 164ms (View: 116, DB: 21) | 200 OK [http://localhost/people/1] 52 |53 | 54 | 55 | And here's how it would look in production mode on a host with a long name. This host name is "myreallybigserver-7.mydomain.com". 56 | 57 |
58 | igserver-7.27471 2011-10-14T15:39:17.063613-04:00 INFO Session ID: 7eeb00aa62b395698a28bf033e56b7c5 59 | igserver-7.27471 2011-10-14T15:39:17.063613-04:00 INFO Parameters: {"action"=>"show", "id"=>"1", "controller"=>"people"} 60 | igserver-7.27471 2011-10-14T15:39:17.063613-04:00 INFO Rendering template within layouts/application 61 | igserver-7.27471 2011-10-14T15:39:17.063613-04:00 INFO Rendering people/show 62 | igserver-7.27471 2011-10-14T15:39:17.063613-04:00 INFO Adding Cache-Control header 63 | igserver-7.27471 2011-10-14T15:39:17.063613-04:00 INFO Completed in 164ms (View: 116, DB: 21) | 200 OK [http://localhost/people/1] 64 |65 | 66 | Note that the hostname & process ID is added to the beginning of each line of a multi-line log statement. So even if you call logger.error() with a string that has newlines in it, the host & process ID will be added to each line, not only the first. 67 | 68 | This is so that you can filter your log with a regular expression like /^igserver-7\.27471/ and not miss lines. 69 | 70 | 71 | h2. Improved warn() and error() methods 72 | 73 | The warn() and error() methods now allow an Exception object to be given as an optional second parameter. If the exception is given, then the stack trace will be automatically logged. 74 | 75 | For example: 76 | 77 |
78 | begin 79 | # do something that raises an exception 80 | rescue Exception => e 81 | Rails.logger.error "Oops", e 82 | end 83 |84 | 85 | The above code will log "Oops", and then log the stack trace. 86 | 87 | 88 | h2. Why? 89 | 90 | h3. Adding severity 91 | 92 | All lines printed to the log have a "severity" level, this can be "DEBUG", "WARN", "ERROR", etc. Normally this isn't included in the log output, so it's impossible to search a log file for warnings or errors, or filter based on severity, and it's just a useful thing to see. 93 | 94 | h3. Adding hostname and process ID 95 | 96 | Normally, when not in development mode, a Rails app consists of more than one Rails process responding to requests at the same time. Those processes may be printing lines to the log at the same time, and it's hard to know which process printed a certain line. 97 | 98 | Also, it's common to have multiple servers working in parallel, and a user's session might involve requests to multiple servers. If the log files are combined it's useful to know which process on which server printed a given line. 99 | 100 | This makes it possible to filter a Rails log to show output from one process only, and to combine the log files from multiple servers. 101 | 102 | The hostname is truncated (by default to 10 characters but this is configurable). The end of the hostname is printed, rather than the beginning, because often the end of the hostname is more unique. 103 | 104 | h3. Adding a timestamp 105 | 106 | This should be pretty obvious, but the log file isn't too useful for debugging errors if you don't know what time anything happened. The first line printed by each Rails action does include a timestamp, but it's common to have other processes that aren't responding to web requests, and these are likely printing to your Rails log also (e.g. a background queue, etc). 107 | 108 | h3. Adding a custom string 109 | 110 | You can also add a custom string that will appear as the first column in the output, for example: 111 | 112 |
113 | my-custom-string igserver-7.27471 2011-10-14T15:39:17.063613-04:00 INFO Completed in 164ms (View: 116, DB: 21) | 200 OK [http://localhost/people/1] 114 |115 | 116 | 117 | h2. Why not log to syslog? 118 | 119 | It's a single point of failure, and it will become a scalability bottleneck. There are good arguments for using a common syslog server, but I prefer to just log locally on each server and combine them via post-processing. 120 | 121 | 122 | h2. Installation 123 | 124 | Add to your Gemfile: 125 | @gem 'better_logging'@ 126 | 127 | 128 | h2. Configuration 129 | 130 | By default it behaves differently in development mode, it doesn't log the time, process ID or hostname. If RAILS_ENV is not "development" those will be logged. 131 | 132 | There are some options that can be set, add these lines to an initializer: 133 | 134 | @PaulDowman::RailsPlugins::BetterLogging.verbose = false@ 135 | * This suppresses printing of the hostname, process ID and timestamp. This defaults to false in development mode, true otherwise. 136 | 137 | @PaulDowman::RailsPlugins::BetterLogging.hostname_maxlen = 15@ 138 | * This sets the maximum number of characters of the hostname that will be printed. The beginning of the hostname is truncated, rather than the end, because often the end of the hostname is more unique than the beginning. The default is 10. 139 | 140 | @PaulDowman::RailsPlugins::BetterLogging.custom = "my-custom-string"@ 141 | * This sets a custom string that will be printed at the beginning of the output, if desired. 142 | 143 | 144 | h2. Viewing log files 145 | 146 | On OS X I like to use Console.app to view log files. It can load huge files easily and it can filter based on a regular expression (e.g. you can show only lines from one particular Rails process). On *NIX I just use "less". 147 | 148 | 149 | h2. Requirements 150 | 151 | Rails 3.0+. 152 | 153 | I haven't tested this on Rails 2.3.x since it became a RubyGem, so it might not work and I won't continue to support Rails 2. However, you can use the "Rails-2.3 branch":https://github.com/pauldowman/better_logging/tree/Rails-2.3 even though it probably won't be updated. 154 | 155 | 156 | h2. How does it work? 157 | 158 | It works by modifying ActiveSupport::BufferedLogger (the Rails logger class). 159 | 160 | 161 | h2. License 162 | 163 | This is distributed under a Creative Commons "Attribution-Share Alike" license. For details see: 164 | "http://creativecommons.org/licenses/by-sa/3.0/":http://creativecommons.org/licenses/by-sa/3.0/ 165 | 166 | 167 | h2. Bugs? 168 | 169 | This was written by "Paul Dowman":http://pauldowman.com/. 170 | 171 | Please let me know if you find any bugs. File a "bug report":http://github.com/pauldowman/better_logging/issues or, if you don't have a GitHub account then "contact me directly":http://pauldowman.com/contact/. 172 | 173 | Or even better, send me a patch or GitHub pull request! 174 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require "bundler/gem_tasks" 2 | -------------------------------------------------------------------------------- /better_logging.gemspec: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | $:.push File.expand_path("../lib", __FILE__) 3 | 4 | Gem::Specification.new do |s| 5 | s.name = "better_logging" 6 | s.version = "1.0.3" 7 | s.authors = ["Paul Dowman"] 8 | s.email = ["paul@pauldowman.com"] 9 | s.homepage = "https://github.com/pauldowman/better_logging" 10 | s.summary = %q{Better logging for Rails} 11 | s.description = %q{A Rails plugin that improves the log format, and adds an optional "Exception" parameter to the warn() and error() methods to print a stack trace automatically.} 12 | 13 | s.rubyforge_project = "better_logging" 14 | 15 | s.files = `git ls-files`.split("\n") 16 | s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") 17 | s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } 18 | s.require_paths = ["lib"] 19 | end 20 | -------------------------------------------------------------------------------- /lib/better_logging.rb: -------------------------------------------------------------------------------- 1 | require 'active_support' 2 | require 'better_logging/better_logging' 3 | 4 | module BetterLogging 5 | class Railtie < ::Rails::Railtie 6 | ActiveSupport::BufferedLogger.send(:include, ::PaulDowman::RailsPlugins::BetterLogging) 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /lib/better_logging/better_logging.rb: -------------------------------------------------------------------------------- 1 | # This module, when included into ActiveSupport::BufferedLogger, improves the 2 | # logging format. See the README file for more info. 3 | # 4 | # This is distributed under a Creative Commons "Attribution-Share Alike" 5 | # license: for details see: 6 | # http://creativecommons.org/licenses/by-sa/3.0/ 7 | # 8 | module PaulDowman 9 | module RailsPlugins 10 | module BetterLogging 11 | 12 | LENGTH = ActiveSupport::BufferedLogger::Severity.constants.map{|c| c.to_s.length}.max 13 | 14 | def self.included(base) 15 | base.class_eval do 16 | alias_method_chain :add, :extra_info 17 | alias_method_chain :error, :exception_param 18 | alias_method_chain :warn, :exception_param 19 | end 20 | 21 | # Get the length to format the output so that the pid column lines up. 22 | # The severity levels probably won't change but this avoids hard-coding 23 | # them anyway, just in case. 24 | # Most of this is done with class_eval so it should only be done once 25 | # while the class is being loaded. 26 | if_stmts = "" 27 | for c in ActiveSupport::BufferedLogger::Severity.constants 28 | if_stmts += <<-EOT 29 | if severity == #{c} 30 | severity_name = sprintf("%1$*2$s", "#{c}", #{LENGTH * -1}) 31 | use_colour = false 32 | if Rails.version.to_i >= 3 33 | use_colour = true if ActiveSupport::LogSubscriber.colorize_logging 34 | else 35 | use_colour = true if defined?(ActiveRecord) && ActiveRecord::Base.colorize_logging 36 | end 37 | if use_colour 38 | if severity == INFO 39 | severity_name = "\033[32m" + severity_name + "\033[0m" 40 | elsif severity == WARN 41 | severity_name = "\033[33m" + severity_name + "\033[0m" 42 | elsif severity == ERROR || severity == FATAL 43 | severity_name = "\033[31m" + severity_name + "\033[0m" 44 | end 45 | end 46 | return severity_name 47 | end 48 | EOT 49 | end 50 | base.class_eval <<-EOT, __FILE__, __LINE__ 51 | def self.severity_name(severity) 52 | #{if_stmts} 53 | return "UNKNOWN" 54 | end 55 | EOT 56 | end 57 | 58 | def self.fraction_digits=(num) 59 | @@fraction_digits = num 60 | end 61 | 62 | def self.verbose=(boolean) 63 | @@verbose = boolean 64 | end 65 | 66 | def self.custom=(string) 67 | @@custom = string 68 | @@line_prefix = format_line_prefix 69 | end 70 | 71 | def self.hostname_maxlen=(integer) 72 | @@hostname_maxlen = integer 73 | @@line_prefix = format_line_prefix 74 | end 75 | 76 | def self.format_line_prefix 77 | if @@full_hostname.length < @@hostname_maxlen 78 | hostname = @@full_hostname 79 | else 80 | hostname = @@full_hostname[-(@@hostname_maxlen)..-1] 81 | end 82 | 83 | line_prefix = sprintf("%1$*2$s", "#{hostname}.#{@@pid} ", -(7 + hostname.length)) 84 | line_prefix = "#{@@custom} #{line_prefix}" if @@custom 85 | return line_prefix 86 | end 87 | 88 | def self.get_hostname 89 | `hostname -s`.strip 90 | end 91 | 92 | # The following are cached as class variables for speed. 93 | 94 | # These are configurable, put something like the following in an initializer: 95 | # PaulDowman::RailsPlugins::BetterLogging.verbose = false 96 | @@verbose = Rails.env != "development" 97 | @@full_hostname = get_hostname 98 | @@hostname_maxlen = 10 99 | @@custom = nil 100 | @@fraction_digits = 6 101 | 102 | 103 | # These are not configurable 104 | @@pid = $$ 105 | @@line_prefix = format_line_prefix 106 | 107 | 108 | # the cached pid can be wrong after a fork(), this checks if it has changed and 109 | # re-caches the line_prefix 110 | def update_pid 111 | if @@pid != $$ 112 | @@pid = $$ 113 | @@line_prefix = BetterLogging.format_line_prefix 114 | end 115 | end 116 | 117 | def add_with_extra_info(severity, message = nil, progname = nil, &block) 118 | update_pid 119 | time = @@verbose ? "#{Time.now.iso8601(@@fraction_digits)} " : "" 120 | 121 | if message.nil? 122 | if block_given? 123 | if severity < @level 124 | return true 125 | end 126 | message = yield 127 | end 128 | end 129 | message = "#{time}#{ActiveSupport::BufferedLogger.severity_name(severity)} #{message}" 130 | 131 | # Make sure every line has the PID and hostname and custom string 132 | # so we can use grep to isolate output from one process or server. 133 | # gsub works even when the output contains "\n", though there's 134 | # probably a small performance cost. 135 | message = message.gsub(/^/, @@line_prefix) if @@verbose 136 | 137 | add_without_extra_info(severity, message, progname, &block) 138 | end 139 | 140 | 141 | # add an optional second parameter to the error & warn methods to allow a stack trace: 142 | 143 | def error_with_exception_param(message, exception = nil) 144 | message += "\n#{exception.inspect}\n#{exception.backtrace.join("\n")}" if exception 145 | error_without_exception_param(message) 146 | end 147 | 148 | def warn_with_exception_param(message, exception = nil) 149 | message += "\n#{exception.inspect}\n#{exception.backtrace.join("\n")}" if exception 150 | warn_without_exception_param(message) 151 | end 152 | end 153 | end 154 | end 155 | --------------------------------------------------------------------------------