captains_log/lib.rs
1//! # captains-log
2//!
3//! A light-weight logger for rust, implementation base on the crate `log`.
4//!
5//! ## Features
6//!
7//! * Allow customize log format and time format. Refer to [LogFormat].
8//!
9//! * Supports multiple types of sink stacking, each with its own log level.
10//!
11//! + [Builder::console()] : Console output to stdout/stderr.
12//!
13//! + [Builder::raw_file()] : Support atomic appending from multi-process on linux
14//!
15//! + [Builder::buf_file()] : Write to log file with merged I/O and delay flush, and optional self-rotation.
16//!
17//! * Log panic message by default.
18//!
19//! * Provide additional [macros](#macros)
20//!
21//! * Supports signal listening for log-rotate. Refer to [Builder::signal()]
22//!
23//! * Provides many preset recipes in [recipe] module for convenience.
24//!
25//! * [Supports configure by environment](#configure-by-environment)
26//!
27//! * [Fine-grain module-level control](#fine-grain-module-level-control)
28//!
29//! * [API-level log handling](#api-level-log-handling)
30//!
31//! * For test suits usage:
32//!
33//! + Allow dynamic reconfigure logger setting in different test function.
34//!
35//! Refer to [Unit test example](#unit-test-example).
36//!
37//! + Provides an attribute macro #\[logfn\] to wrap test function.
38//!
39//! Refer to [Best practice][#best-practice-with-tests].
40//!
41//! * Provides a [LogParser](crate::parser::LogParser) to work on your log files.
42//!
43//! ## Usage
44//!
45//! Cargo.toml
46//!
47//! ``` toml
48//! [dependencies]
49//! log = { version = "0.4", features = ["std", "kv_unstable"] }
50//! captains_log = "0.6"
51//! ```
52//!
53//! lib.rs or main.rs:
54//!
55//! ``` rust
56//!
57//! // By default, reexport the macros from log crate
58//! #[macro_use]
59//! extern crate captains_log;
60//!
61//! ```
62//!
63//! ## Fast setup examples
64//!
65//! You can refer to various preset recipe in [recipe] module.
66//!
67//! The following is setup two log files for different log-level:
68//!
69//! ``` rust
70//! #[macro_use]
71//! extern crate captains_log;
72//! use captains_log::recipe;
73//!
74//! // You'll get /tmp/test.log with all logs, and /tmp/test.log.wf only with error logs.
75//! let log_builder = recipe::split_error_file_logger("/tmp", "test", log::Level::Debug);
76//! // Builder::build() is equivalent of setup_log().
77//! log_builder.build();
78//! // non-error msg will only appear in /tmp/test.log
79//! debug!("Set a course to Sol system");
80//! info!("Engage");
81//! // will appear in both /tmp/test.log and /tmp/test.log.wf
82//! error!("Engine over heat!");
83//! ```
84//!
85//! Buffered sink with log rotation (See the definition of [Rotation]):
86//!
87//! ``` rust
88//! #[macro_use]
89//! extern crate captains_log;
90//! use captains_log::*;
91//! // rotate when log file reaches 512M. Keep max 10 archiveed files, with recent 2 not compressed.
92//! // All archived log is moved to "/tmp/rotation/old"
93//! let rotation = Rotation::by_size(
94//! 512 * 1024 * 1024, Some(10)).compress_exclude(2).archive_dir("/tmp/rotation/old");
95//! let _ = recipe::buffered_rotated_file_logger("/tmp/rotation.log", Level::Debug, rotation).build();
96//! ```
97//!
98//! ## Configure by environment
99//!
100//! There is a recipe [env_logger()](crate::recipe::env_logger()) to configure a file logger or
101//! console logger from env. As simple as:
102//!
103//! ``` rust
104//! use captains_log::recipe;
105//! let _ = recipe::env_logger("LOG_FILE", "LOG_LEVEL").build();
106//! ```
107//!
108//! ## Customize format example
109//!
110//! ``` rust
111//! use captains_log::*;
112//!
113//! fn format_f(r: FormatRecord) -> String {
114//! let time = r.time();
115//! let level = r.level();
116//! let file = r.file();
117//! let line = r.line();
118//! let msg = r.msg();
119//! format!("{time}|{level}|{file}:{line}|{msg}\n").to_string()
120//! }
121//! let debug_format = LogFormat::new(
122//! "%Y%m%d %H:%M:%S%.6f",
123//! format_f,
124//! );
125//! let debug_file = LogRawFile::new(
126//! "/tmp", "test.log", log::Level::Trace, debug_format);
127//! let config = Builder::default()
128//! .signal(signal_hook::consts::SIGINT)
129//! .raw_file(debug_file);
130//! config.build();
131//! ```
132//!
133//!
134//! If you want to custom more, setup your config with [env_or] helper.
135//!
136//! ## Fine-grain module-level control
137//!
138//! Place [LogFilter] in Arc and share among coroutines.
139//! Log level can be changed on-the-fly.
140//!
141//! There're a set of macro "logger_XXX" to work with `LogFilter`.
142//!
143//! ``` rust
144//! use std::sync::Arc;
145//! use captains_log::*;
146//! log::set_max_level(log::LevelFilter::Debug);
147//! let logger_io = Arc::new(LogFilter::new());
148//! let logger_req = Arc::new(LogFilter::new());
149//! logger_io.set_level(log::Level::Error);
150//! logger_req.set_level(log::Level::Debug);
151//! logger_debug!(logger_req, "Begin handle req ...");
152//! logger_debug!(logger_io, "Issue io to disk ...");
153//! logger_error!(logger_req, "Req invalid ...");
154//! ```
155//!
156//!
157//! ## API-level log handling
158//!
159//! Request log can be track by customizable key (for example, "req_id"), which kept in [LogFilterKV],
160//! and `LogFilterKV` is inherit from `LogFilter`.
161//! You need macro "logger_XXX" to work with it.
162//!
163//! ``` rust
164//! use captains_log::*;
165//! fn debug_format_req_id_f(r: FormatRecord) -> String {
166//! let time = r.time();
167//! let level = r.level();
168//! let file = r.file();
169//! let line = r.line();
170//! let msg = r.msg();
171//! let req_id = r.key("req_id");
172//! format!("[{time}][{level}][{file}:{line}] {msg}{req_id}\n").to_string()
173//! }
174//! let builder = recipe::raw_file_logger_custom("/tmp/log_filter.log", log::Level::Debug,
175//! recipe::DEFAULT_TIME, debug_format_req_id_f);
176//! builder.build().expect("setup_log");
177//! let logger = LogFilterKV::new("req_id", format!("{:016x}", 123).to_string());
178//! info!("API service started");
179//! logger_debug!(logger, "Req / received");
180//! logger_debug!(logger, "header xxx");
181//! logger_info!(logger, "Req / 200 complete");
182//! ```
183//!
184//! The log will be:
185//!
186//! ``` text
187//! [2025-06-11 14:33:08.089090][DEBUG][request.rs:67] API service started
188//! [2025-06-11 14:33:10.099092][DEBUG][request.rs:67] Req / received (000000000000007b)
189//! [2025-06-11 14:33:10.099232][WARN][request.rs:68] header xxx (000000000000007b)
190//! [2025-06-11 14:33:11.009092][DEBUG][request.rs:67] Req / 200 complete (000000000000007b)
191//! ```
192//!
193//!
194//! ## Unit test example
195//!
196//! To setup different log config on different tests.
197//!
198//! **Make sure that you call [Builder::test()]** in test cases.
199//! which enable dynamic log config and disable signal_hook.
200//!
201//! ```rust
202//!
203//! use captains_log::*;
204//!
205//! #[test]
206//! fn test1() {
207//! recipe::raw_file_logger(
208//! "/tmp/test1.log", Level::Debug).test().build();
209//! info!("doing test1");
210//! }
211//!
212//! #[test]
213//! fn test2() {
214//! recipe::raw_file_logger(
215//! "/tmp/test2.log", Level::Debug).test().build();
216//! info!("doing test2");
217//! }
218//! ```
219//!
220//! ## Best practice with rstest
221//!
222//! We provides proc macro [logfn], the following example shows how to combine with rstest.
223//!
224//! * When you have large test suit, you want to know which logs belong to which test case.
225//!
226//! * Sometimes your test crashes, you want to find the responsible test case.
227//!
228//! * The time spend in each test.
229//!
230//! ``` rust
231//!
232//! use rstest::*;
233//! use captains_log::*;
234//!
235//! // A show case that setup() fixture will be called twice, before each test.
236//! // In order make logs available.
237//! #[fixture]
238//! fn setup() {
239//! let builder = recipe::raw_file_logger("/tmp/log_rstest.log", log::Level::Debug).test();
240//! builder.build().expect("setup_log");
241//! }
242//!
243//! #[logfn]
244//! #[rstest(file_size, case(0), case(1))]
245//! fn test_rstest_foo(setup: (), file_size: usize) {
246//! info!("do something111");
247//! }
248//!
249//! #[logfn]
250//! #[rstest]
251//! fn test_rstest_bar(setup: ()) {
252//! info!("do something222");
253//! }
254//!
255//! // NOTE rstest must be at the bottom to make fixture effective
256//! #[tokio::test]
257//! #[logfn]
258//! #[rstest]
259//! async fn test_rstest_async(setup: ()) {
260//! info!("something333")
261//! }
262//! ```
263//!
264//! **Notice:** the order when combine tokio::test with rstest,
265//! `#[rstest]` attribute must be at the bottom to make setup fixture effective.
266//!
267//! After running the test with:
268//!
269//! cargo test -- --test-threads=1
270//!
271//! /tmp/log_rstest.log will have this content:
272//!
273//! ``` text
274//! [2025-07-13 18:22:39.159642][INFO][test_rstest.rs:33] <<< test_rstest_async (setup = ()) enter <<<
275//! [2025-07-13 18:22:39.160255][INFO][test_rstest.rs:37] something333
276//! [2025-07-13 18:22:39.160567][INFO][test_rstest.rs:33] >>> test_rstest_async return () in 564.047µs >>>
277//! [2025-07-13 18:22:39.161299][INFO][test_rstest.rs:26] <<< test_rstest_bar (setup = ()) enter <<<
278//! [2025-07-13 18:22:39.161643][INFO][test_rstest.rs:29] do something222
279//! [2025-07-13 18:22:39.161703][INFO][test_rstest.rs:26] >>> test_rstest_bar return () in 62.681µs >>>
280//! [2025-07-13 18:22:39.162169][INFO][test_rstest.rs:20] <<< test_rstest_foo (setup = (), file_size = 0) enter <<<
281//! [2025-07-13 18:22:39.162525][INFO][test_rstest.rs:23] do something111
282//! [2025-07-13 18:22:39.162600][INFO][test_rstest.rs:20] >>> test_rstest_foo return () in 78.457µs >>>
283//! [2025-07-13 18:22:39.163050][INFO][test_rstest.rs:20] <<< test_rstest_foo (setup = (), file_size = 1) enter <<<
284//! [2025-07-13 18:22:39.163320][INFO][test_rstest.rs:23] do something111
285//! [2025-07-13 18:22:39.163377][INFO][test_rstest.rs:20] >>> test_rstest_foo return () in 58.747µs >>>
286//! ```
287
288extern crate captains_log_helper;
289extern crate log;
290extern crate signal_hook;
291
292#[macro_use]
293extern crate enum_dispatch;
294
295mod buf_file_impl;
296mod config;
297mod console_impl;
298mod env;
299mod file_impl;
300mod formatter;
301mod log_impl;
302mod rotation;
303mod time;
304
305pub mod macros;
306pub mod parser;
307pub mod recipe;
308
309mod log_filter;
310
311pub use self::buf_file_impl::*;
312pub use self::console_impl::*;
313pub use self::env::*;
314pub use self::file_impl::*;
315pub use self::rotation::*;
316pub use self::{config::*, formatter::FormatRecord, log_filter::*, log_impl::setup_log};
317pub use captains_log_helper::logfn;
318
319pub use log::{Level, LevelFilter};
320pub use log::{debug, error, info, trace, warn};
321
322#[cfg(test)]
323mod tests;