dzl/
lib.rs

1//! # dzl
2//! A crate for logging.
3//!
4//! It is simple and easy to use
5//!
6//! You can learn more [here](https://github.com/za-songguo/dzl "Github")
7//!
8//! # Example
9//! `main.rs`
10//! ```
11//! dzl::init().ok(); // Call this function only once in main.rs
12//! dzl::loggers::trace("Something...");
13//! dzl::loggers::debug("Something...");
14//! dzl::loggers::info("Something...");
15//! dzl::loggers::warn("Something...");
16//! dzl::loggers::error("Something...");
17//! dzl::loggers::custom("CustomType", "Something...");
18//! ```
19//!
20//! `Dzl.toml`
21//! ```toml
22//! write_to_log_file = true
23//! log_path = "dzl.log" # This file needs to be created
24//! log_level = "debug" # Only logs greater than or equal to this level will be printed and written to the log file
25//! ```
26//!
27//! Output:
28//! ```
29//! 2022-12-03 11:30:55.23172315 +08:00:00 DEBUG Something...
30//! 2022-12-03 11:30:55.233852405 +08:00:00 WARN Something...
31//! 2022-12-03 11:30:55.235884013 +08:00:00 ERROR Something...
32//! 2022-12-03 11:30:55.240158709 +08:00:00 CustomType Something...
33//! ```
34//!
35
36use std::{fs, io::ErrorKind};
37
38pub(crate) mod config;
39pub(crate) mod errors;
40pub(crate) mod log;
41pub mod loggers;
42
43/// Init function
44pub fn init() -> Result<(), errors::CustomError> {
45    let config = config::Config::new().read()?;
46    if let Some(log_path) = config.log_path() {
47        let file = fs::File::open(&log_path);
48        if file.is_err() && file.unwrap_err().kind() == ErrorKind::NotFound {
49            // Create the log file if the file is not exists
50            println!("Log file was not created, creating...");
51            fs::File::create(&log_path)?;
52        }
53    }
54
55    Ok(())
56}