Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
69f5e39
Autofix for RuboCop: Layout/ElseAlignment
pieterocp Jun 30, 2025
672a086
Regen autogen, removing all claude-scratchpad/*
pieterocp Jun 30, 2025
b4daa9b
Autofix RuboCop Layout/EmptyLine
pieterocp Jun 30, 2025
86f2485
AutoFix RuboCop Style/ZeroLengthPredicate
pieterocp Jun 30, 2025
223c84c
AutoFix RuboCop Layout/EmptyLinesAroundAccessModifier
pieterocp Jun 30, 2025
fc2add8
AutoFix RuboCop Layout/EmptyLinesAroundMethodBody
pieterocp Jun 30, 2025
aa596b8
AutoFix RuboCop Layout/EmptyLinesAroundBlockBody
pieterocp Jun 30, 2025
cf62a24
AutoFix RuboCop Layout/EmptyLinesAroundClassBody
pieterocp Jun 30, 2025
4cdf5f3
AutoFix RuboCop Layout/EndAlignment
pieterocp Jun 30, 2025
b683365
AutoFix RuboCop Layout/ExtraSpacing
pieterocp Jun 30, 2025
c9dfc20
AutoFix RuboCop Layout/FirstHashElementIndentation
pieterocp Jun 30, 2025
ea6126d
AutoFix RuboCop Layout/HashAlignment
pieterocp Jun 30, 2025
fc7ae90
AutoFix RuboCop Layout/IndentationWidth
pieterocp Jun 30, 2025
1b9aedf
Regenerate todo
pieterocp Jun 30, 2025
f5a1cdb
AutoFix RuboCop Layout/SpaceBeforeBlockBraces
pieterocp Jun 30, 2025
0ac8504
AutoFix RuboCop Layout/SpaceBeforeComma
pieterocp Jun 30, 2025
8b1f794
AutoFix RuboCop Layout/SpaceInsideBlockBraces
pieterocp Jun 30, 2025
433ace3
AutoFix RuboCop Layout/SpaceInsideHashLiteralBraces
pieterocp Jun 30, 2025
abcef47
AutoFix RuboCop Layout/TrailingEmptyLines
pieterocp Jun 30, 2025
78f7ba0
AutoFix RuboCop Style/TrailingCommaInHashLiteral
pieterocp Jul 8, 2025
9e33e1f
AutoFix RuboCop Style/StringLiteralsInInterpolation
pieterocp Jul 8, 2025
5eea5ab
AutoFix RuboCop Style/StringLiterals
pieterocp Jul 8, 2025
5e78a32
AutoFix RuboCop Style/RescueStandardError
pieterocp Jul 8, 2025
e6af1da
AutoFix RuboCop Style/RedundantPercentQ
pieterocp Jul 8, 2025
3a71be7
AutoFix RuboCop Style/RedundantConstantBase
pieterocp Jul 8, 2025
6f0ffc2
AutoFix RuboCop Style/QuotedSymbols
pieterocp Jul 8, 2025
481a6f6
AutoFix RuboCop Style/PercentLiteralDelimiters
pieterocp Jul 8, 2025
c1fa224
AutoFix RuboCop Style/ParallelAssignment
pieterocp Jul 8, 2025
a95640b
AutoFix RuboCop Style/MultilineIfModifier
pieterocp Jul 8, 2025
65aa464
AutoFix RuboCop Style/Lambda
pieterocp Jul 8, 2025
4ca251f
AutoFix RuboCop Style/IfUnlessModifier
pieterocp Jul 8, 2025
f6ae186
AutoFix RuboCop Style/HashSyntax
pieterocp Jul 8, 2025
b8d0831
AutoFix RuboCop Style/GuardClause
pieterocp Jul 8, 2025
086281a
AutoFix RuboCop Style/ExpandPathArguments
pieterocp Jul 8, 2025
f3552bc
AutoFix RuboCop Style/BlockDelimiters
pieterocp Jul 8, 2025
93b41a6
AutoFix RuboCop Style/BlockComments
pieterocp Jul 8, 2025
e5b6b00
AutoFix RuboCop Lint/UnusedMethodArgument
pieterocp Jul 8, 2025
f3ce256
AutoFix RuboCop Lint/SymbolConversion
pieterocp Jul 8, 2025
ba45a7d
Merge branch 'add-rubocop' into add-all-todos
pieterocp Jul 10, 2025
b338298
Fix auto-gen formatting + RuboCop AutoFix Style/ModuleFunction
pieterocp Jul 10, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
379 changes: 30 additions & 349 deletions .rubocop_todo.yml

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions grape_logging.gemspec
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
lib = File.expand_path('../lib', __FILE__)
lib = File.expand_path('lib', __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'grape_logging/version'

Expand All @@ -8,13 +8,13 @@ Gem::Specification.new do |spec|
spec.authors = ['aserafin']
spec.email = ['adrian@softmad.pl']

spec.summary = %q{Out of the box request logging for Grape!}
spec.description = %q{This gem provides simple request logging for Grape with just few lines of code you have to put in your project! In return you will get response codes, paths, parameters and more!}
spec.summary = 'Out of the box request logging for Grape!'
spec.description = 'This gem provides simple request logging for Grape with just few lines of code you have to put in your project! In return you will get response codes, paths, parameters and more!'
spec.homepage = 'http://github.com/aserafin/grape_logging'
spec.license = 'MIT'

spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']

Expand Down
1 change: 1 addition & 0 deletions lib/grape_logging/formatters/default.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ def format(data)
end

private

def format_hash(hash)
hash.keys.sort.map { |key| "#{key}=#{hash[key]}" }.join(' ')
end
Expand Down
6 changes: 3 additions & 3 deletions lib/grape_logging/formatters/logstash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ module Formatters
class Logstash
def call(severity, datetime, _, data)
{
:'@timestamp' => datetime.iso8601,
:'@version' => '1',
:severity => severity
'@timestamp': datetime.iso8601,
'@version': '1',
severity: severity
}.merge!(format(data)).to_json + "\n"
end

Expand Down
8 changes: 3 additions & 5 deletions lib/grape_logging/formatters/rails.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
module GrapeLogging
module Formatters
class Rails

def call(severity, datetime, _, data)
if data.is_a?(String)
"#{severity[0..0]} [#{datetime}] #{severity} -- : #{data}\n"
Expand All @@ -24,15 +23,15 @@ def format_exception(exception)
[
"#{exception.message} (#{exception.class})",
backtrace_array.join("\n")
].reject{|line| line == ""}.join("\n")
].reject { |line| line == '' }.join("\n")
end

def format_hash(hash)
# Create Rails' single summary line at the end of every request, formatted like:
# Completed 200 OK in 958ms (Views: 951.1ms | ActiveRecord: 3.8ms)
# See: actionpack/lib/action_controller/log_subscriber.rb

message = ""
message = ''
additions = []
status = hash.delete(:status)
params = hash.delete(:params)
Expand All @@ -47,13 +46,12 @@ def format_hash(hash)
message << " Parameters: #{params.inspect}\n" if params

message << "Completed #{status} #{::Rack::Utils::HTTP_STATUS_CODES[status]} in #{total_time}ms"
message << " (#{additions.join(" | ".freeze)})" if additions.size > 0
message << " (#{additions.join(' | '.freeze)})" unless additions.empty?
message << "\n"
message << "\n" if defined?(::Rails.env) && ::Rails.env.development?

message
end

end
end
end
2 changes: 1 addition & 1 deletion lib/grape_logging/loggers/base.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
module GrapeLogging
module Loggers
class Base
def parameters(request, response)
def parameters(_request, _response)
{}
end
end
Expand Down
2 changes: 1 addition & 1 deletion lib/grape_logging/loggers/client_env.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module GrapeLogging
module Loggers
class ClientEnv < GrapeLogging::Loggers::Base
def parameters(request, _)
{ ip: request.env["HTTP_X_FORWARDED_FOR"] || request.env["REMOTE_ADDR"], ua: request.env["HTTP_USER_AGENT"] }
{ ip: request.env['HTTP_X_FORWARDED_FOR'] || request.env['REMOTE_ADDR'], ua: request.env['HTTP_USER_AGENT'] }
end
end
end
Expand Down
6 changes: 3 additions & 3 deletions lib/grape_logging/loggers/filter_parameters.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module Loggers
class FilterParameters < GrapeLogging::Loggers::Base
AD_PARAMS = 'action_dispatch.request.parameters'.freeze

def initialize(filter_parameters = nil, replacement = nil, exceptions = %w(controller action format))
def initialize(filter_parameters = nil, replacement = nil, exceptions = %w[controller action format])
@filter_parameters = filter_parameters || (defined?(::Rails.application) ? ::Rails.application.config.filter_parameters : [])
@replacement = replacement || '[FILTERED]'
@exceptions = exceptions
Expand All @@ -30,8 +30,8 @@ def safe_parameters(request)

def clean_parameters(parameters)
original_encoding_map = build_encoding_map(parameters)
params = transform_key_encoding(parameters, Hash.new{ |h, _| [Encoding::ASCII_8BIT, h] })
cleaned_params = parameter_filter.filter(params).reject{ |key, _value| @exceptions.include?(key) }
params = transform_key_encoding(parameters, Hash.new { |h, _| [Encoding::ASCII_8BIT, h] })
cleaned_params = parameter_filter.filter(params).reject { |key, _value| @exceptions.include?(key) }
transform_key_encoding(cleaned_params, original_encoding_map)
end

Expand Down
2 changes: 0 additions & 2 deletions lib/grape_logging/loggers/request_headers.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
module GrapeLogging
module Loggers
class RequestHeaders < GrapeLogging::Loggers::Base

HTTP_PREFIX = 'HTTP_'.freeze

def parameters(request, _)
Expand All @@ -16,7 +15,6 @@ def parameters(request, _)

{ headers: headers }
end

end
end
end
5 changes: 2 additions & 3 deletions lib/grape_logging/loggers/response.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,11 @@ def parameters(_, response)
# For example, if you POST on a PUT endpoint, response.body is egal to """".
# It's strange, but it's the Grape behavior...
def serialized_response_body(response)

if response.respond_to?(:body)
# Rack responses
begin
response.body.map{ |body| JSON.parse(body.to_s) }
rescue # No reason to have "=> e" here when we don't use it..
response.body.map { |body| JSON.parse(body.to_s) }
rescue StandardError # No reason to have "=> e" here when we don't use it..
response.body
end
else
Expand Down
19 changes: 10 additions & 9 deletions lib/grape_logging/middleware/request_logger.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
module GrapeLogging
module Middleware
class RequestLogger < Grape::Middleware::Base

ActiveSupport::Notifications.subscribe('sql.active_record') do |*args|
event = ActiveSupport::Notifications::Event.new(*args)
GrapeLogging::Timings.append_db_runtime(event)
end if defined?(ActiveRecord)
if defined?(ActiveRecord)
ActiveSupport::Notifications.subscribe('sql.active_record') do |*args|
event = ActiveSupport::Notifications::Event.new(*args)
GrapeLogging::Timings.append_db_runtime(event)
end
end

# Persist response status & response (body)
# to use int in parameters
Expand All @@ -18,10 +19,10 @@ def initialize(app, options = {})

@included_loggers = @options[:include] || []
@reporter = if options[:instrumentation_key]
Reporters::ActiveSupportReporter.new(@options[:instrumentation_key])
else
Reporters::LoggerReporter.new(@options[:logger], @options[:formatter], @options[:log_level])
end
Reporters::ActiveSupportReporter.new(@options[:instrumentation_key])
else
Reporters::LoggerReporter.new(@options[:logger], @options[:formatter], @options[:log_level])
end
end

def before
Expand Down
4 changes: 2 additions & 2 deletions lib/grape_logging/multi_io.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ def initialize(*targets)
end

def write(*args)
@targets.each {|t| t.write(*args)}
@targets.each { |t| t.write(*args) }
end

def close
@targets.each(&:close)
end
end
end
end
2 changes: 1 addition & 1 deletion lib/grape_logging/reporters/active_support_reporter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ def perform(params)
ActiveSupport::Notifications.instrument @instrumentation_key, params
end
end
end
end
4 changes: 1 addition & 3 deletions lib/grape_logging/reporters/logger_reporter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ class LoggerReporter
def initialize(logger, formatter, log_level)
@logger = logger.clone || Logger.new(STDOUT)
@log_level = log_level || :info
if @logger.respond_to?(:formatter=)
@logger.formatter = formatter || @logger.formatter || GrapeLogging::Formatters::Default.new
end
@logger.formatter = formatter || @logger.formatter || GrapeLogging::Formatters::Default.new if @logger.respond_to?(:formatter=)
end

def perform(params)
Expand Down
4 changes: 2 additions & 2 deletions lib/grape_logging/timings.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module GrapeLogging
module Timings
extend self
module_function

def db_runtime=(value)
Thread.current[:grape_db_runtime] = value
Expand All @@ -18,4 +18,4 @@ def append_db_runtime(event)
self.db_runtime += event.duration
end
end
end
end
16 changes: 9 additions & 7 deletions lib/grape_logging/util/parameter_filter.rb
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
if defined?(::Rails.application)
if defined?(Rails.application)
if Gem::Version.new(Rails.version) < Gem::Version.new('6.0.0')
class ParameterFilter < ActionDispatch::Http::ParameterFilter
def initialize(_replacement, filter_parameters)
super(filter_parameters)
end
end
else
require "active_support/parameter_filter"
require 'active_support/parameter_filter'

class ParameterFilter < ActiveSupport::ParameterFilter
def initialize(_replacement, filter_parameters)
Expand Down Expand Up @@ -37,9 +37,11 @@ def compiled_filter

class CompiledFilter # :nodoc:
def self.compile(replacement, filters)
return lambda { |params| params.dup } if filters.empty?
return ->(params) { params.dup } if filters.empty?

strings, regexps, blocks = [], [], []
strings = []
regexps = []
blocks = []

filters.each do |item|
case item
Expand All @@ -52,8 +54,8 @@ def self.compile(replacement, filters)
end
end

deep_regexps, regexps = regexps.partition { |r| r.to_s.include?("\\.".freeze) }
deep_strings, strings = strings.partition { |s| s.include?("\\.".freeze) }
deep_regexps, regexps = regexps.partition { |r| r.to_s.include?('\\.'.freeze) }
deep_strings, strings = strings.partition { |s| s.include?('\\.'.freeze) }

regexps << Regexp.new(strings.join('|'.freeze), true) unless strings.empty?
deep_regexps << Regexp.new(deep_strings.join('|'.freeze), true) unless deep_strings.empty?
Expand All @@ -67,7 +69,7 @@ def initialize(replacement, regexps, deep_regexps, blocks)
@replacement = replacement
@regexps = regexps
@deep_regexps = deep_regexps.any? ? deep_regexps : nil
@blocks = blocks
@blocks = blocks
end

def call(original_params, parents = [])
Expand Down
33 changes: 16 additions & 17 deletions spec/lib/grape_logging/formatters/rails_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,23 @@

describe GrapeLogging::Formatters::Rails do
let(:formatter) { described_class.new }
let(:severity) { "INFO" }
let(:severity) { 'INFO' }
let(:datetime) { Time.new('2018', '03', '02', '10', '35', '04', '+13:00') }

let(:exception_data) { ArgumentError.new('Message') }
let(:hash_data) {
let(:hash_data) do
{
status: 200,
time: {
total: 272.4,
db: 40.63,
view: 231.76999999999998
},
method: "GET",
path: "/api/endpoint",
host: "localhost"
method: 'GET',
path: '/api/endpoint',
host: 'localhost'
}
}
end

describe '#call' do
context 'string data' do
Expand All @@ -36,7 +36,7 @@
message = formatter.call(severity, datetime, nil, exception_data)
lines = message.split("\n")

expect(lines[0]).to eq "I [2018-03-02 10:35:04 +1300] INFO -- : Message (ArgumentError)"
expect(lines[0]).to eq 'I [2018-03-02 10:35:04 +1300] INFO -- : Message (ArgumentError)'
expect(lines[1]).to include '.rb'
expect(lines.size).to be > 1
end
Expand All @@ -52,9 +52,9 @@
it 'includes params if included (from GrapeLogging::Loggers::FilterParameters)' do
hash_data.merge!(
params: {
"some_param" => {
value_1: "123",
value_2: "456"
'some_param' => {
value_1: '123',
value_2: '456'
}
}
)
Expand All @@ -63,22 +63,21 @@
lines = message.split("\n")

expected_output = if RUBY_VERSION >= '3.4'
' Parameters: {"some_param" => {value_1: "123", value_2: "456"}}'
else
' Parameters: {"some_param"=>{:value_1=>"123", :value_2=>"456"}}'
end
' Parameters: {"some_param" => {value_1: "123", value_2: "456"}}'
else
' Parameters: {"some_param"=>{:value_1=>"123", :value_2=>"456"}}'
end
expect(lines.first).to eq expected_output
expect(lines.last).to eq "Completed 200 OK in 272.4ms (Views: 231.77ms | DB: 40.63ms)"
expect(lines.last).to eq 'Completed 200 OK in 272.4ms (Views: 231.77ms | DB: 40.63ms)'
end
end

context "unhandled data" do
context 'unhandled data' do
it 'returns the #inspect string representation' do
message = formatter.call(severity, datetime, nil, [1, 2, 3])

expect(message).to eq "[1, 2, 3]\n"
end
end
end

end
Loading