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