Skip to content

Commit cca5e06

Browse files
Merge pull request #1456 from amberframework/perf/logger-skips-filtered-lines
Logger: allocate nothing when the level filters every line out
2 parents 814705e + ea04541 commit cca5e06

3 files changed

Lines changed: 136 additions & 28 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22

33
## Unreleased
44

5+
- `Amber::Pipe::Logger` allocates nothing when the log level filters its lines
6+
out. At the default `info` level it used to build every debug line before
7+
`Log` dropped it, parse the params, and create a session, about 11.8 KB per
8+
request while writing nothing. When it does write, each line is built inside
9+
the `Log` block and headers are read in place.
510
- A request with a compressed body is answered `415 Unsupported Media Type`,
611
with `Accept-Encoding: identity` and `Connection: close`, before routing or
712
any pipe reads its body. Crystal before 1.21.1 inflates gzip and deflate

‎spec/amber/pipes/logger_spec.cr‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,37 @@ module Amber::Pipe
5050
end
5151

5252
describe "#call" do
53+
it "allocates nothing when the level filters every line out" do
54+
pipe = Logger.new(colorize: false)
55+
pipe.next = ->(_context : HTTP::Server::Context) { }
56+
context = create_context(HTTP::Request.new("GET", "/logger_spec?page=2", HTTP::Headers{"Cookie" => "a=b"}))
57+
Log.capture("*", :info) do |logs|
58+
pipe.call(context)
59+
before = GC.stats.total_bytes
60+
100.times { pipe.call(context) }
61+
(GC.stats.total_bytes - before).should eq 0
62+
logs.empty
63+
end
64+
end
65+
66+
it "writes the request, header, cookie and param lines at debug level" do
67+
pipe = Logger.new(filter: ["password"], skip: ["Host"], colorize: false)
68+
pipe.next = ->(_context : HTTP::Server::Context) { }
69+
request = HTTP::Request.new("GET", "/logger_spec?page=2&password=secret",
70+
HTTP::Headers{"Host" => "example.com", "Accept" => "text/html", "Cookie" => "flavor=oat"})
71+
Log.capture("*", :debug) do |logs|
72+
pipe.call(create_context(request))
73+
logs.check(:debug, /^Started /)
74+
logs.check(:debug, /^Status: 200 Method: GET Pipeline: /)
75+
logs.check(:debug, "Requested Url: /logger_spec?page=2&password=secret")
76+
logs.check(:debug, /^Time Elapsed: /)
77+
logs.check(:debug, %(Accept: ["text/html"]))
78+
logs.check(:debug, /^flavor: /)
79+
logs.check(:debug, "page: 2")
80+
logs.check(:debug, "password: FILTERED")
81+
end
82+
end
83+
5384
it "logs plain text when colorize is false" do
5485
with_global_colorize(true) do
5586
requested_url_line(Logger.new(colorize: false)).should eq "Requested Url: /logger_spec"

‎src/amber/pipes/logger.cr‎

Lines changed: 100 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,128 @@
11
module Amber
22
module Pipe
33
class Logger < Base
4+
# The log sources this pipe writes to, in the order it writes them.
5+
SOURCE_NAMES = {"request", "Request", "headers", "cookies", "params", "session"}
6+
7+
# The color each source name is painted with, by position in `SOURCE_NAMES`.
8+
SOURCE_COLORS = {:magenta, :magenta, :light_cyan, :light_blue, :light_blue, :light_yellow}
9+
10+
# The `::Log` instances behind one spelling of the source names: plain, or
11+
# painted when colored output is on. `::Log` instances are kept up to date
12+
# by `Log.setup` in place, so holding them keeps their levels current.
13+
private record Sources,
14+
request : ::Log,
15+
request_summary : ::Log,
16+
headers : ::Log,
17+
cookies : ::Log,
18+
params : ::Log,
19+
session : ::Log do
20+
# Returns `true` when at least one source would write a debug line.
21+
def writes_any_line? : Bool
22+
{request, request_summary, headers, cookies, params, session}.any? do |log|
23+
Logger.writes_debug?(log)
24+
end
25+
end
26+
end
27+
28+
@plain_sources : Sources
29+
@painted_sources : Sources
30+
431
# Reads `Amber.settings` only when the pipe is built, which happens in
532
# `config/routes.cr` after the app's initializers have registered their
633
# settings sections. A read while `require "amber"` runs would cache the
734
# settings before those sections exist.
835
def initialize(@filter : Array(String) = log_config.filter,
936
@skip : Array(String) = log_config.skip,
1037
@colorize : Bool = log_config.colorize)
38+
@plain_sources = build_sources(painted: false)
39+
@painted_sources = build_sources(painted: true)
40+
end
41+
42+
# Returns `true` when *log* would write a debug line.
43+
#
44+
# ```
45+
# Amber::Pipe::Logger.writes_debug?(::Log.for("request"))
46+
# ```
47+
def self.writes_debug?(log : ::Log) : Bool
48+
!log.backend.nil? && log.level <= ::Log::Severity::Debug
1149
end
1250

51+
# Logs the request at debug level after the rest of the pipeline runs.
52+
#
53+
# When no source would write a debug line (Amber's default `info` level),
54+
# it passes the request on and allocates nothing: it does not read the
55+
# clock, parse params, or build the session.
1356
def call(context : HTTP::Server::Context)
57+
sources = current_sources
58+
unless sources.writes_any_line?
59+
call_next(context)
60+
return context
61+
end
62+
1463
time = Time.utc
1564
call_next(context)
16-
status = context.response.status_code
17-
elapsed = elapsed_text(Time.utc - time)
18-
request(context, time, elapsed, status, :magenta)
19-
log_other(context.request.headers, "headers")
20-
log_other(Amber::Router::Cookies::Store.from_headers(context.request.headers), "cookies", :light_blue)
21-
log_other(context.params, "params", :light_blue)
22-
log_other(context.session, "session", :light_yellow)
65+
elapsed = Time.utc - time
66+
log_request(sources, context, time, elapsed)
67+
log_headers(sources.headers, context.request.headers)
68+
if Logger.writes_debug?(sources.cookies)
69+
log_other(sources.cookies, Amber::Router::Cookies::Store.from_headers(context.request.headers), :light_blue)
70+
end
71+
log_other(sources.params, context.params, :light_blue) if Logger.writes_debug?(sources.params)
72+
log_other(sources.session, context.session, :light_yellow) if Logger.writes_debug?(sources.session)
2373
context
2474
end
2575

26-
private def request(context, time, elapsed, status, color = :magenta)
27-
msg = String.build do |str|
28-
str << "Status: #{http_status(status)} Method: #{method(context)}"
29-
str << " Pipeline: #{paint(context.valve, color)} Format: #{paint(context.format, color)}"
76+
# Colored source names are only written when this pipe colors its lines
77+
# and the app has left `Colorize` on, the same rule `LogColor` follows.
78+
private def current_sources : Sources
79+
@colorize && Colorize.enabled? ? @painted_sources : @plain_sources
80+
end
81+
82+
private def build_sources(painted : Bool) : Sources
83+
logs = SOURCE_NAMES.map_with_index do |name, index|
84+
source = painted ? Support::LogColor.paint(name, SOURCE_COLORS[index], true).to_s : name
85+
::Log.for(source)
3086
end
31-
log "Started #{paint(time, color)}", "request", color
32-
log msg, "Request", color
33-
log "Requested Url: #{paint(context.requested_url, color)}", "request", color
34-
log "Time Elapsed: #{paint(elapsed, color)}", "request", color
87+
Sources.new(*logs)
3588
end
3689

37-
private def log_other(other, name, color = :light_cyan)
38-
other.to_h.each do |key, val|
39-
next if @skip.includes? key
40-
if @filter.includes? key.to_s
41-
log "#{key}: #{paint("FILTERED", :white).mode(:underline)}", name, color
42-
else
43-
log "#{key}: #{paint(val, color)}", name, color
90+
private def log_request(sources, context, time, elapsed) : Nil
91+
color = :magenta
92+
sources.request.debug { "Started #{paint(time, color)}" }
93+
sources.request_summary.debug do
94+
String.build do |line|
95+
line << "Status: " << http_status(context.response.status_code)
96+
line << " Method: " << paint(context.request.method, :light_red)
97+
line << " Pipeline: " << paint(context.valve, color)
98+
line << " Format: " << paint(context.format, color)
4499
end
45100
end
101+
sources.request.debug { "Requested Url: #{paint(context.requested_url, color)}" }
102+
sources.request.debug { "Time Elapsed: #{paint(elapsed_text(elapsed), color)}" }
103+
end
104+
105+
# Walks the headers in place rather than copying them into a hash first.
106+
private def log_headers(log, headers : HTTP::Headers) : Nil
107+
return unless Logger.writes_debug?(log)
108+
headers.each do |key, values|
109+
log_value(log, key, values, :light_cyan)
110+
end
111+
end
112+
113+
private def log_other(log, other, color) : Nil
114+
other.to_h.each do |key, value|
115+
log_value(log, key, value, color)
116+
end
46117
end
47118

48-
private def method(context)
49-
paint(context.request.method, :light_red).to_s
119+
private def log_value(log, key, value, color) : Nil
120+
return if @skip.includes? key
121+
if @filter.includes? key.to_s
122+
log.debug { "#{key}: #{paint("FILTERED", :white).mode(:underline)}" }
123+
else
124+
log.debug { "#{key}: #{paint(value, color)}" }
125+
end
50126
end
51127

52128
private def http_status(status)
@@ -66,10 +142,6 @@ module Amber
66142
"#{(millis * 1000).round(2)}µs"
67143
end
68144

69-
private def log(msg, prog, color = :white)
70-
Log.for(paint(prog, color).to_s).debug { msg }
71-
end
72-
73145
private def paint(value, color)
74146
Support::LogColor.paint(value, color, @colorize)
75147
end

0 commit comments

Comments
 (0)