项目作者: amedia

项目描述 :
contextual logger :-)
高级语言: Ruby
项目地址: git://github.com/amedia/contextual-logger.git
创建时间: 2014-09-04T12:27:53Z
项目社区:https://github.com/amedia/contextual-logger

开源协议:

下载


ContextualLogger

This gem provides a wrapper for logging with contextual information.

Installation

Add this line to your application’s Gemfile:

  1. gem 'contextual_logger'

And then execute:

  1. $ bundle

Or install it yourself as:

  1. $ gem install contextual_logger

Usage

The ContextualLogger::LogstashLogger class wraps logging to a LogstashLogger
instance.

The ContextualLogger::MultiLogger class wraps logging to both a standard Logger instance
and a LogstashLogger instance at the same time. Both logger instances
must be setup independently in advance.

For each example below, the output being logged to each instance will be
shown underneath the code example.

  1. FILELOGGER = Logger.new(...)
  2. LOGSTASH = LogStashLogger.new(...)
  3. logger = ContextualLogger::LogstashLogger.new(LOGSTASH)
  4. # or
  5. logger = ContextualLogger::MultiLogger.new(FILELOGGER, LOGSTASH)
  6. logger.info "Hello, world!"
  7. # => "Hello, world!"
  8. # => {"message": "Hello, world!"}

Contextual info can be added anywhere before the logging is performed:

  1. logger.add_context user_id: user.id
  2. logger.info "User logged in."
  3. # => "User logged in. {:user_id=>123}"
  4. # => {"message": "User logged in.", "user_id": 123}

Contextual info can also be tacked on directly when logging:

  1. logger.info "Logged out.", user_id: user.id
  2. # => "Logged out. {:user_id=>123}"
  3. # => {"message": "Logged out.", "user_id": 123}

Info added to the error context will only be appended to log events
with severities of error or fatal:

  1. logger.add_error_context request_url: request.request_url
  2. logger.info "Starting."
  3. # => "Starting."
  4. # => {"message": "Starting."}
  5. logger.error "Failed!"
  6. # => "Failed! {:request_url=>'http://localhost:9292/foo/bar'}
  7. # => {"message": "Failed!", "request_url": "http://localhost:9292/foo/bar"}

The context can be emptied by request:

  1. logger.clear_context

Exception objects can be added to the context and will be automatically formatted:

  1. begin
  2. raise SomeError, "Oops!"
  3. rescue SomeError => err
  4. logger.error "Failed.", exception: err
  5. end
  6. # => "Failed. {exception: "SomeError: Oops!"}
  7. # => {"message": "Failed.", exception: "SomeError: Oops!"}

LoggerMixin

To get a clean logger object with some common context in your code, you can
include LoggerMixin. Example:

  1. class GenderGuesser
  2. include ContextualLogger::LoggerMixin
  3. def guess(name)
  4. # ...
  5. logger.info "#{name} is probably #{gender}", name: name
  6. # ...
  7. pass
  8. end

Please note that this requires that you have setup contextual logger to the
global LOGGER variable.