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/metrics.rb,
lib/sapience/version.rb,
lib/sapience/appender.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/log_methods.rb,
lib/sapience/rails/engine.rb,
lib/sapience/config_loader.rb,
lib/sapience/configuration.rb,
lib/sapience/error_handler.rb,
lib/sapience/rails/railtie.rb,
lib/sapience/formatters/raw.rb,
lib/sapience/appender/stream.rb,
lib/sapience/formatters/base.rb,
lib/sapience/formatters/json.rb,
lib/sapience/metrics/datadog.rb,
lib/sapience/appender/wrapper.rb,
lib/sapience/formatters/color.rb,
lib/sapience/formatters/default.rb,
lib/sapience/error_handler/sentry.rb,
lib/sapience/error_handler/silent.rb,
lib/sapience/concerns/compatibility.rb,
lib/sapience/extensions/grape/timings.rb,
lib/sapience/extensions/notifications.rb,
lib/sapience/extensions/grape/notifications.rb,
lib/sapience/extensions/active_job/notifications.rb,
lib/sapience/extensions/grape/middleware/logging.rb,
lib/sapience/extensions/action_view/log_subscriber.rb,
lib/sapience/extensions/active_record/model_metrics.rb,
lib/sapience/extensions/active_record/notifications.rb,
lib/sapience/extensions/grape/request_format_helper.rb,
lib/sapience/extensions/active_record/log_subscriber.rb,
lib/sapience/extensions/action_controller/notifications.rb,
lib/sapience/extensions/action_controller/log_subscriber.rb
Overview
:nodoc:
Defined Under Namespace
Modules: AnsiColors, Appender, Concerns, ConfigLoader, Descendants, Extensions, Formatters, LogMethods, Loggable, Rails, Sneakers Classes: Base, Configuration, ErrorHandler, Grape, Log, Logger, Metrics, Subscriber
Constant Summary collapse
- VERSION =
"2.0.2"
- UnknownClass =
Class.new(NameError)
- AppNameMissing =
Class.new(NameError)
- TestException =
Class.new(StandardError)
- UnkownLogLevel =
Class.new(StandardError)
- InvalidLogExecutor =
Class.new(StandardError)
- MissingConfiguration =
Class.new(StandardError)
- LEVELS =
Logging levels in order of most detailed to most severe
[:trace, :debug, :info, :warn, :error, :fatal].freeze
- APP_NAME =
"APP_NAME".freeze
- DEFAULT_ENV =
"default".freeze
- RACK_ENV =
"RACK_ENV".freeze
- RAILS_ENV =
"RAILS_ENV".freeze
- SAPIENCE_ENV =
"SAPIENCE_ENV".freeze
- APPENDER_NAMESPACE =
Sapience::Appender
- METRICS_NAMESPACE =
Sapience::Metrics
- ERROR_HANDLER_NAMESPACE =
Sapience::ErrorHandler
- DEFAULT_STATSD_URL =
"udp://localhost:8125".freeze
- @@configured =
false
Class Method Summary collapse
-
.[](klass) ⇒ Object
Return a logger for the supplied class or class_name.
-
.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.
-
.add_appenders(*appenders) ⇒ Object
Examples: Sapience.add_appenders( { file: { io: STDOUT } }, { sentry: { dsn: “app.getsentry.com/” } }, ).
- .app_name ⇒ Object
-
.appenders ⇒ Object
Returns [Sapience::Subscriber] a copy of the list of active appenders for debugging etc.
- .capture_exception(exception, payload = {}) ⇒ Object
- .capture_message(message, payload = {}) ⇒ Object
- .clear_tags! ⇒ Object
-
.close ⇒ Object
Close and flush all appenders.
- .config ⇒ Object
- .config_hash ⇒ Object
- .configure(force: false) {|config| ... } ⇒ Object
- .configured? ⇒ Boolean
- .constantize(class_name) ⇒ Object
- .constantize_symbol(symbol, namespace = APPENDER_NAMESPACE) ⇒ Object
- .create_class(config_section, namespace) ⇒ Object
- .default_options(options = {}) ⇒ Object
-
.environment ⇒ Object
TODO: Default to SAPIENCE_ENV (if present it should be returned first).
- .error_handler ⇒ Object
- .error_handler=(error_handler) ⇒ Object
-
.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.
-
.flush ⇒ Object
Wait until all queued log messages have been written and flush all active appenders.
- .known_appenders ⇒ Object
- .log_executor_class ⇒ Object
- .logger ⇒ Object
- .logger=(logger) ⇒ Object
- .metrics ⇒ Object
- .metrics=(metrics) ⇒ Object
- .namify(appname, sep = "_") ⇒ Object
-
.pop_tags(quantity = 1) ⇒ Object
Remove specified number of tags from the current tag list.
-
.push_tags(*tags) ⇒ Object
Add tags to the current scope Returns the list of tags pushed after flattening them out and removing blanks.
-
.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.
-
.remove_appenders(appenders = @@appenders) ⇒ Object
Remove specific appenders or all existing.
-
.reopen ⇒ Object
After forking an active process call Sapience.reopen to re-open any open file handles etc to resources.
- .reset! ⇒ Object
- .reset_appenders! ⇒ Object
- .root ⇒ Object
-
.silence(new_level = :error) ⇒ Object
Silence noisy log levels by changing the default_level within the block.
-
.tagged(*tags) ⇒ Object
Add the supplied tags to the list of tags to log for this thread whilst the supplied block is active.
-
.tags ⇒ Object
Returns a copy of the [Array] of [String] tags currently active for this thread Returns nil if no tags are set.
- .test_exception(_level = :error) ⇒ Object
- .validate_appender_class!(appender_class) ⇒ Object
Class Method Details
.[](klass) ⇒ Object
Return a logger for the supplied class or class_name
138 139 140 |
# File 'lib/sapience/sapience.rb', line 138 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')
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 |
# File 'lib/sapience/sapience.rb', line 220 def self.add_appender(appender, = {}, _deprecated_level = nil, &_block) # rubocop:disable AbcSize fail ArgumentError, "options should be a hash" unless .is_a?(Hash) = .dup.deep_symbolize_keyz! appender_class = constantize_symbol(appender) validate_appender_class!(appender_class) appender = appender_class.new() warn "appender #{appender} with (#{.inspect}) is not valid" unless appender.valid? @@appenders << appender # Start appender thread if it is not already running Sapience::Logger.start_appender_thread Sapience::Logger.start_invalid_appenders_task Sapience.logger = appender if appender.is_a?(Sapience::Appender::Stream) appender end |
.add_appenders(*appenders) ⇒ Object
Examples:
Sapience.add_appenders(
{ file: { io: STDOUT } },
{ sentry: { dsn: "https://app.getsentry.com/" } },
)
253 254 255 256 257 258 259 |
# File 'lib/sapience/sapience.rb', line 253 def self.add_appenders(*appenders) appenders.flatten.compact.each do |appender| appender.each do |name, | add_appender(name, ) end end end |
.app_name ⇒ Object
111 112 113 114 115 116 117 118 |
# File 'lib/sapience/sapience.rb', line 111 def self.app_name @@app_name ||= config.app_name @@app_name ||= config_hash.fetch(environment) { {} }["app_name"] @@app_name ||= config_hash.fetch(DEFAULT_ENV) { {} }["app_name"] @@app_name ||= ENV[APP_NAME] fail AppNameMissing, "app_name is not configured. See documentation for more information" unless @@app_name @@app_name end |
.appenders ⇒ Object
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
280 281 282 |
# File 'lib/sapience/sapience.rb', line 280 def self.appenders @@appenders.clone end |
.capture_exception(exception, payload = {}) ⇒ Object
300 301 302 |
# File 'lib/sapience/sapience.rb', line 300 def self.capture_exception(exception, payload = {}) error_handler.capture_exception(exception, payload) end |
.capture_message(message, payload = {}) ⇒ Object
304 305 306 |
# File 'lib/sapience/sapience.rb', line 304 def self.(, payload = {}) error_handler.(, payload) end |
.clear_tags! ⇒ Object
396 397 398 |
# File 'lib/sapience/sapience.rb', line 396 def self. Thread.current[:sapience_tags] = [] end |
.close ⇒ Object
Close and flush all appenders
345 346 347 |
# File 'lib/sapience/sapience.rb', line 345 def self.close Sapience::Logger.close end |
.config ⇒ Object
58 59 60 61 62 63 64 |
# File 'lib/sapience/sapience.rb', line 58 def self.config @@config ||= begin = config_hash[environment] ||= (config_hash) Configuration.new() end end |
.config_hash ⇒ Object
54 55 56 |
# File 'lib/sapience/sapience.rb', line 54 def self.config_hash @@config_hash ||= ConfigLoader.load_from_file end |
.configure(force: false) {|config| ... } ⇒ Object
44 45 46 47 48 49 50 51 52 |
# File 'lib/sapience/sapience.rb', line 44 def self.configure(force: false) yield config if block_given? return config if configured? && force == false reset_appenders! add_appenders(*config.appenders) @@configured = true config end |
.configured? ⇒ Boolean
66 67 68 |
# File 'lib/sapience/sapience.rb', line 66 def self.configured? @@configured end |
.constantize(class_name) ⇒ Object
461 462 463 464 465 466 467 468 469 470 |
# File 'lib/sapience/sapience.rb', line 461 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 = APPENDER_NAMESPACE) ⇒ Object
456 457 458 459 |
# File 'lib/sapience/sapience.rb', line 456 def self.constantize_symbol(symbol, namespace = APPENDER_NAMESPACE) class_name = "#{namespace}::#{symbol.to_sym.camelize}" constantize(class_name) end |
.create_class(config_section, namespace) ⇒ Object
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 |
# File 'lib/sapience/sapience.rb', line 308 def self.create_class(config_section, namespace) namespace_string = namespace.to_s.split("::").last fail MissingConfiguration, "No #{namespace_string} configured" unless config_section klass_name = config_section.keys.first = config_section.values.first klass = constantize_symbol(klass_name, namespace) if namespace.descendants.include?(klass) klass.new() else fail NotImplementedError, "Unknown #{namespace_string} '#{klass_name}'" end end |
.default_options(options = {}) ⇒ Object
70 71 72 73 74 75 |
# File 'lib/sapience/sapience.rb', line 70 def self.( = {}) unless environment =~ /default|rspec/ warn "No configuration for environment #{environment}. Using 'default'" end [DEFAULT_ENV] end |
.environment ⇒ Object
TODO: Default to SAPIENCE_ENV (if present it should be returned first)
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
# File 'lib/sapience/sapience.rb', line 95 def self.environment @@environment ||= ENV.fetch(SAPIENCE_ENV) do ENV.fetch(RAILS_ENV) do ENV.fetch(RACK_ENV) do if defined?(::Rails) && ::Rails.respond_to?(:env) ::Rails.env else warn "Sapience is going to use default configuration" DEFAULT_ENV end end end end end |
.error_handler ⇒ Object
296 297 298 |
# File 'lib/sapience/sapience.rb', line 296 def self.error_handler @@error_handler ||= create_class(config.error_handler, ERROR_HANDLER_NAMESPACE) end |
.error_handler=(error_handler) ⇒ Object
292 293 294 |
# File 'lib/sapience/sapience.rb', line 292 def self.error_handler=(error_handler) @@error_handler = error_handler 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
361 362 363 364 365 366 |
# File 'lib/sapience/sapience.rb', line 361 def self.fast_tag(tag) (Thread.current[:sapience_tags] ||= []) << tag yield ensure Thread.current[:sapience_tags].pop end |
.flush ⇒ Object
Wait until all queued log messages have been written and flush all active appenders
340 341 342 |
# File 'lib/sapience/sapience.rb', line 340 def self.flush Sapience::Logger.flush end |
.known_appenders ⇒ Object
244 245 246 |
# File 'lib/sapience/sapience.rb', line 244 def self.known_appenders @_known_appenders ||= Sapience::Subscriber.descendants end |
.log_executor_class ⇒ Object
452 453 454 |
# File 'lib/sapience/sapience.rb', line 452 def self.log_executor_class constantize_symbol(config.log_executor, "Concurrent") end |
.logger ⇒ Object
328 329 330 |
# File 'lib/sapience/sapience.rb', line 328 def self.logger @@logger ||= Sapience::Logger.logger end |
.logger=(logger) ⇒ Object
324 325 326 |
# File 'lib/sapience/sapience.rb', line 324 def self.logger=(logger) @@logger = Sapience::Logger.logger = logger end |
.metrics ⇒ Object
288 289 290 |
# File 'lib/sapience/sapience.rb', line 288 def self.metrics @@metrics ||= create_class(config.metrics, METRICS_NAMESPACE) end |
.metrics=(metrics) ⇒ Object
284 285 286 |
# File 'lib/sapience/sapience.rb', line 284 def self.metrics=(metrics) @@metrics = metrics end |
.namify(appname, sep = "_") ⇒ Object
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
# File 'lib/sapience/sapience.rb', line 120 def self.namify(appname, sep = "_") return unless appname.is_a?(String) return unless appname.length > 0 # Turn unwanted chars into the separator appname = appname.dup appname.gsub!(/[^a-z0-9\-_]+/i, sep) unless sep.nil? || sep.empty? re_sep = Regexp.escape(sep) # No more than one of the separator in a row. appname.gsub!(/#{re_sep}{2,}/, sep) # Remove leading/trailing separator. appname.gsub!(/^#{re_sep}|#{re_sep}$/, "") end appname.downcase end |
.pop_tags(quantity = 1) ⇒ Object
Remove specified number of tags from the current tag list
401 402 403 404 |
# File 'lib/sapience/sapience.rb', line 401 def self.(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
388 389 390 391 392 393 394 |
# File 'lib/sapience/sapience.rb', line 388 def self.(*) # Need to flatten and reject empties to support calls from Rails 4 = .flatten.collect(&:to_s).reject(&:empty?) t = Thread.current[:sapience_tags] Thread.current[:sapience_tags] = t.nil? ? : t.concat() 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.
265 266 267 |
# File 'lib/sapience/sapience.rb', line 265 def self.remove_appender(appender) @@appenders.delete(appender) end |
.remove_appenders(appenders = @@appenders) ⇒ Object
Remove specific appenders or all existing
270 271 272 273 274 |
# File 'lib/sapience/sapience.rb', line 270 def self.remove_appenders(appenders = @@appenders) appenders.each do |appender| remove_appender(appender) end end |
.reopen ⇒ Object
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
353 354 355 356 357 |
# File 'lib/sapience/sapience.rb', line 353 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
77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/sapience/sapience.rb', line 77 def self.reset! @@config = nil @@logger = nil @@metrics = nil @@error_handler = nil @@environment = nil @@app_name = nil @@configured = false @@config_hash = nil reset_appenders! end |
.reset_appenders! ⇒ Object
90 91 92 |
# File 'lib/sapience/sapience.rb', line 90 def self.reset_appenders! @@appenders = Concurrent::Array.new end |
.root ⇒ Object
472 473 474 |
# File 'lib/sapience/sapience.rb', line 472 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
442 443 444 445 446 447 448 |
# File 'lib/sapience/sapience.rb', line 442 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
371 372 373 374 375 376 |
# File 'lib/sapience/sapience.rb', line 371 def self.tagged(*) = (*) yield self ensure (.size) end |
.tags ⇒ Object
Returns a copy of the [Array] of [String] tags currently active for this thread Returns nil if no tags are set
380 381 382 383 384 |
# File 'lib/sapience/sapience.rb', line 380 def self. # 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
332 333 334 335 336 |
# File 'lib/sapience/sapience.rb', line 332 def self.test_exception(_level = :error) fail Sapience::TestException, "Sapience Test Exception" rescue Sapience::TestException => ex Sapience.capture_exception(ex, test_exception: true) end |
.validate_appender_class!(appender_class) ⇒ Object
237 238 239 240 241 242 |
# File 'lib/sapience/sapience.rb', line 237 def self.validate_appender_class!(appender_class) return if known_appenders.include?(appender_class) fail NotImplementedError, "Unknown appender '#{appender_class}'. Supported appenders are (#{known_appenders.join(", ")})" end |