1
0
Fork 0
mirror of https://github.com/puma/puma.git synced 2022-11-09 13:48:40 -05:00
puma--puma/lib/puma/error_logger.rb

89 lines
2.1 KiB
Ruby
Raw Normal View History

2020-05-04 14:30:18 -04:00
# frozen_string_literal: true
require 'puma/const'
2020-05-04 14:30:18 -04:00
module Puma
# The implementation of a logging in debug mode.
#
class ErrorLogger
include Const
2020-05-04 14:30:18 -04:00
attr_reader :ioerr
2020-05-11 06:19:53 -04:00
REQUEST_FORMAT = %{"%s %s%s" - (%s)}
2020-05-04 14:30:18 -04:00
def initialize(ioerr)
@ioerr = ioerr
@ioerr.sync = true
@debug = ENV.key? 'PUMA_DEBUG'
end
def self.stdio
new $stderr
end
# Print occured error details.
2020-05-04 14:30:18 -04:00
# +options+ hash with additional options:
2020-05-09 11:04:04 -04:00
# - +error+ is an exception object
2020-05-11 06:19:53 -04:00
# - +req+ the http request
2020-05-09 11:04:04 -04:00
# - +text+ (default nil) custom string to print in title
2020-05-04 14:30:18 -04:00
# and before all remaining info.
#
def info(options={})
error_dump(options)
end
2020-05-11 06:19:53 -04:00
# Print occured error details only if
# environment variable PUMA_DEBUG is defined.
# +options+ hash with additional options:
# - +error+ is an exception object
# - +req+ the http request
# - +text+ (default nil) custom string to print in title
# and before all remaining info.
#
def debug(options={})
return unless @debug
error_dump(options)
end
private
def error_dump(options={})
2020-05-09 11:04:04 -04:00
error = options[:error]
2020-05-11 06:19:53 -04:00
req = options[:req]
env = req.env if req
2020-05-09 11:04:04 -04:00
text = options[:text]
2020-05-04 14:30:18 -04:00
2020-05-09 11:04:04 -04:00
string_block = []
formatted_text = " #{text}" if text
formatted_error = ": #{error.inspect}" if error
2020-05-09 12:03:32 -04:00
string_block << "#{Time.now}#{formatted_text}#{formatted_error}"
2020-05-11 06:19:53 -04:00
2020-05-04 14:30:18 -04:00
if env
2020-05-11 06:19:53 -04:00
string_block << "Handling request { #{request_title(env)} }"
string_block << "Headers: #{request_headers(env)}"
string_block << "Body: #{req.body}"
2020-05-04 14:30:18 -04:00
end
2020-05-09 11:04:04 -04:00
string_block << error.backtrace if error
2020-05-04 14:30:18 -04:00
ioerr.puts string_block.join("\n")
end
2020-05-11 06:19:53 -04:00
def request_title(env)
REQUEST_FORMAT % [
2020-05-11 06:19:53 -04:00
env[REQUEST_METHOD],
env[REQUEST_PATH] || env[PATH_INFO],
env[QUERY_STRING] || "",
env[HTTP_X_FORWARDED_FOR] || env[REMOTE_ADDR] || "-"
]
end
def request_headers(env)
headers = env.select { |key, _| key.start_with?('HTTP_') }
headers.map { |key, value| [key[5..-1], value] }.to_h.inspect
end
2020-05-04 14:30:18 -04:00
end
end