From e284ba819639315381c06a9834b38143847fbbc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?A=C5=9Fk=C4=B1n=20Gedik?= Date: Sun, 22 Nov 2015 19:02:09 +0200 Subject: [PATCH] add colorize for logger --- spec/logger_spec.cr | 1 - src/kemal.cr | 2 ++ src/kemal/logger.cr | 49 ++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 50 insertions(+), 2 deletions(-) diff --git a/spec/logger_spec.cr b/spec/logger_spec.cr index 82e59d1..e450c97 100644 --- a/spec/logger_spec.cr +++ b/spec/logger_spec.cr @@ -18,7 +18,6 @@ describe "Logger" do logger = Kemal::Logger.new logger.handler.should be_a File end - it "writes to a file in production" do config = Kemal.config config.env = "production" diff --git a/src/kemal.cr b/src/kemal.cr index 3459715..94179c4 100644 --- a/src/kemal.cr +++ b/src/kemal.cr @@ -22,6 +22,8 @@ at_exit do logger.write "[#{config.env}] Kemal is ready to lead at #{config.scheme}://0.0.0.0:#{config.port}\n" Signal::INT.trap { + logger.write "Kemal is going to take a rest!\n" + logger.write "#{Time.now} - Bye Bye!\n\n" logger.handler.close server.close exit diff --git a/src/kemal/logger.cr b/src/kemal/logger.cr index 9bdfc44..422fe3b 100644 --- a/src/kemal/logger.cr +++ b/src/kemal/logger.cr @@ -1,3 +1,5 @@ +require "colorize" + class Kemal::Logger < HTTP::Handler getter handler @@ -17,7 +19,19 @@ class Kemal::Logger < HTTP::Handler response = call_next(request) elapsed = Time.now - time elapsed_text = elapsed_text(elapsed) - output_message = "#{request.method} #{request.resource} - #{response.status_code} (#{elapsed_text})\n" + + if @env == "production" + status_code = " #{response.status_code} " + method = request.method + else + statusColor = color_for_status(response.status_code) + methodColor = color_for_method(request.method) + + status_code = " #{response.status_code} ".colorize.back(statusColor).fore(:white) + method = request.method.colorize(methodColor) + end + + output_message = "#{time} |#{status_code}| #{method} #{request.resource} - (#{elapsed_text})\n" write output_message response end @@ -42,4 +56,37 @@ class Kemal::Logger < HTTP::Handler @handler.print message end end + + private def color_for_status(code) + if code >= 200 && code < 300 + return :green + elsif code >= 300 && code < 400 + return :magenta + elsif code >= 400 && code < 500 + return :yellow + else + return :default + end + end + + private def color_for_method(method) + case method + when "GET" + return :blue + when "POST" + return :cyan + when "PUT" + return :yellow + when "DELETE" + return :red + when "PATCH" + return :green + when "HEAD" + return :magenta + when "OPTIONS" + return :white + else + return :default + end + end end