Added environment

This commit is contained in:
Sdogruyol 2015-11-16 23:55:02 +02:00
parent 0e617dcfb6
commit 79ef2f30f7
4 changed files with 44 additions and 18 deletions

View file

@ -2,10 +2,10 @@ require "./spec_helper"
describe "Logger" do describe "Logger" do
it "logs stuff" do it "logs stuff" do
IO.pipe do |r, w| # IO.pipe do |r, w|
logger = Kemal::Logger.new(w) # logger = Kemal::Logger.new(w)
logger.info "Info from logger" # logger.info "Info from logger"
r.gets.should match(/Info from logger/) # r.gets.should match(/Info from logger/)
end # end
end end
end end

View file

@ -6,12 +6,16 @@ at_exit do
opts.on("-p ", "--port ", "port") do |opt_port| opts.on("-p ", "--port ", "port") do |opt_port|
Kemal.config.port = opt_port.to_i Kemal.config.port = opt_port.to_i
end end
opts.on("-e ", "--environment ", "environment") do |env|
Kemal.config.env = env
end
end end
config = Kemal.config config = Kemal.config
config.add_handler HTTP::LogHandler.new config.add_handler Kemal::Logger.new
config.add_handler Kemal::Handler::INSTANCE config.add_handler Kemal::Handler::INSTANCE
config.add_handler HTTP::StaticFileHandler.new("./public") config.add_handler HTTP::StaticFileHandler.new("./public")
server = HTTP::Server.new(config.port, config.handlers) server = HTTP::Server.new(config.port, config.handlers)
server.ssl = config.ssl server.ssl = config.ssl

View file

@ -5,6 +5,7 @@ module Kemal
HANDLERS = [] of HTTP::Handler HANDLERS = [] of HTTP::Handler
property ssl property ssl
property port property port
property env
def initialize def initialize
@port = 3000 @port = 3000

View file

@ -1,16 +1,37 @@
class Kemal::Logger class Kemal::Logger < HTTP::Handler
LOG_LEVELS = %w(info debug error warn) property handler
def initialize(@stream) def initialize
end @env = Kemal.config.env
if @env == "production"
{% for method in LOG_LEVELS %} @handler = File.new("kemal.log", "a+")
def {{method.id}}(message) else
@stream.puts message @handler = STDOUT
end end
{% end %}
def exception(e)
error "#{e.message}:\n\t#{e.backtrace.join("\n\t")}"
end end
def call(request)
time = Time.now
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"
@handler.print output_message if @env == "development"
@handler.write output_message.to_slice if @env == "production"
response
end
private def elapsed_text(elapsed)
minutes = elapsed.total_minutes
return "#{minutes.round(2)}m" if minutes >= 1
seconds = elapsed.total_seconds
return "#{seconds.round(2)}s" if seconds >= 1
millis = elapsed.total_milliseconds
return "#{millis.round(2)}ms" if millis >= 1
"#{(millis * 1000).round(2)}µs"
end
end end