Logger: Add color support for different log levels

This commit is contained in:
Fijxu
2024-09-19 21:24:20 -03:00
parent d9df90b5e3
commit f8ec312328
4 changed files with 32 additions and 3 deletions

View File

@@ -1,3 +1,5 @@
require "colorize"
enum LogLevel
All = 0
Trace = 1
@@ -10,7 +12,7 @@ enum LogLevel
end
class Invidious::LogHandler < Kemal::BaseLogHandler
def initialize(@io : IO = STDOUT, @level = LogLevel::Debug)
def initialize(@io : IO = STDOUT, @level = LogLevel::Debug, @color : Bool = true)
end
def call(context : HTTP::Server::Context)
@@ -39,10 +41,23 @@ class Invidious::LogHandler < Kemal::BaseLogHandler
@io.flush
end
def color(level)
case level
when LogLevel::Trace then :cyan
when LogLevel::Debug then :green
when LogLevel::Info then :white
when LogLevel::Warn then :yellow
when LogLevel::Error then :red
when LogLevel::Fatal then :magenta
else :default
end
end
{% for level in %w(trace debug info warn error fatal) %}
def {{level.id}}(message : String)
if LogLevel::{{level.id.capitalize}} >= @level
puts("#{Time.utc} [{{level.id}}] #{message}")
puts("#{Time.utc} [{{level.id}}] #{message}".colorize(color(LogLevel::{{level.id.capitalize}})).toggle(@color))
end
end
{% end %}