Skip to content

Commit 609d75f

Browse files
committed
RUBY-897 Print first 250 chars of query selector when logging and rescue inspect error
1 parent dfdf9af commit 609d75f

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

lib/mongo/protocol/query.rb

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,12 @@ module Protocol
3030
# @api semipublic
3131
class Query < Message
3232

33+
# Constant for the max number of characters to print when inspecting
34+
# a query field.
35+
#
36+
# @since 2.0.3
37+
LOG_STRING_LIMIT = 250
38+
3339
# Creates a new Query message
3440
#
3541
# @example Find all users named Tyler.
@@ -78,7 +84,7 @@ def log_message
7884
fields = []
7985
fields << ["%s |", query_type]
8086
fields << ["namespace=%s", namespace]
81-
fields << ["selector=%s", selector.inspect]
87+
fields << ["selector=%s", formatted_selector]
8288
fields << ["flags=%s", flags.inspect]
8389
fields << ["limit=%s", limit.inspect]
8490
fields << ["skip=%s", skip.inspect]
@@ -111,6 +117,13 @@ def query_type
111117
namespace.include?(Database::COMMAND) ? 'COMMAND' : 'QUERY'
112118
end
113119

120+
def formatted_selector
121+
( (str = selector.inspect).length > LOG_STRING_LIMIT ) ?
122+
"#{str[0..LOG_STRING_LIMIT]}..." : str
123+
rescue ArgumentError
124+
'<Could not inspect selector>'
125+
end
126+
114127
# Available flags for a Query message.
115128
FLAGS = [
116129
:reserved,

spec/mongo/protocol/query_spec.rb

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,4 +282,33 @@
282282
end
283283
end
284284
end
285+
286+
describe '#log_message' do
287+
288+
context 'when the selector is greater than LOG_STRING_LIMIT characters' do
289+
290+
let(:selector) do
291+
'z'*260
292+
end
293+
294+
it 'Only prints LOG_STRING_LIMIT number of characters' do
295+
expect(message.log_message.scan(/z/).length).to eq(Mongo::Protocol::Query::LOG_STRING_LIMIT)
296+
end
297+
end
298+
299+
context 'when the selector cannot be inspected' do
300+
301+
let(:selector) do
302+
'invalid string'
303+
end
304+
305+
before do
306+
allow(selector).to receive(:inspect).and_raise(ArgumentError)
307+
end
308+
309+
it 'Does not include the selector in the log message' do
310+
expect(message.log_message.scan(/invalid string/).length).to eq(0)
311+
end
312+
end
313+
end
285314
end

0 commit comments

Comments
 (0)