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
use std::{fs::File, io};

use tracing_appender::{
    non_blocking::{NonBlocking, NonBlockingBuilder, WorkerGuard},
    rolling::{RollingFileAppender, RollingWriter},
};

/// A thread guard in the case of [`NonBlocking`](crate::NonBlocking) config.
///
/// See [`WorkerGuard`] for more.
pub struct Guard(Option<GuardInner>);

/// Implementor of [`tracing_subscriber::fmt::MakeWriter`],
/// constructed from [`Writer`](crate::Writer) in [`Self::new`].
pub struct MakeWriter(MakeWriterInner);

/// Implementor of [`io::Write`], used by [`MakeWriter`].
pub struct Writer<'a>(WriterInner<'a>);

/// Error that can occur when constructing a writer, including e.g [`File`]-opening errors.
#[derive(Debug, thiserror::Error)]
#[error("{}: {}", .context, .source)]
pub struct Error {
    context: String,
    #[source]
    source: ErrorInner,
}

impl MakeWriter {
    pub fn new(writer: crate::Writer) -> Result<(Self, Guard), Error> {
        MakeWriterInner::new(writer).map(|(l, r)| (Self(l), Guard(r)))
    }
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for MakeWriter {
    type Writer = Writer<'a>;

    fn make_writer(&'a self) -> Self::Writer {
        Writer(self.0.make_writer())
    }
}

impl io::Write for Writer<'_> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.0.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.0.flush()
    }
}

impl crate::NonBlocking {
    fn build<T: io::Write + Send + 'static>(
        &self,
        writer: T,
    ) -> (tracing_appender::non_blocking::NonBlocking, WorkerGuard) {
        let Self {
            buffer_length,
            behaviour,
        } = self;
        let mut builder = NonBlockingBuilder::default();
        if let Some(it) = buffer_length {
            builder = builder.buffered_lines_limit(*it)
        }
        let builder = match behaviour {
            Some(crate::BackpressureBehaviour::Block) => builder.lossy(false),
            Some(crate::BackpressureBehaviour::Drop) => builder.lossy(true),
            None => builder,
        };
        builder.finish(writer)
    }
}

impl MakeWriterInner {
    fn new(writer: crate::Writer) -> Result<(Self, Option<GuardInner>), Error> {
        match writer {
            crate::Writer::File {
                path,
                behaviour,
                non_blocking,
            } => {
                match match behaviour {
                    crate::FileOpenBehaviour::Truncate => File::create(&path),
                    crate::FileOpenBehaviour::Append => File::options().append(true).open(&path),
                } {
                    Ok(it) => match non_blocking {
                        Some(nb) => {
                            let (nb, g) = nb.build(it);
                            Ok((Self::NonBlocking(nb), Some(GuardInner::NonBlocking(g))))
                        }
                        None => Ok((Self::File(it), None)),
                    },
                    Err(e) => Err(Error {
                        context: format!("Couldn't open log file {}", path.display()),
                        source: ErrorInner::Io(e),
                    }),
                }
            }
            crate::Writer::Rolling {
                directory,
                rolling,
                non_blocking,
            } => {
                let crate::Rolling {
                    limit,
                    prefix,
                    suffix,
                    rotation,
                } = rolling.unwrap_or_default();
                let mut builder = RollingFileAppender::builder();
                if let Some(limit) = limit {
                    builder = builder.max_log_files(limit)
                }
                if let Some(prefix) = prefix {
                    builder = builder.filename_prefix(prefix)
                }
                if let Some(suffix) = suffix {
                    builder = builder.filename_suffix(suffix)
                }
                let builder = match rotation.unwrap_or_default() {
                    crate::Rotation::Minutely => {
                        builder.rotation(tracing_appender::rolling::Rotation::MINUTELY)
                    }
                    crate::Rotation::Hourly => {
                        builder.rotation(tracing_appender::rolling::Rotation::HOURLY)
                    }
                    crate::Rotation::Daily => {
                        builder.rotation(tracing_appender::rolling::Rotation::DAILY)
                    }
                    crate::Rotation::Never => {
                        builder.rotation(tracing_appender::rolling::Rotation::NEVER)
                    }
                };

                match builder.build(&directory) {
                    Ok(it) => match non_blocking {
                        Some(nb) => {
                            let (nb, g) = nb.build(it);
                            Ok((Self::NonBlocking(nb), Some(GuardInner::NonBlocking(g))))
                        }
                        None => Ok((Self::Rolling(it), None)),
                    },
                    Err(e) => Err(Error {
                        context: format!(
                            "Couldn't start rolling logging in directory {}",
                            directory.display()
                        ),
                        source: ErrorInner::Init(e),
                    }),
                }
            }
            crate::Writer::Stdout => Ok((Self::Stdout(io::stdout()), None)),
            crate::Writer::Stderr => Ok((Self::Stderr(io::stderr()), None)),
            crate::Writer::Null => Ok((Self::Null(io::sink()), None)),
        }
    }
}

#[derive(Debug, thiserror::Error)]
#[error(transparent)]
enum ErrorInner {
    Io(io::Error),
    Init(tracing_appender::rolling::InitError),
}

enum GuardInner {
    NonBlocking(WorkerGuard),
}

enum MakeWriterInner {
    Null(io::Sink),
    NonBlocking(tracing_appender::non_blocking::NonBlocking),
    Stdout(io::Stdout),
    Stderr(io::Stderr),
    File(File),
    Rolling(RollingFileAppender),
}

enum WriterInner<'a> {
    Null(&'a io::Sink),
    NonBlocking(NonBlocking),
    Stdout(&'a io::Stdout),
    Stderr(&'a io::Stderr),
    File(&'a File),
    Rolling(RollingWriter<'a>),
}

impl io::Write for WriterInner<'_> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match self {
            WriterInner::NonBlocking(it) => it.write(buf),
            WriterInner::Stdout(it) => it.write(buf),
            WriterInner::Stderr(it) => it.write(buf),
            WriterInner::File(it) => it.write(buf),
            WriterInner::Rolling(it) => it.write(buf),
            WriterInner::Null(it) => it.write(buf),
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        match self {
            WriterInner::NonBlocking(it) => it.flush(),
            WriterInner::Stdout(it) => it.flush(),
            WriterInner::Stderr(it) => it.flush(),
            WriterInner::File(it) => it.flush(),
            WriterInner::Rolling(it) => it.flush(),
            WriterInner::Null(it) => it.flush(),
        }
    }
}

impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for MakeWriterInner {
    type Writer = WriterInner<'a>;

    fn make_writer(&'a self) -> Self::Writer {
        match self {
            MakeWriterInner::NonBlocking(it) => Self::Writer::NonBlocking(it.make_writer()),
            MakeWriterInner::Stdout(it) => Self::Writer::Stdout(it),
            MakeWriterInner::Stderr(it) => Self::Writer::Stderr(it),
            MakeWriterInner::File(it) => Self::Writer::File(it.make_writer()),
            MakeWriterInner::Rolling(it) => Self::Writer::Rolling(it.make_writer()),
            MakeWriterInner::Null(it) => Self::Writer::Null(it),
        }
    }
}