DEV: Add exception class and message fields to DiscourseLogstashLogger (#27787)

This commit updates `DiscourseLogstashlogger` to add the
`exception_class` and `exception_message` field to the log line when the
`progname` of the log message is `web-exception` which is Logster's
logging of exceptions during a web request.

The `exception_class` and `exception_message` fields allows consumers of
the logs to easily group logs together.
This commit is contained in:
Alan Guo Xiang Tan 2024-07-10 08:54:39 +08:00 committed by GitHub
parent 7049838673
commit af2bd4cc50
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 21 additions and 0 deletions

View File

@ -74,6 +74,17 @@ class DiscourseLogstashLogger < Logger
event["backtrace"] = backtrace event["backtrace"] = backtrace
end end
# `web-exception` is a log message triggered by logster.
# The exception class and message are extracted from the message based on the format logged by logster in
# https://github.com/discourse/logster/blob/25375250fb8a5c312e9c55a75f6048637aad2c69/lib/logster/middleware/debug_exceptions.rb#L22.
#
# In theory we could get logster to include the exception class and message in opts but logster currently does not
# need those options so we are parsing it from the message for now and not making a change in logster.
if progname == "web-exception" && message =~ /^(\w+) \((.+)\)\n/
event["exception.class"] = $1
event["exception.message"] = $2
end
if (env = opts&.dig(:env)).present? if (env = opts&.dig(:env)).present?
ALLOWED_HEADERS_FROM_ENV.each do |header| ALLOWED_HEADERS_FROM_ENV.each do |header|
event["request.headers.#{header.downcase}"] = opts[:env][header] event["request.headers.#{header.downcase}"] = opts[:env][header]

View File

@ -48,6 +48,16 @@ RSpec.describe DiscourseLogstashLogger do
expect(parsed["message"]).to eq("error message") expect(parsed["message"]).to eq("error message")
end end
it "logs a JSON string with the `exception_class` and `exception_message` fields when `progname` is `web-exception`" do
logger = described_class.logger(logdev: output, type: "test")
logger.add(Logger::ERROR, "StandardError (some error message)\ntest", "web-exception")
output.rewind
parsed = JSON.parse(output.read.chomp)
expect(parsed["exception.class"]).to eq("StandardError")
expect(parsed["exception.message"]).to eq("some error message")
end
it "logs a JSON string with the right fields when `customize_event` attribute is set" do it "logs a JSON string with the right fields when `customize_event` attribute is set" do
logger = logger =
described_class.logger( described_class.logger(