Skip to main content

gcloud_observability/logs/
error_reporting.rs

1//! Error Reporting support for the logging layer.
2//!
3//! Cloud Error Reporting groups the entries it recognises as errors. For entries written
4//! through Cloud Logging it recognises one when its `jsonPayload` carries the
5//! `ReportedErrorEvent` type, which forces evaluation, and reads the error text from
6//! `stack_trace`, then `exception`, then `message`; the first present wins. Rust stack traces
7//! are accepted when they carry standard `std::backtrace` frames. Without a trace, an error is
8//! grouped by its message and by `context.reportLocation`, which is why that is always set.
9//!
10//! <https://docs.cloud.google.com/error-reporting/docs/formatting-error-messages>
11//! <https://docs.cloud.google.com/error-reporting/reference/rest/v1beta1/projects.events/report>
12
13use serde_json::{Map, Value};
14use std::backtrace::{Backtrace, BacktraceStatus};
15use std::error::Error;
16use tracing::Metadata;
17
18use super::format::{as_i64, KEY_HTTP_REQUEST, KEY_MESSAGE};
19
20/// Forces Error Reporting to evaluate the entry as an error event.
21const KEY_TYPE: &str = "@type";
22const REPORTED_ERROR_EVENT_TYPE: &str =
23    "type.googleapis.com/google.devtools.clouderrorreporting.v1beta1.ReportedErrorEvent";
24/// Required: names the service the error is grouped under.
25const KEY_SERVICE_CONTEXT: &str = "serviceContext";
26/// Holds `reportLocation` and `httpRequest`, as Error Reporting's `ErrorContext`.
27const KEY_CONTEXT: &str = "context";
28/// Required when the entry carries no stack trace.
29const KEY_REPORT_LOCATION: &str = "reportLocation";
30/// Error Reporting's own request context, a different shape from the top-level `httpRequest`
31/// that Cloud Logging maps to `LogEntry.httpRequest`.
32const KEY_CONTEXT_HTTP_REQUEST: &str = "httpRequest";
33/// An event field that names the exception type for the OTLP `exception.type` attribute; a
34/// `&dyn Error` has no type name on stable Rust.
35const FIELD_EXCEPTION_TYPE: &str = "exception.type";
36/// The event field the panic hook records the panic's `file:line:column` in.
37const FIELD_PANIC_LOCATION: &str = "panic.location";
38
39/// `HttpRequest` member names mapped to Error Reporting's `HttpRequestContext` members.
40const HTTP_REQUEST_CONTEXT_KEYS: [(&str, &str); 6] = [
41    ("requestMethod", "method"),
42    ("requestUrl", "url"),
43    ("userAgent", "userAgent"),
44    ("referer", "referrer"),
45    ("status", "responseStatusCode"),
46    ("remoteIp", "remoteIp"),
47];
48
49/// The service Error Reporting groups errors under, as `serviceContext` in its entries.
50///
51/// Set through
52/// [`GcpCloudLoggingLayerBuilder::with_error_reporting`](crate::logs::GcpCloudLoggingLayerBuilder::with_error_reporting).
53#[derive(Debug, Clone)]
54pub struct ServiceContext {
55    service: String,
56    version: Option<String>,
57}
58
59impl ServiceContext {
60    /// Names the service, for example the Cloud Run service or the binary name.
61    pub fn new(service: impl Into<String>) -> Self {
62        Self {
63            service: service.into(),
64            version: None,
65        }
66    }
67
68    /// Sets the deployed version, which Error Reporting shows beside the error.
69    pub fn with_version(mut self, version: impl Into<String>) -> Self {
70        self.version = Some(version.into());
71        self
72    }
73
74    /// Turns `record`, built for an event at ERROR severity or above, into an Error Reporting
75    /// event, and returns the exception details the OTLP sink sends as attributes.
76    ///
77    /// `error_chain` is the texts of the event's first `&dyn Error` field, outermost first.
78    /// The backtrace is captured here, at the event site, so it costs nothing unless
79    /// `RUST_BACKTRACE` or `RUST_LIB_BACKTRACE` enables it.
80    pub(crate) fn report(
81        &self,
82        record: &mut Map<String, Value>,
83        metadata: &Metadata<'_>,
84        error_chain: Option<&[String]>,
85    ) -> ExceptionDetails {
86        let event_message = match record.get(KEY_MESSAGE) {
87            Some(Value::String(message)) => message.clone(),
88            Some(other) => other.to_string(),
89            None => String::new(),
90        };
91        let exception_message = match error_chain {
92            Some(chain) => chain.join(": "),
93            None => event_message.clone(),
94        };
95        let stacktrace = capture_backtrace();
96
97        // The trace goes in `message` only: `stack_trace` would hide it, and with it the header.
98        // The chain stays on the header line: Error Reporting keys a group on the cause a
99        // `Caused by:` line names, so unrelated errors that share a root cause would be one
100        // group.
101        let mut message = match error_chain {
102            Some(_) => format!("{event_message}: {exception_message}"),
103            None => event_message,
104        };
105        if let Some(stacktrace) = &stacktrace {
106            message.push_str("\n\n");
107            message.push_str(stacktrace);
108        }
109        record.insert(KEY_MESSAGE.to_string(), Value::from(message));
110
111        record.insert(KEY_TYPE.to_string(), Value::from(REPORTED_ERROR_EVENT_TYPE));
112        let mut service = Map::new();
113        service.insert("service".to_string(), Value::from(self.service.clone()));
114        if let Some(version) = &self.version {
115            service.insert("version".to_string(), Value::from(version.clone()));
116        }
117        record.insert(KEY_SERVICE_CONTEXT.to_string(), Value::Object(service));
118
119        let mut context = Map::new();
120        let location = report_location(record, metadata);
121        if !location.is_empty() {
122            context.insert(KEY_REPORT_LOCATION.to_string(), Value::Object(location));
123        }
124        if let Some(Value::Object(request)) = record.get(KEY_HTTP_REQUEST) {
125            let request = http_request_context(request);
126            if !request.is_empty() {
127                context.insert(KEY_CONTEXT_HTTP_REQUEST.to_string(), Value::Object(request));
128            }
129        }
130        if !context.is_empty() {
131            record.insert(KEY_CONTEXT.to_string(), Value::Object(context));
132        }
133
134        ExceptionDetails {
135            kind: match record.get(FIELD_EXCEPTION_TYPE) {
136                Some(Value::String(kind)) => Some(kind.clone()),
137                _ => None,
138            },
139            message: exception_message,
140        }
141    }
142}
143
144/// Where the error is reported from: the location of a panic, which the panic hook records in
145/// `panic.location`, and otherwise the code location of the event. The hook's own location
146/// would put every panic at one place.
147fn report_location(record: &Map<String, Value>, metadata: &Metadata<'_>) -> Map<String, Value> {
148    let mut location = Map::new();
149    let panic_location = record
150        .get(FIELD_PANIC_LOCATION)
151        .and_then(Value::as_str)
152        .and_then(|text| {
153            let (file_and_line, _column) = text.rsplit_once(':')?;
154            let (file, line) = file_and_line.rsplit_once(':')?;
155            Some((file, line.parse::<u32>().ok()?))
156        });
157    match panic_location {
158        Some((file, line)) => {
159            location.insert("filePath".to_string(), Value::from(file));
160            location.insert("lineNumber".to_string(), Value::from(line));
161        }
162        None => {
163            if let Some(file) = metadata.file() {
164                location.insert("filePath".to_string(), Value::from(file));
165            }
166            if let Some(line) = metadata.line() {
167                location.insert("lineNumber".to_string(), Value::from(line));
168            }
169            if let Some(module_path) = metadata.module_path() {
170                location.insert("functionName".to_string(), Value::from(module_path));
171            }
172        }
173    }
174    location
175}
176
177fn http_request_context(request: &Map<String, Value>) -> Map<String, Value> {
178    HTTP_REQUEST_CONTEXT_KEYS
179        .iter()
180        .filter_map(|(logging_key, context_key)| {
181            let value = request.get(*logging_key)?;
182            // Error Reporting types the status as an integer; the layer may hold it as a string.
183            let value = if *logging_key == "status" {
184                as_i64(value).map_or_else(|| value.clone(), Value::from)
185            } else {
186                value.clone()
187            };
188            Some((context_key.to_string(), value))
189        })
190        .collect()
191}
192
193/// The backtrace at the call site, or `None` when capturing is disabled or unsupported.
194/// Never forces a capture: that costs milliseconds per event.
195fn capture_backtrace() -> Option<String> {
196    let backtrace = Backtrace::capture();
197    (backtrace.status() == BacktraceStatus::Captured).then(|| backtrace.to_string())
198}
199
200/// What the OTLP sink sets as the OpenTelemetry `exception.*` attributes on an error event.
201// Read only by the OTLP sink.
202#[cfg_attr(not(feature = "logs-otlp"), allow(dead_code))]
203pub(crate) struct ExceptionDetails {
204    pub(crate) kind: Option<String>,
205    pub(crate) message: String,
206}
207
208/// `error` and its `source()` chain as text, outermost first. `tracing` hands an event field
209/// only as `&dyn Error`, so the chain is read while the event is recorded.
210pub(crate) fn error_chain(error: &(dyn Error + 'static)) -> Vec<String> {
211    std::iter::successors(Some(error), |cause| (*cause).source())
212        .map(ToString::to_string)
213        .collect()
214}
215
216/// Emits one `tracing` error event for every panic, then calls the hook that was installed
217/// before. Call it once, early in `main`.
218///
219/// The event carries the panic message and `panic.location`, and `context.reportLocation`
220/// names that location. It reaches Error Reporting when the logging layer was built with
221/// [`with_error_reporting`](crate::logs::GcpCloudLoggingLayerBuilder::with_error_reporting);
222/// the backtrace the layer captures then runs from this hook, and needs `RUST_BACKTRACE`.
223///
224/// The Cloud Logging API and OTLP sinks only queue the event and send it later in the
225/// background, so it is lost when the process ends before the queue is flushed: after
226/// `panic = "abort"`, or when a panic unwinds out of `main`, unless something flushes on the
227/// way, such as a guard that shuts the logger provider down on drop. Flush or shut down the
228/// logger provider or the `GcpCloudLoggingHandle` before the process ends, or use the JSON
229/// sink, which writes the event before this hook returns.
230pub fn install_panic_hook() {
231    let previous_hook = std::panic::take_hook();
232    std::panic::set_hook(Box::new(move |info| {
233        let message = info
234            .payload_as_str()
235            .unwrap_or("panic with a non-string payload");
236        match info.location() {
237            Some(location) => tracing::error!(
238                "exception.type" = "panic",
239                "panic.location" = %location,
240                "{message}"
241            ),
242            None => tracing::error!("exception.type" = "panic", "{message}"),
243        }
244        previous_hook(info);
245    }));
246}