2019-01-23 20:15:19 +00:00
|
|
|
require "logger"
|
|
|
|
|
2019-06-08 01:07:55 +00:00
|
|
|
enum LogLevel
|
2021-01-04 15:05:15 +00:00
|
|
|
All = 0
|
|
|
|
Trace = 1
|
|
|
|
Debug = 2
|
|
|
|
Info = 3
|
|
|
|
Warn = 4
|
|
|
|
Error = 5
|
|
|
|
Fatal = 6
|
|
|
|
Off = 7
|
2019-06-08 01:07:55 +00:00
|
|
|
end
|
|
|
|
|
2019-01-23 20:15:19 +00:00
|
|
|
class Invidious::LogHandler < Kemal::BaseLogHandler
|
2020-12-21 15:05:35 +00:00
|
|
|
def initialize(@io : IO = STDOUT, @level = LogLevel::Debug)
|
2019-01-23 20:15:19 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def call(context : HTTP::Server::Context)
|
2020-12-21 15:05:35 +00:00
|
|
|
elapsed_time = Time.measure { call_next(context) }
|
|
|
|
elapsed_text = elapsed_text(elapsed_time)
|
2019-01-23 20:15:19 +00:00
|
|
|
|
2020-12-21 15:05:35 +00:00
|
|
|
info("#{context.response.status_code} #{context.request.method} #{context.request.resource} #{elapsed_text}")
|
2019-01-23 20:15:19 +00:00
|
|
|
|
|
|
|
context
|
|
|
|
end
|
|
|
|
|
2019-06-08 01:07:55 +00:00
|
|
|
def puts(message : String)
|
|
|
|
@io << message << '\n'
|
2020-12-21 15:05:35 +00:00
|
|
|
@io.flush
|
2019-06-08 01:07:55 +00:00
|
|
|
end
|
|
|
|
|
2020-12-21 15:05:35 +00:00
|
|
|
def write(message : String)
|
2019-01-23 20:15:19 +00:00
|
|
|
@io << message
|
2020-12-21 15:05:35 +00:00
|
|
|
@io.flush
|
2019-01-23 20:15:19 +00:00
|
|
|
end
|
|
|
|
|
2019-06-08 01:07:55 +00:00
|
|
|
def set_log_level(level : String)
|
2020-12-21 15:05:35 +00:00
|
|
|
@level = LogLevel.parse(level)
|
2019-06-08 01:07:55 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def set_log_level(level : LogLevel)
|
|
|
|
@level = level
|
|
|
|
end
|
|
|
|
|
2020-12-21 15:05:35 +00:00
|
|
|
{% for level in %w(trace debug info warn error fatal) %}
|
2019-06-08 01:07:55 +00:00
|
|
|
def {{level.id}}(message : String)
|
2020-12-21 15:05:35 +00:00
|
|
|
if LogLevel::{{level.id.capitalize}} >= @level
|
|
|
|
puts("#{Time.utc} [{{level.id}}] #{message}")
|
|
|
|
end
|
2019-06-08 01:07:55 +00:00
|
|
|
end
|
|
|
|
{% end %}
|
|
|
|
|
2019-01-23 20:15:19 +00:00
|
|
|
private def elapsed_text(elapsed)
|
|
|
|
millis = elapsed.total_milliseconds
|
|
|
|
return "#{millis.round(2)}ms" if millis >= 1
|
|
|
|
|
|
|
|
"#{(millis * 1000).round(2)}µs"
|
|
|
|
end
|
|
|
|
end
|