invidious-experimenting/src/invidious/helpers/logger.cr

74 lines
1.4 KiB
Crystal
Raw Normal View History

2019-01-24 01:45:19 +05:30
require "logger"
2019-06-08 06:37:55 +05:30
enum LogLevel
Debug
Info
Warn
Error
end
2019-01-24 01:45:19 +05:30
class Invidious::LogHandler < Kemal::BaseLogHandler
2019-06-08 06:37:55 +05:30
def initialize(@io : IO = STDOUT, @level = LogLevel::Warn)
2019-01-24 01:45:19 +05:30
end
def call(context : HTTP::Server::Context)
2019-06-08 06:26:41 +05:30
time = Time.utc
2019-01-24 01:45:19 +05:30
call_next(context)
2019-06-08 06:26:41 +05:30
elapsed_text = elapsed_text(Time.utc - time)
2019-01-24 01:45:19 +05:30
@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 06:37:55 +05:30
def puts(message : String)
@io << message << '\n'
if @io.is_a? File
@io.flush
end
end
def write(message : String, level = @level)
2019-01-24 01:45:19 +05:30
@io << message
if @io.is_a? File
@io.flush
end
end
2019-06-08 06:37:55 +05:30
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-24 01:45:19 +05:30
private def elapsed_text(elapsed)
millis = elapsed.total_milliseconds
return "#{millis.round(2)}ms" if millis >= 1
"#{(millis * 1000).round(2)}µs"
end
end