gcloud_observability/logs/
error_reporting.rs1use 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
20const KEY_TYPE: &str = "@type";
22const REPORTED_ERROR_EVENT_TYPE: &str =
23 "type.googleapis.com/google.devtools.clouderrorreporting.v1beta1.ReportedErrorEvent";
24const KEY_SERVICE_CONTEXT: &str = "serviceContext";
26const KEY_CONTEXT: &str = "context";
28const KEY_REPORT_LOCATION: &str = "reportLocation";
30const KEY_CONTEXT_HTTP_REQUEST: &str = "httpRequest";
33const FIELD_EXCEPTION_TYPE: &str = "exception.type";
36const FIELD_PANIC_LOCATION: &str = "panic.location";
38
39const 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#[derive(Debug, Clone)]
54pub struct ServiceContext {
55 service: String,
56 version: Option<String>,
57}
58
59impl ServiceContext {
60 pub fn new(service: impl Into<String>) -> Self {
62 Self {
63 service: service.into(),
64 version: None,
65 }
66 }
67
68 pub fn with_version(mut self, version: impl Into<String>) -> Self {
70 self.version = Some(version.into());
71 self
72 }
73
74 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 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
144fn 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 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
193fn capture_backtrace() -> Option<String> {
196 let backtrace = Backtrace::capture();
197 (backtrace.status() == BacktraceStatus::Captured).then(|| backtrace.to_string())
198}
199
200#[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
208pub(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
216pub 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}