2019-01-23 20:15:19 +00:00
|
|
|
require "logger"
|
|
|
|
|
2019-06-08 01:07:55 +00:00
|
|
|
enum LogLevel
|
|
|
|
Debug
|
|
|
|
Info
|
|
|
|
Warn
|
|
|
|
Error
|
|
|
|
end
|
|
|
|
|
2019-01-23 20:15:19 +00:00
|
|
|
class Invidious::LogHandler < Kemal::BaseLogHandler
|
2019-06-08 01:07:55 +00:00
|
|
|
def initialize(@io : IO = STDOUT, @level = LogLevel::Warn)
|
2019-01-23 20:15:19 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def call(context : HTTP::Server::Context)
|
2019-06-08 00:56:41 +00:00
|
|
|
time = Time.utc
|
2019-01-23 20:15:19 +00:00
|
|
|
call_next(context)
|
2019-06-08 00:56:41 +00:00
|
|
|
elapsed_text = elapsed_text(Time.utc - time)
|
2019-01-23 20:15:19 +00:00
|
|
|
|
|
|
|
@io << time << ' ' << context.response.status_code << ' ' << context.request.method << ' ' << context.request.resource << ' ' << elapsed_text << '\n'
|
|
|
|
|
|
|
|
if @io.is_a? File
|
|
|
|
@io.flush
|
|
|
|
end
|
|
|
|
|
|
|
|
context
|
|
|
|
end
|
|
|
|
|
2019-06-08 01:07:55 +00:00
|
|
|
def puts(message : String)
|
|
|
|
@io << message << '\n'
|
|
|
|
|
|
|
|
if @io.is_a? File
|
|
|
|
@io.flush
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def write(message : String, level = @level)
|
2019-01-23 20:15:19 +00:00
|
|
|
@io << message
|
|
|
|
|
|
|
|
if @io.is_a? File
|
|
|
|
@io.flush
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2019-06-08 01:07:55 +00:00
|
|
|
def set_log_level(level : String)
|
|
|
|
case level.downcase
|
|
|
|
when "debug"
|
|
|
|
set_log_level(LogLevel::Debug)
|
|
|
|
when "info"
|
|
|
|
set_log_level(LogLevel::Info)
|
|
|
|
when "warn"
|
|
|
|
set_log_level(LogLevel::Warn)
|
|
|
|
when "error"
|
|
|
|
set_log_level(LogLevel::Error)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def set_log_level(level : LogLevel)
|
|
|
|
@level = level
|
|
|
|
end
|
|
|
|
|
|
|
|
{% for level in %w(debug info warn error) %}
|
|
|
|
def {{level.id}}(message : String)
|
|
|
|
puts(message, LogLevel::{{level.id.capitalize}})
|
|
|
|
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
|