Just something I whipped up to make application event and exception logging a little more readable:
# # Report something to the default logger, with a timestamp and # importance. # # severity # Symbolic name of one of the logger severity levels (e.g., :error). # This will be passed directly to the logger. # # message # A string, or array of strings, to be recorded one per line. Each # line will be prefixed with a timestamp and the severity. # def log_event(severity, message) text = message.dup tstamp = Time.now tstamp = (tstamp.respond_to?(:iso8601) \ ? tstamp.iso8601 \ : tstamp.strftime('%Y-%m-%dT%H:%M:%S%z')) tstamp = "[#{tstamp}] [#{severity.to_s.downcase}] " text = text.join("\n" + tstamp) if (text.kind_of?(Array)) logger.send(severity.to_sym, tstamp + text) end # # Record an exception in the log, using the #log_event method. # # severity # See #log_event. # # e # An exception object of some sort. # # options # Hash for configuring logging options. Currently the only # option is :enable_backtrace (defaults to true). # def log_exception(severity, e, options={ :include_backtrace => true }) message = [ "Exception #{e.class.name}: #{e.message}" ] if (options[:include_backtrace]) message.push(' Exception backtrace:') if (e.backtrace.nil? || e.backtrace.empty?) message.push(' [empty backtrace]') else message += e.backtrace.collect { |line| ' ' + line } end end log_event(severity.to_sym, message) end
The test for the iso8601 method should be factored out and done once, probably in config/environment.rb, but you get the idea..