Class: SmarterLogging::BaseLogger
- Inherits:
-
Object
- Object
- SmarterLogging::BaseLogger
- Defined in:
- lib/smarter_logging/base_logger.rb
Direct Known Subclasses
Instance Method Summary collapse
-
#_log(data) ⇒ Object
lowest-level logging method:.
-
#_log_wrapper(data = {}, &block) ⇒ Object
this wrapper around _log() handles blocks and errors which could handle in a block if there is an exception during evaluation of the block, we log it as an anomaly and re-raise the exception.
-
#initialize(log_filename) ⇒ BaseLogger
constructor
A new instance of BaseLogger.
Constructor Details
#initialize(log_filename) ⇒ BaseLogger
Returns a new instance of BaseLogger.
6 7 8 9 10 11 12 13 14 15 |
# File 'lib/smarter_logging/base_logger.rb', line 6 def initialize(log_filename) if defined?(Rails) log_filename = "#{Rails.root}/log/#{log_filename}" else FilUtils.mkdir './log' log_filename = "./log/#{log_filename}" end @logger = Logger.new(log_filename) @logger.formatter = nil if @logger.respond_to?(:formatter) end |
Instance Method Details
#_log(data) ⇒ Object
lowest-level logging method:
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/smarter_logging/base_logger.rb', line 51 def _log(data) if exception = data.delete(:exception) data[:error] = [exception.class, exception.].join[' : '] data[:backtrace] = exception.backtrace[0..5].join(' | ') end extra_data = { :time => Time.now.utc.strftime("%Y-%m-%dT%H:%M:%S.%LZ"), :env => Rails.env, } SmarterLogging::ControllerHelper::KEYS.each do |key| extra_data[key] = Thread.current[key] if Thread.current[key] end data = extra_data.merge( data ) # using low-level logging: @logger << reformat( data ) + "\n" end |
#_log_wrapper(data = {}, &block) ⇒ Object
this wrapper around _log() handles blocks and errors which could handle in a block if there is an exception during evaluation of the block, we log it as an anomaly and re-raise the exception
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/smarter_logging/base_logger.rb', line 19 def _log_wrapper(data={}, &block) had_anomaly = false if block_given? begin start = Time.now.utc # to measure duration of the block result = yield(data) data[:duration] = ((Time.now.utc - start) * 1000).to_f.round(3) # in ms result rescue => e data[:exception] = e data[:duration] = ((Time.now.utc - start) * 1000).to_f.round(3) # in ms # we should log this to the anomaly logger also if one is defined if @anomaly_logger @anomaly_logger._log( data ) had_anomaly = true else data[:success] = false end raise # re-raise ensure # log it, even if there is no anomaly logger _log( data ) unless had_anomaly # if it was logged as an anomaly, don't log again end else # without a block, just call the lowest-level logging _log( data ) end end |