Merge pull request #16 from askn/logger

add colorize for logger
This commit is contained in:
Serdar Dogruyol 2015-11-22 20:09:36 +02:00
commit 07b35a00b4
3 changed files with 50 additions and 2 deletions

View file

@ -18,7 +18,6 @@ describe "Logger" do
logger = Kemal::Logger.new logger = Kemal::Logger.new
logger.handler.should be_a File logger.handler.should be_a File
end end
it "writes to a file in production" do it "writes to a file in production" do
config = Kemal.config config = Kemal.config
config.env = "production" config.env = "production"

View file

@ -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" logger.write "[#{config.env}] Kemal is ready to lead at #{config.scheme}://0.0.0.0:#{config.port}\n"
Signal::INT.trap { Signal::INT.trap {
logger.write "Kemal is going to take a rest!\n"
logger.write "#{Time.now} - Bye Bye!\n\n"
logger.handler.close logger.handler.close
server.close server.close
exit exit

View file

@ -1,3 +1,5 @@
require "colorize"
class Kemal::Logger < HTTP::Handler class Kemal::Logger < HTTP::Handler
getter handler getter handler
@ -17,7 +19,19 @@ class Kemal::Logger < HTTP::Handler
response = call_next(request) response = call_next(request)
elapsed = Time.now - time elapsed = Time.now - time
elapsed_text = elapsed_text(elapsed) 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 write output_message
response response
end end
@ -42,4 +56,37 @@ class Kemal::Logger < HTTP::Handler
@handler.print message @handler.print message
end end
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 end