Merge pull request #54 from sdogruyol/logger

Make logger configurable
This commit is contained in:
Serdar Dogruyol 2016-01-17 14:33:58 +02:00
commit 8bac0a8aef
4 changed files with 31 additions and 6 deletions

View file

@ -21,4 +21,11 @@ describe "Macros" do
Kemal.config.handlers.size.should eq 1 Kemal.config.handlers.size.should eq 1
end end
end end
describe "#logging" do
it "sets logging status" do
logging false
Kemal.config.logging.should eq false
end
end
end end

View file

@ -4,18 +4,20 @@ require "./kemal/middleware/*"
at_exit do at_exit do
Kemal::CLI.new Kemal::CLI.new
config = Kemal.config config = Kemal.config
logger = Kemal::Logger.new if config.logging
config.add_handler logger logger = Kemal::Logger.new
config.logger = logger
config.logger.write "[#{config.env}] Kemal is ready to lead at #{config.scheme}://#{config.host_binding}:#{config.port}\n"
end
config.add_handler Kemal::StaticFileHandler.new(config.public_folder) config.add_handler Kemal::StaticFileHandler.new(config.public_folder)
config.add_handler Kemal::Handler::INSTANCE config.add_handler Kemal::Handler::INSTANCE
server = HTTP::Server.new(config.host_binding.not_nil!.to_slice, config.port, config.handlers) server = HTTP::Server.new(config.host_binding.not_nil!.to_slice, config.port, config.handlers)
server.ssl = config.ssl server.ssl = config.ssl
logger.write "[#{config.env}] Kemal is ready to lead at #{config.scheme}://#{config.host_binding}:#{config.port}\n"
Signal::INT.trap { Signal::INT.trap {
logger.write "Kemal is going to take a rest!\n" config.logger.write "Kemal is going to take a rest!\n"
logger.handler.close config.logger.handler.close
server.close server.close
exit exit
} }

View file

@ -4,13 +4,15 @@ module Kemal
class Config class Config
INSTANCE = Config.new INSTANCE = Config.new
HANDLERS = [] of HTTP::Handler HANDLERS = [] of HTTP::Handler
property host_binding, ssl, port, env, public_folder property host_binding, ssl, port, env, public_folder, logging
def initialize def initialize
@host_binding = "0.0.0.0" unless @host_binding @host_binding = "0.0.0.0" unless @host_binding
@port = 3000 @port = 3000
@env = "development" unless @env @env = "development" unless @env
@public_folder = "./public" @public_folder = "./public"
@logging = true
@logger = nil
end end
def scheme def scheme
@ -21,6 +23,15 @@ module Kemal
HANDLERS HANDLERS
end end
def logger
@logger.not_nil!
end
def logger=(logger)
HANDLERS << logger
@logger = logger
end
def add_handler(handler : HTTP::Handler) def add_handler(handler : HTTP::Handler)
HANDLERS << handler HANDLERS << handler
end end

View file

@ -41,3 +41,8 @@ end
macro log(message) macro log(message)
Kemal::Logger::INSTANCE.write "#{{{message}}}\n" Kemal::Logger::INSTANCE.write "#{{{message}}}\n"
end end
# Enables / Disables logging
macro logging(status)
Kemal.config.logging = {{status}}
end