Skip to main content

rlg_tower/
lib.rs

1// lib.rs
2// Copyright © 2024-2026 RustLogs (RLG). All rights reserved.
3// SPDX-License-Identifier: Apache-2.0 OR MIT
4
5//! Tower middleware that emits structured rlg records for every
6//! HTTP request that passes through it.
7//!
8//! Compatible with any service that satisfies
9//! `tower::Service<http::Request<B>>` — axum, tonic, hyper services,
10//! `lambda_runtime`, custom stacks.
11//!
12//! # Example (axum)
13//!
14//! ```ignore
15//! use axum::{Router, routing::get};
16//! use rlg::log_format::LogFormat;
17//! use rlg::log_level::LogLevel;
18//! use rlg_tower::RlgLayer;
19//!
20//! let app: Router = Router::new()
21//!     .route("/", get(|| async { "hello" }))
22//!     .layer(
23//!         RlgLayer::new()
24//!             .level(LogLevel::INFO)
25//!             .format(LogFormat::JSON)
26//!             .header("x-request-id"),
27//!     );
28//! ```
29//!
30//! One record is emitted **per response**, with the following fields:
31//!
32//! | Attribute | Source |
33//! | --- | --- |
34//! | `component` | `"rlg-tower"` (override with `.component(...)`) |
35//! | `description` | `"<METHOD> <path> -> <status>"` |
36//! | `http.method` | request method |
37//! | `http.path` | request URI path |
38//! | `http.status` | response status code |
39//! | `http.latency_ms` | wall-clock milliseconds from poll-ready to ready response |
40//! | `trace_id`, `span_id` | extracted from configured request headers (W3C / b3) if present |
41
42#![forbid(unsafe_code)]
43#![deny(missing_docs)]
44
45use http::Request;
46use http::Response;
47use pin_project_lite::pin_project;
48use rlg::log::Log;
49use rlg::log_format::LogFormat;
50use rlg::log_level::LogLevel;
51use std::future::Future;
52use std::pin::Pin;
53use std::task::{Context, Poll};
54use std::time::Instant;
55use tower_layer::Layer;
56use tower_service::Service;
57
58/// Tower [`Layer`] that wraps a service with rlg request logging.
59///
60/// Build with [`RlgLayer::new`] and the fluent setters. Cheap to
61/// clone — internal state is a couple of small fields.
62#[derive(Debug, Clone)]
63pub struct RlgLayer {
64    config: Config,
65}
66
67#[derive(Debug, Clone)]
68struct Config {
69    level: LogLevel,
70    format: LogFormat,
71    component: &'static str,
72    trace_header: Option<&'static str>,
73}
74
75impl Default for Config {
76    fn default() -> Self {
77        Self {
78            level: LogLevel::INFO,
79            format: LogFormat::Logfmt,
80            component: "rlg-tower",
81            trace_header: None,
82        }
83    }
84}
85
86impl Default for RlgLayer {
87    fn default() -> Self {
88        Self::new()
89    }
90}
91
92impl RlgLayer {
93    /// Construct a new layer with the default configuration:
94    /// level INFO, format Logfmt, component `"rlg-tower"`, no
95    /// trace-header extraction.
96    #[must_use]
97    pub fn new() -> Self {
98        Self {
99            config: Config::default(),
100        }
101    }
102
103    /// Override the level emitted for every record.
104    #[must_use]
105    pub const fn level(mut self, level: LogLevel) -> Self {
106        self.config.level = level;
107        self
108    }
109
110    /// Override the wire format.
111    #[must_use]
112    pub const fn format(mut self, format: LogFormat) -> Self {
113        self.config.format = format;
114        self
115    }
116
117    /// Override the `component` attribute. Useful when multiple
118    /// services share a process and you want to distinguish their
119    /// access logs.
120    #[must_use]
121    pub const fn component(mut self, component: &'static str) -> Self {
122        self.config.component = component;
123        self
124    }
125
126    /// Configure a request header to extract as the `trace_id`
127    /// attribute. The common picks are `traceparent` (W3C
128    /// trace-context) or `x-b3-traceid` (Zipkin B3).
129    #[must_use]
130    pub const fn header(mut self, name: &'static str) -> Self {
131        self.config.trace_header = Some(name);
132        self
133    }
134}
135
136impl<S> Layer<S> for RlgLayer {
137    type Service = RlgService<S>;
138
139    fn layer(&self, inner: S) -> Self::Service {
140        RlgService {
141            inner,
142            config: self.config.clone(),
143        }
144    }
145}
146
147/// Service wrapper produced by [`RlgLayer`].
148#[derive(Debug, Clone)]
149pub struct RlgService<S> {
150    inner: S,
151    config: Config,
152}
153
154impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for RlgService<S>
155where
156    S: Service<Request<ReqBody>, Response = Response<ResBody>>,
157{
158    type Response = S::Response;
159    type Error = S::Error;
160    type Future = RlgFuture<S::Future>;
161
162    fn poll_ready(
163        &mut self,
164        cx: &mut Context<'_>,
165    ) -> Poll<Result<(), Self::Error>> {
166        self.inner.poll_ready(cx)
167    }
168
169    fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
170        let method = req.method().clone();
171        let path = req.uri().path().to_string();
172        let trace_id = self
173            .config
174            .trace_header
175            .and_then(|name| req.headers().get(name))
176            .and_then(|v| v.to_str().ok())
177            .map(str::to_string);
178        let cfg = self.config.clone();
179        let start = Instant::now();
180        let fut = self.inner.call(req);
181        RlgFuture {
182            inner: fut,
183            method,
184            path,
185            trace_id,
186            cfg,
187            start,
188        }
189    }
190}
191
192pin_project! {
193    /// Future returned by [`RlgService::call`].
194    #[derive(Debug)]
195    pub struct RlgFuture<F> {
196        #[pin]
197        inner: F,
198        method: http::Method,
199        path: String,
200        trace_id: Option<String>,
201        cfg: Config,
202        start: Instant,
203    }
204}
205
206impl<F, ResBody, E> Future for RlgFuture<F>
207where
208    F: Future<Output = Result<Response<ResBody>, E>>,
209{
210    type Output = Result<Response<ResBody>, E>;
211
212    fn poll(
213        self: Pin<&mut Self>,
214        cx: &mut Context<'_>,
215    ) -> Poll<Self::Output> {
216        let this = self.project();
217        match this.inner.poll(cx) {
218            Poll::Pending => Poll::Pending,
219            Poll::Ready(Ok(response)) => {
220                emit(
221                    this.cfg,
222                    this.method,
223                    this.path,
224                    this.trace_id.as_deref(),
225                    Some(response.status().as_u16()),
226                    this.start.elapsed().as_millis() as u64,
227                );
228                Poll::Ready(Ok(response))
229            }
230            Poll::Ready(Err(err)) => {
231                emit(
232                    this.cfg,
233                    this.method,
234                    this.path,
235                    this.trace_id.as_deref(),
236                    None,
237                    this.start.elapsed().as_millis() as u64,
238                );
239                Poll::Ready(Err(err))
240            }
241        }
242    }
243}
244
245fn emit(
246    cfg: &Config,
247    method: &http::Method,
248    path: &str,
249    trace_id: Option<&str>,
250    status: Option<u16>,
251    latency_ms: u64,
252) {
253    let status_str =
254        status.map_or_else(|| "ERR".to_string(), |s| s.to_string());
255    let description = format!("{method} {path} -> {status_str}");
256    let mut log = Log::build(cfg.level, &description)
257        .component(cfg.component)
258        .format(cfg.format)
259        .with("http.method", method.as_str())
260        .with("http.path", path)
261        .with("http.latency_ms", latency_ms);
262    if let Some(s) = status {
263        log = log.with("http.status", s);
264    }
265    if let Some(t) = trace_id {
266        log = log.with("trace_id", t);
267    }
268    log.fire();
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274
275    #[test]
276    fn defaults_are_sensible() {
277        let cfg = Config::default();
278        assert_eq!(cfg.level, LogLevel::INFO);
279        assert_eq!(cfg.format, LogFormat::Logfmt);
280        assert_eq!(cfg.component, "rlg-tower");
281        assert!(cfg.trace_header.is_none());
282    }
283
284    #[test]
285    fn fluent_setters_chain() {
286        let layer = RlgLayer::new()
287            .level(LogLevel::WARN)
288            .format(LogFormat::JSON)
289            .component("api")
290            .header("traceparent");
291        assert_eq!(layer.config.level, LogLevel::WARN);
292        assert_eq!(layer.config.format, LogFormat::JSON);
293        assert_eq!(layer.config.component, "api");
294        assert_eq!(layer.config.trace_header, Some("traceparent"));
295    }
296
297    #[test]
298    fn default_constructor_matches_new() {
299        let a = RlgLayer::default();
300        let b = RlgLayer::new();
301        assert_eq!(a.config.level, b.config.level);
302        assert_eq!(a.config.format, b.config.format);
303    }
304
305    #[test]
306    fn layer_is_clone() {
307        let l1 = RlgLayer::new().component("svc");
308        let l2 = l1.clone();
309        assert_eq!(l1.config.component, l2.config.component);
310    }
311}