Skip to content

Use as Rack logger

Toshimitsu Takahashi edited this page Dec 15, 2017 · 1 revision

rack_ougai_logger.rb

Define injecting Ougai::logger and generate HTTP request as structured as Rack middleware.

require 'time'
require 'rubygems'
require 'ougai'

module Rack
  module Ougai
    class Logger
      def initialize(app, level = ::Logger::INFO)
        @app, @level = app, level
      end

      def call(env)
        logger = ::Ougai::Logger.new(env[RACK_ERRORS])
        logger.level = @level

        env[RACK_LOGGER] = logger
        @app.call(env)
      end
    end

    class RequestLogger
      def initialize(app, logger = nil)
        @app = app
        @logger = logger
      end

      def call(env)
        status, headers, body = @app.call(env)
      ensure
        logger = @logger || env[RACK_LOGGER]
        logger.info('HTTP Request', create_log(env, status, headers))
      end

      private

      def create_log(env, status, header)
        {
          time: Time.now,
          remote_addr: env['HTTP_X_FORWARDED_FOR'] || env["REMOTE_ADDR"],
          method: env[REQUEST_METHOD],
          path: env[PATH_INFO],
          query: env[QUERY_STRING],
          status: status.to_i,
        }
      end

    end
  end
end

config.ru

Use the above middlewares.

require_relative 'rack_ougai_logger'

use Rack::Ougai::Logger
use Rack::Ougai::RequestLogger

run Proc.new { |env| ['200', {'Content-Type' => 'text/html'}, ['get rack\'d']] }

result

{"name":"rackup","hostname":"mint2","pid":13477,"level":30,"time":"2017-12-13T13:37:51.241+09:00","v":0,"remote_addr":"127.0.0.1","method":"GET","path":"/","query":"","status":200,"msg":"HTTP Request"}
Clone this wiki locally