Sha256: aae7882556f98afb9626131cf326fd03865fe3c8f5b4891a9f6f17e2b1904b31

Contents?: true

Size: 1.03 KB

Versions: 13

Compression:

Stored size: 1.03 KB

Contents

Rack::App::Extension.register(:logger) do

  require "logger"
  require "securerandom"

  logger_class = Class.new
  logger_class.class_eval do

    def initialize(request_id)
      @request_id = request_id
      @logger = ::Logger.new(STDOUT)
    end

    [:info, :warn, :error, :fatal, :unknown].each do |log_level|
      define_method(log_level) do |msg|
        if msg.is_a?(Hash)
          @logger.__send__(log_level, @request_id){format_hash(msg)}
        else
          @logger.__send__(log_level, @request_id){String(msg)}
        end
      end
    end

    protected

    begin
      require "json"
    rescue LoadError
    end

    def format_hash(hash)
      if defined?(::JSON)
        JSON.dump(hash)
      else
        hash.inspect
      end
    end

    def method_missing(name,*args)
      if @logger.respond_to?(:binding)
        @logger.__send__(name,*args)
      else
        super
      end
    end

  end

  define_method(:logger) do
    @logger ||= logger_class.new(request.env['HTTP_X_REQUEST_ID'] || SecureRandom.hex)
  end

end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
rack-app-5.7.0 lib/rack/app/bundled_extensions/logger.rb
rack-app-5.7.0.rc lib/rack/app/bundled_extensions/logger.rb
rack-app-5.6.0 lib/rack/app/bundled_extensions/logger.rb
rack-app-5.5.1 lib/rack/app/bundled_extensions/logger.rb
rack-app-5.4.0 lib/rack/app/bundled_extensions/logger.rb
rack-app-5.3.2 lib/rack/app/bundled_extensions/logger.rb
rack-app-5.3.1 lib/rack/app/bundled_extensions/logger.rb
rack-app-5.3.0 lib/rack/app/bundled_extensions/logger.rb
rack-app-5.2.0 lib/rack/app/bundled_extensions/logger.rb
rack-app-5.1.0 lib/rack/app/bundled_extensions/logger.rb
rack-app-5.0.0 lib/rack/app/bundled_extensions/logger.rb
rack-app-5.0.0.rc2 lib/rack/app/bundled_extensions/logger.rb
rack-app-5.0.0.rc1 lib/rack/app/bundled_extensions/logger.rb