-
Notifications
You must be signed in to change notification settings - Fork 11
/
standard.cr
54 lines (45 loc) · 1.53 KB
/
standard.cr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
require "colorize"
require "logger"
require "../rescuer"
require "../../ext/http/request/id"
module Onyx::HTTP::Middleware
module Rescuer
# A rescuer which logs a error colorfully into a standard `::Logger`.
# It also logs the `::HTTP::Request#id` if it's present.
# Should be put *after* `Logger` in the stack.
#
# ```
# logger = Onyx::HTTP::Middleware::Logger.new
# renderer = Onyx::HTTP::Middleware::Renderer.new
# rescuer = Onyx::HTTP::Middleware::Rescuers::Standard(Exception).new(renderer)
# router = Onyx::HTTP::Middleware::Router.new
# handlers = [logger, rescuer, router, renderer]
# ```
class Standard(T)
include Rescuer(T)
# A `Logger` to log to. Can be changed in runtime.
property logger : ::Logger
# Set *verbose* to `false` to turn off logging errors' backtraces.
def initialize(
next_handler : ::HTTP::Handler? = nil,
@logger : ::Logger = ::Logger.new(STDERR),
@verbose : Bool = true
)
super(next_handler)
end
# Log the *error* into the `#logger`.
def handle(context, error)
io = IO::Memory.new
if id = context.request.id
io << "[#{id[0...8]}] ".colorize(:dark_gray)
end
io << " ERROR ".rjust(7).colorize.mode(:bold).back(:red)
io << " " << (error.message || "<Empty message error>")
if @verbose
io << "\n\n" << error.inspect_with_backtrace.colorize(:light_gray)
end
@logger.error(io.to_s)
end
end
end
end