Be sure to close handlers

This commit is contained in:
Sdogruyol 2015-11-19 20:54:58 +02:00
parent 86dfd1a24d
commit 0e23e8d9a3
2 changed files with 22 additions and 14 deletions

View file

@ -12,11 +12,20 @@ at_exit do
end end
config = Kemal.config config = Kemal.config
config.add_handler Kemal::Logger.new logger = Kemal::Logger.new
config.add_handler logger
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
logger.write "Kemal is ready to lead at #{config.scheme}://0.0.0.0:#{config.port}\n"
Signal::INT.trap {
logger.handler.close
server.close
exit
}
server.listen server.listen
end end

View file

@ -3,10 +3,11 @@ class Kemal::Logger < HTTP::Handler
def initialize def initialize
@env = Kemal.config.env @env = Kemal.config.env
@handler = STDOUT @handler = if @env == "production"
config = Kemal.config File.new("kemal.log", "a+")
@startup_message = "Kemal is ready to lead at #{config.scheme}://0.0.0.0:#{config.port}" else
@env == "production" ? setup_file_handler : setup_stdout_handler STDOUT
end
end end
def call(request) def call(request)
@ -15,8 +16,7 @@ class Kemal::Logger < HTTP::Handler
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" output_message = "#{request.method} #{request.resource} - #{response.status_code} (#{elapsed_text})\n"
@handler.print output_message if @env == "development" write output_message
@handler.write output_message.to_slice if @env == "production"
response response
end end
@ -33,12 +33,11 @@ class Kemal::Logger < HTTP::Handler
"#{(millis * 1000).round(2)}µs" "#{(millis * 1000).round(2)}µs"
end end
private def setup_file_handler def write(message)
@handler = File.new("kemal.log", "a+") if @env == "production"
@handler.write @startup_message.to_slice @handler.write message.to_slice
end else
@handler.print message
private def setup_stdout_handler end
@handler.print @startup_message
end end
end end