tracing_appender/non_blocking.rs
1//! A non-blocking, off-thread writer.
2//!
3//! This spawns a dedicated worker thread which is responsible for writing log
4//! lines to the provided writer. When a line is written using the returned
5//! `NonBlocking` struct's `make_writer` method, it will be enqueued to be
6//! written by the worker thread.
7//!
8//! The queue has a fixed capacity, and if it becomes full, any logs written
9//! to it will be dropped until capacity is once again available. This may
10//! occur if logs are consistently produced faster than the worker thread can
11//! output them. The queue capacity and behavior when full (i.e., whether to
12//! drop logs or to exert backpressure to slow down senders) can be configured
13//! using [`NonBlockingBuilder::default()`][builder].
14//! This function returns the default configuration. It is equivalent to:
15//!
16//! ```rust
17//! # use tracing_appender::non_blocking::{NonBlocking, WorkerGuard};
18//! # fn doc() -> (NonBlocking, WorkerGuard) {
19//! tracing_appender::non_blocking(std::io::stdout())
20//! # }
21//! ```
22//! [builder]: NonBlockingBuilder::default
23//!
24//! <br/> This function returns a tuple of `NonBlocking` and `WorkerGuard`.
25//! `NonBlocking` implements [`MakeWriter`] which integrates with `tracing_subscriber`.
26//! `WorkerGuard` is a drop guard that is responsible for flushing any remaining logs when
27//! the program terminates.
28//!
29//! Note that the `WorkerGuard` returned by `non_blocking` _must_ be assigned to a binding that
30//! is not `_`, as `_` will result in the `WorkerGuard` being dropped immediately.
31//! Unintentional drops of `WorkerGuard` remove the guarantee that logs will be flushed
32//! during a program's termination, in a panic or otherwise.
33//!
34//! See [`WorkerGuard`] for examples of using the guard.
35//!
36//! # Examples
37//!
38//! ``` rust
39//! # fn docs() {
40//! let (non_blocking, _guard) = tracing_appender::non_blocking(std::io::stdout());
41//! let subscriber = tracing_subscriber::fmt().with_writer(non_blocking);
42//! tracing::subscriber::with_default(subscriber.finish(), || {
43//! tracing::event!(tracing::Level::INFO, "Hello");
44//! });
45//! # }
46//! ```
47use crate::worker::Worker;
48use crate::Msg;
49use crossbeam_channel::{bounded, SendTimeoutError, Sender};
50use std::io;
51use std::io::Write;
52use std::sync::atomic::AtomicUsize;
53use std::sync::atomic::Ordering;
54use std::sync::Arc;
55use std::thread::JoinHandle;
56use std::time::Duration;
57use tracing_subscriber::fmt::MakeWriter;
58
59/// The default maximum number of buffered log lines.
60///
61/// If [`NonBlocking`] is lossy, it will drop spans/events at capacity.
62/// If [`NonBlocking`] is _not_ lossy, backpressure will be exerted on
63/// senders, causing them to block their respective threads until there
64/// is available capacity.
65///
66/// Recommended to be a power of 2.
67pub const DEFAULT_BUFFERED_LINES_LIMIT: usize = 128_000;
68
69/// A guard that flushes spans/events associated to a [`NonBlocking`] on a drop
70///
71/// Writing to a [`NonBlocking`] writer will **not** immediately write a span or event to the underlying
72/// output. Instead, the span or event will be written by a dedicated logging thread at some later point.
73/// To increase throughput, the non-blocking writer will flush to the underlying output on
74/// a periodic basis rather than every time a span or event is written. This means that if the program
75/// terminates abruptly (such as through an uncaught `panic` or a `std::process::exit`), some spans
76/// or events may not be written.
77///
78/// Since spans/events and events recorded near a crash are often necessary for diagnosing the failure,
79/// `WorkerGuard` provides a mechanism to ensure that _all_ buffered logs are flushed to their output.
80/// `WorkerGuard` should be assigned in the `main` function or whatever the entrypoint of the program is.
81/// This will ensure that the guard will be dropped during an unwinding or when `main` exits
82/// successfully.
83///
84/// # Examples
85///
86/// ``` rust
87/// # #[clippy::allow(needless_doctest_main)]
88/// fn main () {
89/// # fn doc() {
90/// let (non_blocking, _guard) = tracing_appender::non_blocking(std::io::stdout());
91/// let subscriber = tracing_subscriber::fmt().with_writer(non_blocking);
92/// tracing::subscriber::with_default(subscriber.finish(), || {
93/// // Emit some tracing events within context of the non_blocking `_guard` and tracing subscriber
94/// tracing::event!(tracing::Level::INFO, "Hello");
95/// });
96/// // Exiting the context of `main` will drop the `_guard` and any remaining logs should get flushed
97/// # }
98/// }
99/// ```
100#[must_use]
101#[derive(Debug)]
102pub struct WorkerGuard {
103 _guard: Option<JoinHandle<()>>,
104 sender: Sender<Msg>,
105 shutdown: Sender<()>,
106}
107
108/// A non-blocking writer.
109///
110/// While the line between "blocking" and "non-blocking" IO is fuzzy, writing to a file is typically
111/// considered to be a _blocking_ operation. For an application whose `Subscriber` writes spans and events
112/// as they are emitted, an application might find the latency profile to be unacceptable.
113/// `NonBlocking` moves the writing out of an application's data path by sending spans and events
114/// to a dedicated logging thread.
115///
116/// This struct implements [`MakeWriter`] from the `tracing-subscriber`
117/// crate. Therefore, it can be used with the [`tracing_subscriber::fmt`][fmt] module
118/// or with any other subscriber/layer implementation that uses the `MakeWriter` trait.
119///
120/// [fmt]: mod@tracing_subscriber::fmt
121#[derive(Clone, Debug)]
122pub struct NonBlocking {
123 error_counter: ErrorCounter,
124 channel: Sender<Msg>,
125 is_lossy: bool,
126}
127
128/// Tracks the number of times a log line was dropped by the background thread.
129///
130/// If the non-blocking writer is not configured in [lossy mode], the error
131/// count should always be 0.
132///
133/// [lossy mode]: NonBlockingBuilder::lossy
134#[derive(Clone, Debug)]
135pub struct ErrorCounter(Arc<AtomicUsize>);
136
137impl NonBlocking {
138 /// Returns a new `NonBlocking` writer wrapping the provided `writer`.
139 ///
140 /// The returned `NonBlocking` writer will have the [default configuration][default] values.
141 /// Other configurations can be specified using the [builder] interface.
142 ///
143 /// [default]: NonBlockingBuilder::default
144 /// [builder]: NonBlockingBuilder
145 pub fn new<T: Write + Send + 'static>(writer: T) -> (NonBlocking, WorkerGuard) {
146 NonBlockingBuilder::default().finish(writer)
147 }
148
149 fn create<T: Write + Send + 'static>(
150 writer: T,
151 buffered_lines_limit: usize,
152 is_lossy: bool,
153 thread_name: String,
154 ) -> (NonBlocking, WorkerGuard) {
155 let (sender, receiver) = bounded(buffered_lines_limit);
156
157 let (shutdown_sender, shutdown_receiver) = bounded(0);
158
159 let worker = Worker::new(receiver, writer, shutdown_receiver);
160 let worker_guard = WorkerGuard::new(
161 worker.worker_thread(thread_name),
162 sender.clone(),
163 shutdown_sender,
164 );
165
166 (
167 Self {
168 channel: sender,
169 error_counter: ErrorCounter(Arc::new(AtomicUsize::new(0))),
170 is_lossy,
171 },
172 worker_guard,
173 )
174 }
175
176 /// Returns a counter for the number of times logs where dropped. This will always return zero if
177 /// `NonBlocking` is not lossy.
178 pub fn error_counter(&self) -> ErrorCounter {
179 self.error_counter.clone()
180 }
181}
182
183/// A builder for [`NonBlocking`].
184#[derive(Debug)]
185pub struct NonBlockingBuilder {
186 buffered_lines_limit: usize,
187 is_lossy: bool,
188 thread_name: String,
189}
190
191impl NonBlockingBuilder {
192 /// Sets the number of lines to buffer before dropping logs or exerting backpressure on senders
193 pub fn buffered_lines_limit(mut self, buffered_lines_limit: usize) -> NonBlockingBuilder {
194 self.buffered_lines_limit = buffered_lines_limit;
195 self
196 }
197
198 /// Sets whether `NonBlocking` should be lossy or not.
199 ///
200 /// If set to `true`, logs will be dropped when the buffered limit is reached. If `false`, backpressure
201 /// will be exerted on senders, blocking them until the buffer has capacity again.
202 ///
203 /// By default, the built `NonBlocking` will be lossy.
204 pub fn lossy(mut self, is_lossy: bool) -> NonBlockingBuilder {
205 self.is_lossy = is_lossy;
206 self
207 }
208
209 /// Override the worker thread's name.
210 ///
211 /// The default worker thread name is "tracing-appender".
212 pub fn thread_name(mut self, name: &str) -> NonBlockingBuilder {
213 self.thread_name = name.to_string();
214 self
215 }
216
217 /// Completes the builder, returning the configured `NonBlocking`.
218 pub fn finish<T: Write + Send + 'static>(self, writer: T) -> (NonBlocking, WorkerGuard) {
219 NonBlocking::create(
220 writer,
221 self.buffered_lines_limit,
222 self.is_lossy,
223 self.thread_name,
224 )
225 }
226}
227
228impl Default for NonBlockingBuilder {
229 fn default() -> Self {
230 NonBlockingBuilder {
231 buffered_lines_limit: DEFAULT_BUFFERED_LINES_LIMIT,
232 is_lossy: true,
233 thread_name: "tracing-appender".to_string(),
234 }
235 }
236}
237
238impl std::io::Write for NonBlocking {
239 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
240 let buf_size = buf.len();
241 if self.is_lossy {
242 if self.channel.try_send(Msg::Line(buf.to_vec())).is_err() {
243 self.error_counter.incr_saturating();
244 }
245 } else {
246 return match self.channel.send(Msg::Line(buf.to_vec())) {
247 Ok(_) => Ok(buf_size),
248 Err(_) => Err(io::Error::from(io::ErrorKind::Other)),
249 };
250 }
251 Ok(buf_size)
252 }
253
254 fn flush(&mut self) -> io::Result<()> {
255 Ok(())
256 }
257
258 #[inline]
259 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
260 self.write(buf).map(|_| ())
261 }
262}
263
264impl<'a> MakeWriter<'a> for NonBlocking {
265 type Writer = NonBlocking;
266
267 fn make_writer(&'a self) -> Self::Writer {
268 self.clone()
269 }
270}
271
272impl WorkerGuard {
273 fn new(handle: JoinHandle<()>, sender: Sender<Msg>, shutdown: Sender<()>) -> Self {
274 WorkerGuard {
275 _guard: Some(handle),
276 sender,
277 shutdown,
278 }
279 }
280}
281
282impl Drop for WorkerGuard {
283 fn drop(&mut self) {
284 match self
285 .sender
286 .send_timeout(Msg::Shutdown, Duration::from_millis(100))
287 {
288 Ok(_) => {
289 // Attempt to wait for `Worker` to flush all messages before dropping. This happens
290 // when the `Worker` calls `recv()` on a zero-capacity channel. Use `send_timeout`
291 // so that drop is not blocked indefinitely.
292 // TODO: Make timeout configurable.
293 let _ = self.shutdown.send_timeout((), Duration::from_millis(1000));
294 }
295 Err(SendTimeoutError::Disconnected(_)) => (),
296 Err(SendTimeoutError::Timeout(e)) => println!(
297 "Failed to send shutdown signal to logging worker. Error: {:?}",
298 e
299 ),
300 }
301 }
302}
303
304// === impl ErrorCounter ===
305
306impl ErrorCounter {
307 /// Returns the number of log lines that have been dropped.
308 ///
309 /// If the non-blocking writer is not configured in [lossy mode], the error
310 /// count should always be 0.
311 ///
312 /// [lossy mode]: NonBlockingBuilder::lossy
313 pub fn dropped_lines(&self) -> usize {
314 self.0.load(Ordering::Acquire)
315 }
316
317 fn incr_saturating(&self) {
318 let mut curr = self.0.load(Ordering::Acquire);
319 // We don't need to enter the CAS loop if the current value is already
320 // `usize::MAX`.
321 if curr == usize::MAX {
322 return;
323 }
324
325 // This is implemented as a CAS loop rather than as a simple
326 // `fetch_add`, because we don't want to wrap on overflow. Instead, we
327 // need to ensure that saturating addition is performed.
328 loop {
329 let val = curr.saturating_add(1);
330 match self
331 .0
332 .compare_exchange(curr, val, Ordering::AcqRel, Ordering::Acquire)
333 {
334 Ok(_) => return,
335 Err(actual) => curr = actual,
336 }
337 }
338 }
339}
340
341#[cfg(test)]
342mod test {
343 use super::*;
344 use std::sync::mpsc;
345 use std::thread;
346 use std::time::Duration;
347
348 struct MockWriter {
349 tx: mpsc::SyncSender<String>,
350 }
351
352 impl MockWriter {
353 fn new(capacity: usize) -> (Self, mpsc::Receiver<String>) {
354 let (tx, rx) = mpsc::sync_channel(capacity);
355 (Self { tx }, rx)
356 }
357 }
358
359 impl std::io::Write for MockWriter {
360 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
361 let buf_len = buf.len();
362 let _ = self.tx.send(String::from_utf8_lossy(buf).to_string());
363 Ok(buf_len)
364 }
365
366 fn flush(&mut self) -> std::io::Result<()> {
367 Ok(())
368 }
369 }
370
371 #[test]
372 fn backpressure_exerted() {
373 let (mock_writer, rx) = MockWriter::new(1);
374
375 let (mut non_blocking, _guard) = self::NonBlockingBuilder::default()
376 .lossy(false)
377 .buffered_lines_limit(1)
378 .finish(mock_writer);
379
380 let error_count = non_blocking.error_counter();
381
382 non_blocking.write_all(b"Hello").expect("Failed to write");
383 assert_eq!(0, error_count.dropped_lines());
384
385 let handle = thread::spawn(move || {
386 non_blocking.write_all(b", World").expect("Failed to write");
387 });
388
389 // Sleep a little to ensure previously spawned thread gets blocked on write.
390 thread::sleep(Duration::from_millis(100));
391 // We should not drop logs when blocked.
392 assert_eq!(0, error_count.dropped_lines());
393
394 // Read the first message to unblock sender.
395 let mut line = rx.recv().unwrap();
396 assert_eq!(line, "Hello");
397
398 // Wait for thread to finish.
399 handle.join().expect("thread should not panic");
400
401 // Thread has joined, we should be able to read the message it sent.
402 line = rx.recv().unwrap();
403 assert_eq!(line, ", World");
404 }
405
406 fn write_non_blocking(non_blocking: &mut NonBlocking, msg: &[u8]) {
407 non_blocking.write_all(msg).expect("Failed to write");
408
409 // Sleep a bit to prevent races.
410 thread::sleep(Duration::from_millis(200));
411 }
412
413 #[test]
414 #[ignore] // flaky, see https://github.com/tokio-rs/tracing/issues/751
415 fn logs_dropped_if_lossy() {
416 let (mock_writer, rx) = MockWriter::new(1);
417
418 let (mut non_blocking, _guard) = self::NonBlockingBuilder::default()
419 .lossy(true)
420 .buffered_lines_limit(1)
421 .finish(mock_writer);
422
423 let error_count = non_blocking.error_counter();
424
425 // First write will not block
426 write_non_blocking(&mut non_blocking, b"Hello");
427 assert_eq!(0, error_count.dropped_lines());
428
429 // Second write will not block as Worker will have called `recv` on channel.
430 // "Hello" is not yet consumed. MockWriter call to write_all will block until
431 // "Hello" is consumed.
432 write_non_blocking(&mut non_blocking, b", World");
433 assert_eq!(0, error_count.dropped_lines());
434
435 // Will sit in NonBlocking channel's buffer.
436 write_non_blocking(&mut non_blocking, b"Test");
437 assert_eq!(0, error_count.dropped_lines());
438
439 // Allow a line to be written. "Hello" message will be consumed.
440 // ", World" will be able to write to MockWriter.
441 // "Test" will block on call to MockWriter's `write_all`
442 let line = rx.recv().unwrap();
443 assert_eq!(line, "Hello");
444
445 // This will block as NonBlocking channel is full.
446 write_non_blocking(&mut non_blocking, b"Universe");
447 assert_eq!(1, error_count.dropped_lines());
448
449 // Finally the second message sent will be consumed.
450 let line = rx.recv().unwrap();
451 assert_eq!(line, ", World");
452 assert_eq!(1, error_count.dropped_lines());
453 }
454
455 #[test]
456 fn multi_threaded_writes() {
457 let (mock_writer, rx) = MockWriter::new(DEFAULT_BUFFERED_LINES_LIMIT);
458
459 let (non_blocking, _guard) = self::NonBlockingBuilder::default()
460 .lossy(true)
461 .finish(mock_writer);
462
463 let error_count = non_blocking.error_counter();
464 let mut join_handles: Vec<JoinHandle<()>> = Vec::with_capacity(10);
465
466 for _ in 0..10 {
467 let cloned_non_blocking = non_blocking.clone();
468 join_handles.push(thread::spawn(move || {
469 let subscriber = tracing_subscriber::fmt().with_writer(cloned_non_blocking);
470 tracing::subscriber::with_default(subscriber.finish(), || {
471 tracing::event!(tracing::Level::INFO, "Hello");
472 });
473 }));
474 }
475
476 for handle in join_handles {
477 handle.join().expect("Failed to join thread");
478 }
479
480 let mut hello_count: u8 = 0;
481
482 while let Ok(event_str) = rx.recv_timeout(Duration::from_secs(5)) {
483 assert!(event_str.contains("Hello"));
484 hello_count += 1;
485 }
486
487 assert_eq!(10, hello_count);
488 assert_eq!(0, error_count.dropped_lines());
489 }
490}