Skip to content

Commit e164315

Browse files
committed
fix(logs): skip malformed utf-8 messages
1 parent f7b7438 commit e164315

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

sentry-ruby/lib/sentry/client.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
require "sentry/log_event"
55
require "sentry/log_event_buffer"
66
require "sentry/utils/uuid"
7+
require "sentry/utils/encoding_helper"
78

89
module Sentry
910
class Client
@@ -194,8 +195,11 @@ def event_from_log(message, level:, **options)
194195

195196
attributes = options.reject { |k, _| k == :level || k == :severity || k == :origin }
196197
origin = options[:origin]
198+
body = Utils::EncodingHelper.safe_utf_8_string(message)
197199

198-
LogEvent.new(level: level, body: message, attributes: attributes, origin: origin)
200+
return unless body
201+
202+
LogEvent.new(level: level, body: body, attributes: attributes, origin: origin)
199203
end
200204

201205
# Initializes an Event object with the given Transaction object.

sentry-ruby/lib/sentry/utils/encoding_helper.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
module Sentry
44
module Utils
55
module EncodingHelper
6+
EMPTY_STRING = ""
7+
68
def self.encode_to_utf_8(value)
79
if value.encoding != Encoding::UTF_8 && value.respond_to?(:force_encoding)
810
value = value.dup.force_encoding(Encoding::UTF_8)
@@ -17,6 +19,10 @@ def self.valid_utf_8?(value)
1719

1820
value.dup.force_encoding(Encoding::UTF_8).valid_encoding?
1921
end
22+
23+
def self.safe_utf_8_string(value)
24+
valid_utf_8?(value) && value
25+
end
2026
end
2127
end
2228
end

sentry-ruby/spec/sentry/structured_logger_spec.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,13 @@
9595
expect(log_event[:attributes]["sentry.message.parameter.name"]).to eql({ value: "Jane", type: "string" })
9696
expect(log_event[:attributes]["sentry.message.parameter.day"]).to eql({ value: "Monday", type: "string" })
9797
end
98+
99+
it "doesn't choke on malformed UTF-8 strings" do
100+
malformed_string = "Hello World\x92".dup.force_encoding("UTF-8")
101+
Sentry.logger.public_send(level, malformed_string, user_id: 123)
102+
103+
expect(sentry_logs).to be_empty
104+
end
98105
end
99106
end
100107

0 commit comments

Comments
 (0)