Skip to content

RUBY-897 Print first 250 chars of query selector when logging and rescue inspect error #610

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 24, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
15 changes: 14 additions & 1 deletion lib/mongo/protocol/query.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ module Protocol
# @api semipublic
class Query < Message

# Constant for the max number of characters to print when inspecting
# a query field.
#
# @since 2.0.3
LOG_STRING_LIMIT = 250

# Creates a new Query message
#
# @example Find all users named Tyler.
Expand Down Expand Up @@ -78,7 +84,7 @@ def log_message
fields = []
fields << ["%s |", query_type]
fields << ["namespace=%s", namespace]
fields << ["selector=%s", selector.inspect]
fields << ["selector=%s", formatted_selector]
fields << ["flags=%s", flags.inspect]
fields << ["limit=%s", limit.inspect]
fields << ["skip=%s", skip.inspect]
Expand Down Expand Up @@ -111,6 +117,13 @@ def query_type
namespace.include?(Database::COMMAND) ? 'COMMAND' : 'QUERY'
end

def formatted_selector
( (str = selector.inspect).length > LOG_STRING_LIMIT ) ?
"#{str[0..LOG_STRING_LIMIT]}..." : str
rescue ArgumentError
'<Unable to inspect selector>'
end

# Available flags for a Query message.
FLAGS = [
:reserved,
Expand Down
29 changes: 29 additions & 0 deletions spec/mongo/protocol/query_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -282,4 +282,33 @@
end
end
end

describe '#log_message' do

context 'when the selector is greater than LOG_STRING_LIMIT characters' do

let(:selector) do
'z'*260
end

it 'Only prints LOG_STRING_LIMIT number of characters' do
expect(message.log_message.scan(/z/).length).to eq(Mongo::Protocol::Query::LOG_STRING_LIMIT)
end
end

context 'when the selector cannot be inspected' do

let(:selector) do
'invalid string'
end

before do
allow(selector).to receive(:inspect).and_raise(ArgumentError)
end

it 'Does not include the selector in the log message' do
expect(message.log_message.scan(/invalid string/).length).to eq(0)
end
end
end
end