Module: Sapience

Defined in:
lib/sapience/logger.rb,
lib/sapience/log.rb,
lib/sapience/base.rb,
lib/sapience/grape.rb,
lib/sapience/rails.rb,
lib/sapience/version.rb,
lib/sapience/loggable.rb,
lib/sapience/sapience.rb,
lib/sapience/sneakers.rb,
lib/sapience/subscriber.rb,
lib/sapience/ansi_colors.rb,
lib/sapience/descendants.rb,
lib/sapience/config_loader.rb,
lib/sapience/configuration.rb,
lib/sapience/formatters/raw.rb,
lib/sapience/appender/sentry.rb,
lib/sapience/appender/stream.rb,
lib/sapience/formatters/base.rb,
lib/sapience/formatters/json.rb,
lib/sapience/appender/datadog.rb,
lib/sapience/appender/wrapper.rb,
lib/sapience/formatters/color.rb,
lib/sapience/formatters/default.rb,
lib/sapience/concerns/compatibility.rb,
lib/sapience/extensions/grape/timings.rb,
lib/sapience/extensions/grape/middleware/logging.rb,
lib/sapience/extensions/action_view/log_subscriber.rb,
lib/sapience/extensions/active_record/log_subscriber.rb,
lib/sapience/extensions/action_controller/log_subscriber.rb

Overview

:nodoc:

Defined Under Namespace

Modules: AnsiColors, Appender, Concerns, ConfigLoader, Descendants, Extensions, Formatters, Loggable, Sneakers Classes: Base, Configuration, Grape, Log, Logger, Rails, Subscriber

Constant Summary collapse

VERSION =
"0.2.9"
UnknownClass =
Class.new(NameError)
LEVELS =

Logging levels in order of most detailed to most severe

[:trace, :debug, :info, :warn, :error, :fatal].freeze
DEFAULT_ENV =
"default".freeze
UnkownLogLevel =
Class.new(StandardError)
InvalidLogExecutor =
Class.new(StandardError)
@@configured =
nil

Class Method Summary collapse

Class Method Details

.[](klass) ⇒ Object

Return a logger for the supplied class or class_name



89
90
91
# File 'lib/sapience/sapience.rb', line 89

def self.[](klass)
  Sapience::Logger.new(klass)
end

.add_appender(appender, options = {}, _deprecated_level = nil, &_block) ⇒ Object

Add a new logging appender as a new destination for all log messages emitted from Sapience

Appenders will be written to in the order that they are added

If a block is supplied then it will be used to customize the format of the messages sent to that appender. See Sapience::Logger.new for more information on custom formatters

Parameters

file_name: [String]
  File name to write log messages to.

Or,
io: [IO]
  An IO Stream to log to.
  For example STDOUT, STDERR, etc.

Or,
appender: [Symbol|Sapience::Subscriber]
  A symbol identifying the appender to create.
  For example:
    :bugsnag, :elasticsearch, :graylog, :http, :mongodb, :new_relic, :splunk_http, :syslog, :wrapper
       Or,
  An instance of an appender derived from Sapience::Subscriber
  For example:
    Sapience::Appender::Http.new(url: 'http://localhost:8088/path')

Or,
logger: [Logger|Log4r]
  An instance of a Logger or a Log4r logger.

level: [:trace | :debug | :info | :warn | :error | :fatal]
  Override the log level for this appender.
  Default: Sapience.config.default_level

formatter: [Symbol|Object|Proc]
  Any of the following symbol values: :default, :color, :json
    Or,
  An instance of a class that implements #call
    Or,
  A Proc to be used to format the output from this appender
  Default: :default

filter: [Regexp|Proc]
  RegExp: Only include log messages where the class name matches the supplied.
  regular expression. All other messages will be ignored.
  Proc: Only include log messages where the supplied Proc returns true
        The Proc must return true or false.

Examples:

# Send all logging output to Standard Out (Screen)
Sapience.add_appender(:stream, io: STDOUT)

# Send all logging output to a file
Sapience.add_appender(:stream, file_name: 'logfile.log')

# Send all logging output to a file and only :info and above to standard output
Sapience.add_appender(:stream, file_name: 'logfile.log')
Sapience.add_appender(:stream, io: STDOUT, level: :info)

Log to log4r, Logger, etc.:

# Send logging output to an existing logger
require 'logger'
require 'sapience'

# Built-in Ruby logger
log = Logger.new(STDOUT)
log.level = Logger::DEBUG

Sapience.config.default_level = :debug
Sapience.add_appender(:wrapper, logger: log)

logger = Sapience['Example']
logger.info "Hello World"
logger.debug("Login time", user: 'Joe', duration: 100, ip_address: '127.0.0.1')


171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/sapience/sapience.rb', line 171

def self.add_appender(appender, options = {}, _deprecated_level = nil, &_block)
  fail ArgumentError, "options should be a hash" unless options.is_a?(Hash)
  options.deep_symbolize_keyz!
  appender_class = constantize_symbol(appender)
  validate_appender!(appender_class)

  appender       = appender_class.new(options)
  @@appenders << appender

  # Start appender thread if it is not already running
  Sapience::Logger.start_appender_thread
  Sapience.logger = appender if appender.is_a?(Sapience::Appender::Stream)
  Sapience.metrix = appender if appender.is_a?(Sapience::Appender::Datadog)
  appender
end

.add_appenders(*appenders) ⇒ Object

Examples:

Sapience.add_appenders(
  { file: { io: STDOUT } },
  { sentry: { dsn: "https://app.getsentry.com/" } },
)


203
204
205
206
207
208
209
# File 'lib/sapience/sapience.rb', line 203

def self.add_appenders(*appenders)
  appenders.flatten.compact.each do |appender|
    appender.each do |name, options|
      add_appender(name, options)
    end
  end
end

.appendersObject

Returns [Sapience::Subscriber] a copy of the list of active appenders for debugging etc. Use Sapience.add_appender and Sapience.remove_appender to manipulate the active appenders list



230
231
232
# File 'lib/sapience/sapience.rb', line 230

def self.appenders
  @@appenders.clone
end

.clear_tags!Object



312
313
314
# File 'lib/sapience/sapience.rb', line 312

def self.clear_tags!
  Thread.current[:sapience_tags] = []
end

.closeObject

Close and flush all appenders



261
262
263
# File 'lib/sapience/sapience.rb', line 261

def self.close
  Sapience::Logger.close
end

.configObject

TODO: Should we really always read from file? What if someone wants to configure sapience with a block without reading the default.yml?



33
34
35
36
37
38
39
40
# File 'lib/sapience/sapience.rb', line 33

def self.config
  @@config ||= begin
    config    = ConfigLoader.load_from_file
    options   = config[environment]
    options ||= default_options(config)
    Configuration.new(options)
  end
end

.configure(force: false) {|config| ... } ⇒ Object

TODO: Maybe when configuring with a block we should create a new config? See the TODO note on .config for more information

Yields:



79
80
81
82
83
84
85
86
# File 'lib/sapience/sapience.rb', line 79

def self.configure(force: false)
  yield config if block_given?
  return config if configured? && force == false
  add_appenders(*config.appenders)
  @@configured = true

  config
end

.configured?Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/sapience/sapience.rb', line 42

def self.configured?
  @@configured
end

.constantize(class_name) ⇒ Object



377
378
379
380
381
382
383
384
385
386
# File 'lib/sapience/sapience.rb', line 377

def self.constantize(class_name)
  return class_name unless class_name.is_a?(String)
  if RUBY_VERSION.to_i >= 2
    Object.const_get(class_name)
  else
    class_name.split("::").inject(Object) { |o, name| o.const_get(name) } # rubocop:disable SingleLineBlockParams
  end
rescue NameError
  raise UnknownClass, "Could not find class: #{class_name}."
end

.constantize_symbol(symbol, namespace = "Sapience::Appender") ⇒ Object



372
373
374
375
# File 'lib/sapience/sapience.rb', line 372

def self.constantize_symbol(symbol, namespace = "Sapience::Appender")
  class_name = "#{namespace}::#{symbol.to_sym.camelize}"
  constantize(class_name)
end

.default_options(options = {}) ⇒ Object



46
47
48
49
# File 'lib/sapience/sapience.rb', line 46

def self.default_options(options = {})
  warn "No configuration for environment #{environment}. Using 'default'"
  options[DEFAULT_ENV]
end

.environmentObject



64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/sapience/sapience.rb', line 64

def self.environment
  ENV.fetch("RAILS_ENV") do
    ENV.fetch("RACK_ENV") do
      if defined?(::Rails) && ::Rails.respond_to?(:env)
        ::Rails.env
      else
        puts "Sapience is going to use default configuration"
        DEFAULT_ENV
      end
    end
  end
end

.fast_tag(tag) ⇒ Object

If the tag being supplied is definitely a string then this fast tag api can be used for short lived tags



277
278
279
280
281
282
# File 'lib/sapience/sapience.rb', line 277

def self.fast_tag(tag)
  (Thread.current[:sapience_tags] ||= []) << tag
  yield
ensure
  Thread.current[:sapience_tags].pop
end

.flushObject

Wait until all queued log messages have been written and flush all active appenders



256
257
258
# File 'lib/sapience/sapience.rb', line 256

def self.flush
  Sapience::Logger.flush
end

.known_appendersObject



194
195
196
# File 'lib/sapience/sapience.rb', line 194

def self.known_appenders
  @_known_appenders ||= Sapience::Subscriber.descendants
end

.log_executor_classObject



368
369
370
# File 'lib/sapience/sapience.rb', line 368

def self.log_executor_class
  constantize_symbol(config.log_executor, "Concurrent")
end

.loggerObject



246
247
248
# File 'lib/sapience/sapience.rb', line 246

def self.logger
  @@logger ||= Sapience::Logger.logger
end

.logger=(logger) ⇒ Object



242
243
244
# File 'lib/sapience/sapience.rb', line 242

def self.logger=(logger)
  @@logger = Sapience::Logger.logger = logger
end

.metrixObject



238
239
240
# File 'lib/sapience/sapience.rb', line 238

def self.metrix
  @@metrix ||= Sapience.add_appender(:datadog)
end

.metrix=(metrix) ⇒ Object



234
235
236
# File 'lib/sapience/sapience.rb', line 234

def self.metrix=(metrix)
  @@metrix = metrix
end

.pop_tags(quantity = 1) ⇒ Object

Remove specified number of tags from the current tag list



317
318
319
320
# File 'lib/sapience/sapience.rb', line 317

def self.pop_tags(quantity = 1)
  t = Thread.current[:sapience_tags]
  t.pop(quantity) unless t.nil?
end

.push_tags(*tags) ⇒ Object

Add tags to the current scope Returns the list of tags pushed after flattening them out and removing blanks



304
305
306
307
308
309
310
# File 'lib/sapience/sapience.rb', line 304

def self.push_tags(*tags)
  # Need to flatten and reject empties to support calls from Rails 4
  new_tags                       = tags.flatten.collect(&:to_s).reject(&:empty?)
  t                              = Thread.current[:sapience_tags]
  Thread.current[:sapience_tags] = t.nil? ? new_tags : t.concat(new_tags)
  new_tags
end

.remove_appender(appender) ⇒ Object

Remove an existing appender Currently only supports appender instances TODO: Make it possible to remove appenders by type Maybe create a concurrent collection that allows this by inheriting from concurrent array.



215
216
217
# File 'lib/sapience/sapience.rb', line 215

def self.remove_appender(appender)
  @@appenders.delete(appender)
end

.remove_appenders(appenders = @@appenders) ⇒ Object

Remove specific appenders or all existing



220
221
222
223
224
# File 'lib/sapience/sapience.rb', line 220

def self.remove_appenders(appenders = @@appenders)
  appenders.each do |appender|
    remove_appender(appender)
  end
end

.reopenObject

After forking an active process call Sapience.reopen to re-open any open file handles etc to resources

Note: Only appenders that implement the reopen method will be called



269
270
271
272
273
# File 'lib/sapience/sapience.rb', line 269

def self.reopen
  @@appenders.each { |appender| appender.reopen if appender.respond_to?(:reopen) }
  # After a fork the appender thread is not running, start it if it is not running
  Sapience::Logger.start_appender_thread
end

.reset!Object



51
52
53
54
55
56
57
58
# File 'lib/sapience/sapience.rb', line 51

def self.reset!
  @@config = nil
  @@logger = nil
  @@metrix = nil
  @@configured = nil
  clear_tags!
  reset_appenders!
end

.reset_appenders!Object



60
61
62
# File 'lib/sapience/sapience.rb', line 60

def self.reset_appenders!
  @@appenders = Concurrent::Array.new
end

.rootObject



388
389
390
# File 'lib/sapience/sapience.rb', line 388

def self.root
  @_root ||= Gem::Specification.find_by_name("sapience").gem_dir
end

.silence(new_level = :error) ⇒ Object

Silence noisy log levels by changing the default_level within the block

This setting is thread-safe and only applies to the current thread

Any threads spawned within the block will not be affected by this setting

#silence can be used to both raise and lower the log level within the supplied block.

Example:

# Perform trace level logging within the block when the default is higher
Sapience.config.default_level = :info

logger.debug 'this will _not_ be logged'

Sapience.silence(:trace) do
  logger.debug "this will be logged"
end

Parameters

new_level
  The new log level to apply within the block
  Default: :error

Example:

# Silence all logging for this thread below :error level
Sapience.silence do
  logger.info "this will _not_ be logged"
  logger.warn "this neither"
  logger.error "but errors will be logged"
end

Note:

#silence does not affect any loggers which have had their log level set
explicitly. I.e. That do not rely on the global default level


358
359
360
361
362
363
364
# File 'lib/sapience/sapience.rb', line 358

def self.silence(new_level = :error)
  current_index                     = Thread.current[:sapience_silence]
  Thread.current[:sapience_silence] = Sapience.config.level_to_index(new_level)
  yield
ensure
  Thread.current[:sapience_silence] = current_index
end

.tagged(*tags) ⇒ Object

Add the supplied tags to the list of tags to log for this thread whilst the supplied block is active. Returns result of block



287
288
289
290
291
292
# File 'lib/sapience/sapience.rb', line 287

def self.tagged(*tags)
  new_tags = push_tags(*tags)
  yield self
ensure
  pop_tags(new_tags.size)
end

.tagsObject

Returns a copy of the [Array] of [String] tags currently active for this thread Returns nil if no tags are set



296
297
298
299
300
# File 'lib/sapience/sapience.rb', line 296

def self.tags
  # Since tags are stored on a per thread basis this list is thread-safe
  t = Thread.current[:sapience_tags]
  t.nil? ? [] : t.clone
end

.test_exception(level = :error) ⇒ Object



250
251
252
# File 'lib/sapience/sapience.rb', line 250

def self.test_exception(level = :error)
  Sapience[self].public_send(level, Exception.new("Sapience Test Exception"))
end

.validate_appender!(appender) ⇒ Object



187
188
189
190
191
192
# File 'lib/sapience/sapience.rb', line 187

def self.validate_appender!(appender)
  return if known_appenders.include?(appender)

  fail NotImplementedError,
    "Unknown appender '#{appender}'. Supported appenders are (#{known_appenders.join(", ")})"
end