logforth_append_fastrace/lib.rs
1// Copyright 2024 FastLabs Developers
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Appender for integrating with [fastrace](https://crates.io/crates/fastrace).
16
17#![cfg_attr(docsrs, feature(doc_cfg))]
18
19use std::borrow::Cow;
20
21use jiff::Zoned;
22use logforth_core::Diagnostic;
23use logforth_core::Error;
24use logforth_core::append::Append;
25use logforth_core::kv::Key;
26use logforth_core::kv::Value;
27use logforth_core::kv::Visitor;
28use logforth_core::record::Record;
29
30/// An appender that adds log records to fastrace as an event associated to the current span.
31///
32/// # Examples
33///
34/// ```
35/// use logforth_append_fastrace::FastraceEvent;
36///
37/// let fastrace_appender = FastraceEvent::default();
38/// ```
39///
40/// # Caveats
41///
42/// The caller or application should ensure that the `flush` method or [`fastrace::flush`] is called
43/// before the program exits to collect the final events, especially when this appender is used
44/// in a global context.
45///
46/// Both the `exit` method and the drop glue do not call `fastrace::flush`, because it uses
47/// thread-local storage internally, which is not supported in `atexit` callbacks or arbitrary
48/// drop cases.
49#[derive(Default, Debug, Clone)]
50#[non_exhaustive]
51pub struct FastraceEvent {}
52
53impl Append for FastraceEvent {
54 fn append(&self, record: &Record, diags: &[Box<dyn Diagnostic>]) -> Result<(), Error> {
55 let message = record.payload().to_owned();
56
57 let mut collector = KvCollector { kv: Vec::new() };
58 record.key_values().visit(&mut collector)?;
59 for d in diags {
60 d.visit(&mut collector)?;
61 }
62
63 fastrace::local::LocalSpan::add_event(fastrace::Event::new(message).with_properties(
64 || {
65 [
66 (Cow::from("level"), Cow::from(record.level().name())),
67 (Cow::from("timestamp"), Cow::from(Zoned::now().to_string())),
68 ]
69 .into_iter()
70 .chain(
71 collector
72 .kv
73 .into_iter()
74 .map(|(k, v)| (Cow::from(k), Cow::from(v))),
75 )
76 },
77 ));
78
79 Ok(())
80 }
81
82 fn flush(&self) -> Result<(), Error> {
83 fastrace::flush();
84 Ok(())
85 }
86
87 fn exit(&self) -> Result<(), Error> {
88 // do nothing - because fastrace::flush uses thread-local storage internally,
89 // which is not supported in atexit callbacks.
90 Ok(())
91 }
92}
93
94struct KvCollector {
95 kv: Vec<(String, String)>,
96}
97
98impl Visitor for KvCollector {
99 fn visit(&mut self, key: Key, value: Value) -> Result<(), Error> {
100 self.kv.push((key.to_string(), value.to_string()));
101 Ok(())
102 }
103}