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
#![forbid(unsafe_code)]
#![warn(
    rustdoc::missing_crate_level_docs,
    missing_docs,
    nonstandard_style,
    unused_qualifications
)]

/*!
Welcome to the trillium logger!
*/
pub use crate::formatters::{apache_combined, apache_common, dev_formatter};
use is_terminal::IsTerminal;
use std::{fmt::Display, sync::Arc};
use trillium::{async_trait, Conn, Handler, Info};
/**
Components with which common log formats can be constructed
*/
pub mod formatters;

/**
A configuration option that determines if format will be colorful.

The default is [`ColorMode::Auto`], which only enables color if stdout
is detected to be a shell terminal (tty). If this detection is
incorrect, you can explicitly set it to [`ColorMode::On`] or
[`ColorMode::Off`]

**Note**: The actual colorization of output is determined by the log
formatters, so it is possible for this to be correctly enabled but for
the output to have no colored components.
*/

#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub enum ColorMode {
    /// detect if stdout is a tty
    Auto,
    /// always enable colorful output
    On,
    /// alwasy disable colorful output
    Off,
}

impl ColorMode {
    pub(crate) fn is_enabled(&self) -> bool {
        match self {
            ColorMode::Auto => std::io::stdout().is_terminal(),
            ColorMode::On => true,
            ColorMode::Off => false,
        }
    }
}

impl Default for ColorMode {
    fn default() -> Self {
        Self::Auto
    }
}

/**
Specifies where the logger output should be sent

The default is [`Target::Stdout`].
*/
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub enum Target {
    /**
    Send trillium logger output to a log crate backend. See
    [`log`] for output options
    */
    Logger(log::Level),

    /**
    Send trillium logger output to stdout
    */
    Stdout,
}

/// A trait for log targets. Implemented for [`Target`] and for all
/// `Fn(String) + Send + Sync + 'static`.
pub trait Targetable: Send + Sync + 'static {
    /// write a log line
    fn write(&self, data: String);
}

impl Targetable for Target {
    fn write(&self, data: String) {
        match self {
            Target::Logger(level) => {
                log::log!(*level, "{}", data);
            }

            Target::Stdout => {
                println!("{data}");
            }
        }
    }
}

impl<F> Targetable for F
where
    F: Fn(String) + Send + Sync + 'static,
{
    fn write(&self, data: String) {
        self(data);
    }
}

impl Default for Target {
    fn default() -> Self {
        Self::Stdout
    }
}

/**
The interface to format a &[`Conn`] as a [`Display`]-able output

In general, the included loggers provide a mechanism for composing
these, so top level formats like [`dev_formatter`], [`apache_common`]
and [`apache_combined`] are composed in terms of component formatters
like [`formatters::method`], [`formatters::ip`],
[`formatters::timestamp`], and many others (see [`formatters`] for a
full list)

When implementing this trait, note that [`Display::fmt`] is called on
[`LogFormatter::Output`] _after_ the response has been fully sent, but
that the [`LogFormatter::format`] is called _before_ the response has
been sent. If you need to perform timing-sensitive calculations that
represent the full http cycle, move whatever data is needed to make
the calculation into a new type that implements Display, ensuring that
it is calculated at the right time.


## Implementations

### Tuples

LogFormatter is implemented for all tuples of other LogFormatter
types, from 2-26 formatters long. The output of these formatters is
concatenated with no space between.

### `&'static str`

LogFormatter is implemented for &'static str, allowing for
interspersing spaces and other static formatting details into tuples.

```rust
use trillium_logger::{Logger, formatters};
let handler = Logger::new()
    .with_formatter(("-> ", formatters::method, " ", formatters::url));
```

### `Fn(&Conn, bool) -> impl Display`

LogFormatter is implemented for all functions that conform to this signature.

```rust
# use trillium_logger::{Logger, dev_formatter};
# use trillium::Conn;
# use std::borrow::Cow;
# struct User(String); impl User { fn name(&self) -> &str { &self.0 } }
fn user(conn: &Conn, color: bool) -> Cow<'static, str> {
     match conn.state::<User>() {
        Some(user) => String::from(user.name()).into(),
        None => "guest".into()
    }
}

let handler = Logger::new().with_formatter((dev_formatter, " ", user));
```
*/
pub trait LogFormatter: Send + Sync + 'static {
    /**
    The display type for this formatter

    For a simple formatter, this will likely be a String, or even
    better, a lightweight type that implements Display.
    */
    type Output: Display + Send + Sync + 'static;

    /**
    Extract Output from this Conn
     */
    fn format(&self, conn: &Conn, color: bool) -> Self::Output;
}

/**
The trillium handler for this crate, and the core type
*/
pub struct Logger<F> {
    format: F,
    color_mode: ColorMode,
    target: Arc<dyn Targetable>,
}

impl Logger<()> {
    /**
    Builds a new logger

    Defaults:

    * formatter: [`dev_formatter`]
    * color mode: [`ColorMode::Auto`]
    * target: [`Target::Stdout`]
    */
    pub fn new() -> Logger<impl LogFormatter> {
        Logger {
            format: dev_formatter,
            color_mode: ColorMode::Auto,
            target: Arc::new(Target::Stdout),
        }
    }
}

impl<T> Logger<T> {
    /**
    replace the formatter with any type that implements [`LogFormatter`]

    see the trait documentation for [`LogFormatter`] for more details. note that this can be chained
    with [`Logger::with_target`] and [`Logger::with_color_mode`]

    ```
    use trillium_logger::{Logger, apache_common};
    Logger::new().with_formatter(apache_common("-", "-"));
    ```
    */
    pub fn with_formatter<Formatter: LogFormatter>(
        self,
        formatter: Formatter,
    ) -> Logger<Formatter> {
        Logger {
            format: formatter,
            color_mode: self.color_mode,
            target: self.target,
        }
    }
}

impl<F: LogFormatter> Logger<F> {
    /**
    specify the color mode for this logger.

    see [`ColorMode`] for more details. note that this can be chained
    with [`Logger::with_target`] and [`Logger::with_formatter`]
    ```
    use trillium_logger::{Logger, ColorMode};
    Logger::new().with_color_mode(ColorMode::On);
    ```
    */
    pub fn with_color_mode(mut self, color_mode: ColorMode) -> Self {
        self.color_mode = color_mode;
        self
    }

    /**
    specify the logger target

    see [`Target`] for more details. note that this can be chained
    with [`Logger::with_color_mode`] and [`Logger::with_formatter`]

    ```
    use trillium_logger::{Logger, Target};
    Logger::new().with_target(Target::Logger(log::Level::Info));
    ```
    */
    pub fn with_target(mut self, target: impl Targetable) -> Self {
        self.target = Arc::new(target);
        self
    }
}

struct LoggerWasRun;

#[async_trait]
impl<F> Handler for Logger<F>
where
    F: LogFormatter,
{
    async fn init(&mut self, info: &mut Info) {
        self.target.write(format!(
            "
🌱🦀🌱 {} started
Listening at {}{}

Control-C to quit",
            info.server_description(),
            info.listener_description(),
            info.tcp_socket_addr()
                .map(|s| format!(" (bound as tcp://{s})"))
                .unwrap_or_default(),
        ));
    }
    async fn run(&self, conn: Conn) -> Conn {
        conn.with_state(LoggerWasRun)
    }

    async fn before_send(&self, mut conn: Conn) -> Conn {
        if conn.state::<LoggerWasRun>().is_some() {
            let target = self.target.clone();
            let output = self.format.format(&conn, self.color_mode.is_enabled());
            conn.inner_mut()
                .after_send(move |_| target.write(output.to_string()));
        }

        conn
    }
}

/// Convenience alias for [`Logger::new`]
pub fn logger() -> Logger<impl LogFormatter> {
    Logger::new()
}