|
| 1 | +use std::path::Path; |
| 2 | + |
| 3 | +use anyhow::Context; |
1 | 4 | use tracing::Level; |
| 5 | +use tracing_appender::non_blocking::WorkerGuard; |
2 | 6 | use tracing_subscriber::{ |
3 | | - Layer, filter::DynFilterFn, fmt::format::FmtSpan, layer::SubscriberExt, util::SubscriberInitExt, |
| 7 | + Layer, |
| 8 | + filter::DynFilterFn, |
| 9 | + fmt::{format::FmtSpan, writer::BoxMakeWriter}, |
| 10 | + layer::SubscriberExt, |
| 11 | + util::SubscriberInitExt, |
4 | 12 | }; |
5 | 13 |
|
6 | | -pub fn init(level: u8) -> anyhow::Result<()> { |
| 14 | +pub fn init(level: u8, log_file_path: Option<&Path>) -> anyhow::Result<Option<WorkerGuard>> { |
7 | 15 | let level_t = match level { |
8 | 16 | 1 => Level::INFO, |
9 | 17 | 2 => Level::DEBUG, |
@@ -33,25 +41,36 @@ pub fn init(level: u8) -> anyhow::Result<()> { |
33 | 41 | false |
34 | 42 | }); |
35 | 43 |
|
| 44 | + let (make_writer, with_ansi, guard) = if let Some(log_file_path) = log_file_path { |
| 45 | + let file = std::fs::File::create(log_file_path) |
| 46 | + .with_context(|| format!("failed to open log file path {}", log_file_path.display()))?; |
| 47 | + let (non_blocking, guard) = tracing_appender::non_blocking(file); |
| 48 | + (BoxMakeWriter::new(non_blocking), false, Some(guard)) |
| 49 | + } else { |
| 50 | + (BoxMakeWriter::new(std::io::stderr), true, None) |
| 51 | + }; |
| 52 | + |
36 | 53 | if level >= 4 { |
37 | 54 | tracing_subscriber::registry() |
38 | 55 | .with( |
39 | 56 | tracing_subscriber::fmt::layer() |
40 | 57 | .compact() |
41 | 58 | .with_span_events(FmtSpan::CLOSE) |
42 | | - .with_writer(std::io::stderr) |
| 59 | + .with_writer(make_writer) |
| 60 | + .with_ansi(with_ansi) |
43 | 61 | .with_filter(filter), |
44 | 62 | ) |
45 | 63 | .init() |
46 | 64 | } else { |
47 | 65 | tracing_subscriber::registry() |
48 | 66 | .with( |
49 | 67 | tracing_forest::ForestLayer::from( |
50 | | - tracing_forest::printer::PrettyPrinter::new().writer(std::io::stderr), |
| 68 | + tracing_forest::printer::PrettyPrinter::new().writer(make_writer), |
51 | 69 | ) |
52 | 70 | .with_filter(filter), |
53 | 71 | ) |
54 | 72 | .init(); |
55 | 73 | } |
56 | | - Ok(()) |
| 74 | + |
| 75 | + Ok(guard) |
57 | 76 | } |
0 commit comments