Skip to content

Commit

Permalink
Formatting the log using parameter progname for the logger (#1606)
Browse files Browse the repository at this point in the history
  • Loading branch information
kodram authored Dec 9, 2024
1 parent b7b2bc1 commit 529b5b0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
12 changes: 6 additions & 6 deletions lib/faraday/logging/formatter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,16 @@ def initialize(logger:, options:)
def_delegators :@logger, :debug, :info, :warn, :error, :fatal

def request(env)
public_send(log_level, 'request') do
"#{env.method.upcase} #{apply_filters(env.url.to_s)}"
public_send(log_level) do
"request: #{env.method.upcase} #{apply_filters(env.url.to_s)}"
end

log_headers('request', env.request_headers) if log_headers?(:request)
log_body('request', env[:body]) if env[:body] && log_body?(:request)
end

def response(env)
public_send(log_level, 'response') { "Status #{env.status}" }
public_send(log_level) { "response: Status #{env.status}" }

log_headers('response', env.response_headers) if log_headers?(:response)
log_body('response', env[:body]) if env[:body] && log_body?(:response)
Expand All @@ -41,7 +41,7 @@ def response(env)
def exception(exc)
return unless log_errors?

public_send(log_level, 'error') { exc.full_message }
public_send(log_level) { "error: #{exc.full_message}" }

log_headers('error', exc.response_headers) if exc.respond_to?(:response_headers) && log_headers?(:error)
return unless exc.respond_to?(:response_body) && exc.response_body && log_body?(:error)
Expand Down Expand Up @@ -107,11 +107,11 @@ def log_level
end

def log_headers(type, headers)
public_send(log_level, type) { apply_filters(dump_headers(headers)) }
public_send(log_level) { "#{type}: #{apply_filters(dump_headers(headers))}" }
end

def log_body(type, body)
public_send(log_level, type) { apply_filters(dump_body(body)) }
public_send(log_level) { "#{type}: #{apply_filters(dump_body(body))}" }
end
end
end
Expand Down
20 changes: 20 additions & 0 deletions spec/faraday/response/logger_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,26 @@
end
end

context 'when logger with program name' do
let(:logger) { Logger.new(string_io, progname: 'my_best_program') }

it 'logs with program name' do
conn.get '/hello'

expect(string_io.string).to match('-- my_best_program: request:')
expect(string_io.string).to match('-- my_best_program: response:')
end
end

context 'when logger without program name' do
it 'logs without program name' do
conn.get '/hello'

expect(string_io.string).to match('-- : request:')
expect(string_io.string).to match('-- : response:')
end
end

context 'with default formatter' do
let(:formatter) { instance_double(Faraday::Logging::Formatter, request: true, response: true, filter: []) }

Expand Down

0 comments on commit 529b5b0

Please sign in to comment.