Skip to content

Commit

Permalink
appender: allow worker thread name to be configured (tokio-rs#2364)
Browse files Browse the repository at this point in the history
The worker thread name in non blocking mode is always "tracing-appender".
It can be convenient to quickly identify the appender threads for
audit reasons or affinity pinning.

This patch adds a new setter to the builder and propagates the info to
the thread initialization.
  • Loading branch information
nstinus committed Nov 3, 2022
1 parent 3258a2b commit 86bcfa7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
25 changes: 22 additions & 3 deletions tracing-appender/src/non_blocking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,14 +154,18 @@ impl NonBlocking {
writer: T,
buffered_lines_limit: usize,
is_lossy: bool,
thread_name: String,
) -> (NonBlocking, WorkerGuard) {
let (sender, receiver) = bounded(buffered_lines_limit);

let (shutdown_sender, shutdown_receiver) = bounded(0);

let worker = Worker::new(receiver, writer, shutdown_receiver);
let worker_guard =
WorkerGuard::new(worker.worker_thread(), sender.clone(), shutdown_sender);
let worker_guard = WorkerGuard::new(
worker.worker_thread(thread_name),
sender.clone(),
shutdown_sender,
);

(
Self {
Expand All @@ -187,6 +191,7 @@ impl NonBlocking {
pub struct NonBlockingBuilder {
buffered_lines_limit: usize,
is_lossy: bool,
thread_name: String,
}

impl NonBlockingBuilder {
Expand All @@ -207,9 +212,22 @@ impl NonBlockingBuilder {
self
}

/// Override the worker thread's name.
///
/// The default worker thread name is "tracing-appender".
pub fn thread_name(mut self, name: &str) -> NonBlockingBuilder {
self.thread_name = name.to_string();
self
}

/// Completes the builder, returning the configured `NonBlocking`.
pub fn finish<T: Write + Send + Sync + 'static>(self, writer: T) -> (NonBlocking, WorkerGuard) {
NonBlocking::create(writer, self.buffered_lines_limit, self.is_lossy)
NonBlocking::create(
writer,
self.buffered_lines_limit,
self.is_lossy,
self.thread_name,
)
}
}

Expand All @@ -218,6 +236,7 @@ impl Default for NonBlockingBuilder {
NonBlockingBuilder {
buffered_lines_limit: DEFAULT_BUFFERED_LINES_LIMIT,
is_lossy: true,
thread_name: "tracing-appender".to_string(),
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions tracing-appender/src/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ impl<T: Write + Send + Sync + 'static> Worker<T> {
}

/// Creates a worker thread that processes a channel until it's disconnected
pub(crate) fn worker_thread(mut self) -> std::thread::JoinHandle<()> {
pub(crate) fn worker_thread(mut self, name: String) -> std::thread::JoinHandle<()> {
thread::Builder::new()
.name("tracing-appender".to_string())
.name(name)
.spawn(move || {
loop {
match self.work() {
Expand Down

0 comments on commit 86bcfa7

Please sign in to comment.