diff --git a/lib/rack/contrib.rb b/lib/rack/contrib.rb index 6d7ad96..38fd91a 100644 --- a/lib/rack/contrib.rb +++ b/lib/rack/contrib.rb @@ -30,6 +30,7 @@ def self.release autoload :LazyConditionalGet, "rack/contrib/lazy_conditional_get" autoload :LighttpdScriptNameFix, "rack/contrib/lighttpd_script_name_fix" autoload :Locale, "rack/contrib/locale" + autoload :Logger, "rack/contrib/logger" autoload :MailExceptions, "rack/contrib/mailexceptions" autoload :PostBodyContentTypeParser, "rack/contrib/post_body_content_type_parser" autoload :ProcTitle, "rack/contrib/proctitle" diff --git a/lib/rack/contrib/logger.rb b/lib/rack/contrib/logger.rb new file mode 100644 index 0000000..e971fa9 --- /dev/null +++ b/lib/rack/contrib/logger.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +require 'logger' + +module Rack + # Sets up rack.logger to write to rack.errors stream + class Logger + RACK_ERRORS = 'rack.errors' + RACK_LOGGER = 'rack.logger' + + def initialize(app, level = ::Logger::INFO) + @app, @level = app, level + end + + def call(env) + logger = ::Logger.new(env[RACK_ERRORS]) + logger.level = @level + + env[RACK_LOGGER] = logger + @app.call(env) + end + end +end diff --git a/test/spec_logger.rb b/test/spec_logger.rb new file mode 100644 index 0000000..ec84b07 --- /dev/null +++ b/test/spec_logger.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +require 'minitest/autorun' +require 'rack/contrib/logger' + +describe Rack::Logger do + app = lambda { |env| + log = env['rack.logger'] + log.debug("Created logger") + log.info("Program started") + log.warn("Nothing to do!") + + [200, { 'content-type' => 'text/plain' }, ["Hello, World!"]] + } + + it "conform to Rack::Lint" do + errors = StringIO.new + a = Rack::Lint.new(Rack::Logger.new(app)) + Rack::MockRequest.new(a).get('/', 'rack.errors' => errors) + errors.string.must_match(/INFO -- : Program started/) + errors.string.must_match(/WARN -- : Nothing to do/) + end +end