invidious-mod-JP/src/invidious/helpers/logger.cr

60 lines
1.2 KiB
Crystal
Raw Normal View History

2019-01-23 20:15:19 +00:00
require "logger"
2019-06-08 01:07:55 +00:00
enum LogLevel
All
Trace
2019-06-08 01:07:55 +00:00
Debug
Info
Warn
Error
Fatal
Off
2019-06-08 01:07:55 +00:00
end
2019-01-23 20:15:19 +00:00
class Invidious::LogHandler < Kemal::BaseLogHandler
def initialize(@io : IO = STDOUT, @level = LogLevel::Debug)
2019-01-23 20:15:19 +00:00
end
def call(context : HTTP::Server::Context)
elapsed_time = Time.measure { call_next(context) }
elapsed_text = elapsed_text(elapsed_time)
2019-01-23 20:15:19 +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'
@io.flush
2019-06-08 01:07:55 +00:00
end
def write(message : String)
2019-01-23 20:15:19 +00:00
@io << message
@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)
@level = LogLevel.parse(level)
2019-06-08 01:07:55 +00:00
end
def set_log_level(level : LogLevel)
@level = level
end
{% for level in %w(trace debug info warn error fatal) %}
2019-06-08 01:07:55 +00:00
def {{level.id}}(message : String)
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