grow-graylog 0.2.0

Rust SDK for Graylog Open by Grow Codes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
//! `init_logging`: JSON lines on stdout plus the SDK transport chosen by `GROW_LOGGING_PROVIDER`
//! (GRO-1390 foundation contract).

use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use async_trait::async_trait;

use crate::core::transport::SDK_KEY;
use crate::core::Result;

use super::record::format_timestamp;
use super::{
    active_trace_context, Attributes, BatchStats, DropCallback, LogClient, LogEntry, LogInput,
    LogRecord, Logger, RedactionProcessor, Severity,
};

/// Top-level stdout field: `"sdk"` = the SDK also exports the record (the collector skips the
/// line), `"sdk_failed"` = the SDK could not export it (the collector ships the line).
pub const LOG_SHIPPED_FIELD: &str = "log_shipped";

tokio::task_local! {
    static REQUEST_ID: String;
}

/// Runs `fut` with `request_id` attached to every record it logs through [`init_logging`].
pub async fn with_request_id<F: Future>(request_id: impl Into<String>, fut: F) -> F::Output {
    REQUEST_ID.scope(request_id.into(), fut).await
}

/// The request id of the current task ([`with_request_id`]).
pub fn current_request_id() -> Option<String> {
    REQUEST_ID.try_with(Clone::clone).ok()
}

/// The SDK transport returned by a connector.
pub struct LogConnection {
    /// Batching log client of this package (closed by [`LoggingHandle::close`]).
    pub logs: Arc<dyn LogClient>,
}

/// Builds the SDK transport (`Ok(None)` = stdout only); must not do network I/O. The
/// [`DropCallback`] must be set as `BatchOptions::on_drop`: it re-emits records the SDK could not
/// export on stdout with `log_shipped="sdk_failed"`.
pub type LogConnector = Arc<
    dyn Fn(&Attributes, &HashMap<String, String>, DropCallback) -> Result<Option<LogConnection>>
        + Send
        + Sync,
>;

/// Writes one stdout line (default: `println!`).
pub type LineWriter = Arc<dyn Fn(&str) + Send + Sync>;

/// Options of [`init_logging`].
#[derive(Clone)]
pub struct InitOptions {
    /// `service.name` (default `GROW_SERVICE_NAME` > `OTEL_SERVICE_NAME` > `unknown_service`).
    pub service: Option<String>,
    /// Minimum level: trace|debug|info|warn|error|fatal (default `LOG_LEVEL` > `info`).
    pub level: Option<String>,
    /// Write JSON lines to stdout (default `true`).
    pub stdout: bool,
    /// Force (`Some(true)`) or disable the SDK transport (default: `GROW_LOGGING_PROVIDER`).
    pub ship: Option<bool>,
    /// Environment (default: the process environment).
    pub env: Option<HashMap<String, String>>,
    /// Line writer (tests).
    pub writer: Option<LineWriter>,
    /// Connector override (tests, custom clients).
    pub connector: Option<LogConnector>,
}

impl Default for InitOptions {
    fn default() -> Self {
        InitOptions {
            service: None,
            level: None,
            stdout: true,
            ship: None,
            env: None,
            writer: None,
            connector: None,
        }
    }
}

impl fmt::Debug for InitOptions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("InitOptions")
            .field("service", &self.service)
            .field("level", &self.level)
            .field("stdout", &self.stdout)
            .field("ship", &self.ship)
            .finish_non_exhaustive()
    }
}

/// `LogClient` that writes the redacted stdout JSON copy and forwards to the SDK transport.
struct Tee {
    writer: Option<LineWriter>,
    logs: Option<Arc<dyn LogClient>>,
    resource: Attributes,
    service: String,
    environment: Option<String>,
    redaction: RedactionProcessor,
}

impl Tee {
    fn line(&self, record: &LogRecord) -> String {
        let mut line = serde_json::Map::new();
        line.insert("time".into(), format_timestamp(record.timestamp).into());
        line.insert("level".into(), record.severity.text().to_lowercase().into());
        line.insert("msg".into(), record.body.clone().into());
        line.insert("service".into(), self.service.clone().into());
        if let Some(env) = &self.environment {
            line.insert("environment".into(), env.clone().into());
        }
        if let (Some(t), Some(s)) = (&record.trace_id, &record.span_id) {
            line.insert("trace_id".into(), t.clone().into());
            line.insert("span_id".into(), s.clone().into());
        }
        for (k, v) in &record.attributes {
            line.entry(k.clone()).or_insert_with(|| v.clone());
        }
        if self.logs.is_some() {
            line.insert(LOG_SHIPPED_FIELD.into(), "sdk".into());
        }
        serde_json::Value::Object(line).to_string()
    }
}

#[async_trait]
impl LogClient for Tee {
    fn send(&self, entry: LogEntry) {
        let LogEntry::Input(input) = entry else {
            if let Some(logs) = &self.logs {
                logs.send(entry);
            }
            return;
        };
        let severity = input.severity.unwrap_or_default();
        let mut record = LogRecord::new(severity, input.message);
        record.attributes = input.attributes;
        if let Some(id) = current_request_id() {
            record
                .attributes
                .entry("request_id".into())
                .or_insert(id.into());
        }
        record.resource = self.resource.clone();
        if let Some(ts) = input.timestamp {
            record.timestamp = ts;
        }
        record.trace_id = input.trace_id;
        record.span_id = input.span_id;
        if record.trace_id.is_none() {
            if let Some((trace, span, flags)) = active_trace_context() {
                record.trace_id = Some(trace);
                record.span_id = Some(span);
                record.trace_flags = Some(flags);
            }
        }
        if let Some(writer) = &self.writer {
            writer(&self.line(&self.redaction.process(&record)));
        }
        if let Some(logs) = &self.logs {
            logs.send(LogEntry::Record(record));
        }
    }

    async fn flush(&self, timeout: Option<Duration>) -> Result<()> {
        match &self.logs {
            Some(logs) => logs.flush(timeout).await,
            None => Ok(()),
        }
    }

    async fn close(&self) -> Result<()> {
        match &self.logs {
            Some(logs) => logs.close().await,
            None => Ok(()),
        }
    }

    fn stats(&self) -> BatchStats {
        self.logs.as_ref().map(|l| l.stats()).unwrap_or_default()
    }

    fn logger(&self, name: Option<&str>, attributes: Attributes) -> Logger {
        let _ = name;
        Logger::new(Arc::new(NoopClient), attributes)
    }
}

/// Placeholder used only by `Tee::logger` (the handle hands out loggers bound to the tee).
struct NoopClient;

#[async_trait]
impl LogClient for NoopClient {
    fn send(&self, _entry: LogEntry) {}
    async fn flush(&self, _timeout: Option<Duration>) -> Result<()> {
        Ok(())
    }
    async fn close(&self) -> Result<()> {
        Ok(())
    }
    fn stats(&self) -> BatchStats {
        BatchStats::default()
    }
    fn logger(&self, _name: Option<&str>, attributes: Attributes) -> Logger {
        Logger::new(Arc::new(NoopClient), attributes)
    }
}

/// Handle returned by [`init_logging`].
#[derive(Clone)]
pub struct LoggingHandle {
    tee: Arc<Tee>,
    min: Severity,
    closed: Arc<Mutex<bool>>,
}

impl fmt::Debug for LoggingHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("LoggingHandle")
            .field("service", &self.tee.service)
            .field("shipped", &self.shipped())
            .finish()
    }
}

impl LoggingHandle {
    /// A logger writing to stdout and the SDK transport.
    pub fn logger(&self) -> Logger {
        Logger::new(self.tee.clone(), Attributes::new()).with_min_severity(self.min)
    }

    /// The client behind [`LoggingHandle::logger`] (for `LogLayer` / `LogBridge`).
    pub fn client(&self) -> Arc<dyn LogClient> {
        self.tee.clone()
    }

    /// Whether records are shipped through the SDK.
    pub fn shipped(&self) -> bool {
        self.tee.logs.is_some()
    }

    /// `service.name` of every record.
    pub fn service(&self) -> &str {
        &self.tee.service
    }

    /// Exports everything queued now.
    pub async fn flush(&self) -> Result<()> {
        self.tee.flush(Some(Duration::from_secs(5))).await
    }

    /// Flushes and closes the SDK transport; idempotent.
    pub async fn close(&self) -> Result<()> {
        {
            let mut closed = self.closed.lock().unwrap_or_else(|e| e.into_inner());
            if *closed {
                return Ok(());
            }
            *closed = true;
        }
        self.tee.close().await
    }

    /// Sends `message` (e.g. `foundation-canary-<token>`) through the SDK only and flushes.
    /// Returns `false` when records are not shipped.
    pub async fn canary(&self, message: &str, attributes: Attributes) -> bool {
        let Some(logs) = &self.tee.logs else {
            return false;
        };
        let mut attrs = attributes;
        attrs.insert("foundation.canary".into(), true.into());
        logs.send(LogEntry::Input(
            LogInput::new(message)
                .severity(Severity::Info)
                .attributes(attrs),
        ));
        let _ = logs.flush(Some(Duration::from_secs(5))).await;
        true
    }
}

/// The stdout line of a record the SDK could not export (`log_shipped="sdk_failed"`).
fn failed_line(record: &LogRecord) -> String {
    let mut line = serde_json::Map::new();
    line.insert("time".into(), format_timestamp(record.timestamp).into());
    line.insert("level".into(), record.severity.text().to_lowercase().into());
    line.insert("msg".into(), record.body.clone().into());
    if let Some(v) = record.resource.get("service.name") {
        line.insert("service".into(), v.clone());
    }
    if let Some(v) = record.resource.get("deployment.environment") {
        line.insert("environment".into(), v.clone());
    }
    if let (Some(t), Some(s)) = (&record.trace_id, &record.span_id) {
        line.insert("trace_id".into(), t.clone().into());
        line.insert("span_id".into(), s.clone().into());
    }
    for (k, v) in &record.attributes {
        line.entry(k.clone()).or_insert_with(|| v.clone());
    }
    line.insert(LOG_SHIPPED_FIELD.into(), "sdk_failed".into());
    serde_json::Value::Object(line).to_string()
}

fn first(env: &HashMap<String, String>, names: &[&str]) -> Option<String> {
    names
        .iter()
        .filter_map(|n| env.get(*n))
        .map(|v| v.trim().to_string())
        .find(|v| !v.is_empty())
}

/// Initialises logging: JSON lines on stdout and, when `GROW_LOGGING_PROVIDER` names this package
/// (or `ship`), the SDK transport from the package's own `GROW_<KEY>_*` variables (stdout lines
/// then carry `log_shipped="sdk"`). Never fails for an unreachable logging service. Install
/// `LogLayer::new(handle.client())` to route `tracing` events through it.
pub fn init_logging(opts: InitOptions) -> LoggingHandle {
    let env: HashMap<String, String> = opts
        .env
        .clone()
        .unwrap_or_else(|| std::env::vars().collect());
    let service = opts
        .service
        .clone()
        .or_else(|| first(&env, &["GROW_SERVICE_NAME", "OTEL_SERVICE_NAME"]))
        .unwrap_or_else(|| "unknown_service".into());
    let environment = first(&env, &["GROW_ENVIRONMENT", "DEPLOYMENT_ENVIRONMENT"]);
    let min = opts
        .level
        .clone()
        .or_else(|| first(&env, &["LOG_LEVEL"]))
        .and_then(|l| l.parse::<Severity>().ok())
        .unwrap_or(Severity::Info);
    let mut resource = Attributes::new();
    resource.insert("service.name".into(), service.clone().into());
    if let Some(e) = &environment {
        resource.insert("deployment.environment".into(), e.clone().into());
    }
    let writer: LineWriter = opts
        .writer
        .clone()
        .unwrap_or_else(|| Arc::new(|l: &str| println!("{l}")));
    let ship = opts
        .ship
        .unwrap_or_else(|| first(&env, &["GROW_LOGGING_PROVIDER"]).as_deref() == Some(SDK_KEY));
    let mut logs = None;
    if ship {
        let failed_writer = writer.clone();
        let on_dropped: DropCallback = Arc::new(move |records, _reason| {
            for record in records {
                failed_writer(&failed_line(record));
            }
        });
        let result = match &opts.connector {
            Some(connect) => connect(&resource, &env, on_dropped),
            None => connect_log_client(&resource, &env, on_dropped),
        };
        match result {
            Ok(conn) => logs = conn.map(|c| c.logs),
            Err(err) => writer(
                &serde_json::json!({
                    "time": format_timestamp(std::time::SystemTime::now()),
                    "level": "warn",
                    "msg": format!("logging: {SDK_KEY} transport not available, stdout only ({:?})", err.code()),
                    "service": service,
                })
                .to_string(),
            ),
        }
    }
    let tee = Tee {
        writer: opts.stdout.then_some(writer),
        logs,
        resource,
        service,
        environment,
        redaction: RedactionProcessor::default(),
    };
    LoggingHandle {
        tee: Arc::new(tee),
        min,
        closed: Arc::new(Mutex::new(false)),
    }
}

/// The connector of this package: builds the SDK log client from the package's own variables with
/// `resource` attached and `on_dropped` as `BatchOptions::on_drop`. Must not do network I/O. The
/// body is service-owned (keep region).
#[allow(unused_variables)]
pub fn connect_log_client(
    resource: &Attributes,
    env: &HashMap<String, String>,
    on_dropped: DropCallback,
) -> Result<Option<LogConnection>> {
    // @sdk-kit:keep connector — service-owned body: build the log client (no network I/O)
    Ok(None)
    // @sdk-kit:endkeep
}