Skip to content

Commit

Permalink
Add Rack::Logger.
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix committed Jun 11, 2024
1 parent d5265bc commit 0d43932
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/rack/contrib.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
22 changes: 22 additions & 0 deletions lib/rack/logger.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# frozen_string_literal: true

require 'logger'

require 'rack/constants'

module Rack
# Sets up rack.logger to write to rack.errors stream
class 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
23 changes: 23 additions & 0 deletions test/spec_logger.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# frozen_string_literal: true

require 'minitest/autorun'
require 'rack/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

0 comments on commit 0d43932

Please sign in to comment.