logger_rust/
lib.rs

1//! # Logger macro
2//! This crate provides a simple and flexible logging system for Rust projects. It allows you to log messages of different types (error, warn, info, debug) using macros and choose whether to log messages to the console, a file, or both.
3//!
4//! # Features
5//! - Log messages of different types (error, warn, info, debug) using macros
6//! - Choose whether to log messages to the console, a file, or both
7//! - Set the log level at runtime
8//! - Automatically create and append to log files based on the current date
9//! - Handle errors when writing to log files
10//!
11//! ## Usage
12//! To use this crate in your project, add it as a dependency in your `Cargo.toml` file:
13//!
14//! ```env
15//! [dependencies]
16//! logger-rust = "0.2.12"
17//! ```
18//! Then, import the crate:
19//! ```rust
20//! use logger_rust::*;
21//! ```
22//! If you want to use them separately:
23//! ```rust
24//! // all possible crates
25//! use logger_rust::log_debug;
26//! use logger_rust::log_info;
27//! use logger_rust::log_warn;
28//! use logger_rust::log_error;
29//! use logger_rust::set_log_path;
30//! use logger_rust::set_log_level;
31//! use logger_rust::LOG_PATH;
32//! use logger_rust::LogLevel;
33//! use logger_rust::current_time;
34//! ```
35//!
36//! You can now use the `log_error!`, `log_warn!`, `log_info!`, and `log_debug!` macros to log messages of different types:
37//!
38//! ```rust
39//! use logger_rust::*;
40//! 
41//! fn main() {
42//!     log_error!("An error occurred: {}", "Something went wrong");
43//!     log_warn!("A warning occurred: {}", "Something might be wrong");
44//!     log_info!("An info message: {}", "Something happened");
45//!     log_debug!("A debug message: {}", "Something happened in detail");
46//! }
47//! ```
48//!
49//!
50//! Also you can use this:
51//! ```rust
52//! use logger_rust::*;
53//! 
54//!     error(&current_time(), "An error message");
55//!     warn(&current_time(), "A warning message");
56//!     info(&current_time(), "An info message");
57//! ```
58//! Output:
59//! ```diff
60//! - 2023-06-05 12:23:25 [ERROR] An error occurred: Something went wrong
61//! - 2023-06-05 12:23:25 [WARN] A warning occurred: Something might be wrong
62//! A warning occurred: Something might be wrong
63//! + 2023-06-05 12:23:25 [INFO] An info message: Something happened
64//! An info message: Something happened
65//! + 2023-06-05 12:23:25 [DEBUG] A debug message: Something happened in detail
66//! A debug message: Something happened in detail
67//! ```
68//!
69//! # Custom logging
70//! After 0.1.2 version, you can create a custom logging function with macros.
71//!
72//! 1. Create a `class` named as function that you needed (e.g. `trace`):
73//!
74//! ```rust
75//! use logger_rust::*;
76//! 
77//! pub fn trace(now: &str, message: &str) {
78//!     log_message("TRACE", now, message);
79//! }
80//! ```
81//!
82//! 
83//!
84
85pub mod time;
86pub mod config;
87pub mod set_log;
88pub mod log_file;
89pub mod log_rotator;
90pub mod tracer_config;
91pub use crate::set_log::*;
92pub use crate::log_rotator::*;
93pub use crate::tracer_config::*;
94pub use crate::config::LOG_PATH;
95pub use crate::time::current_time;
96pub use crate::log_file::log_message;
97pub use crate::set_log::{set_log_level, set_log_path};
98pub use crate::config::{LogVariables, LogVariablesImpl, LogLevel};
99
100pub fn error(now: &str, message: &str) {
101//! # Error
102//! Outputs an error message via `log_error!` macros.
103//! You can also use just an `error` method instead, but it requires you to define any variable as `&str`
104//! > E.g:
105//! ```rust
106//! use logger_rust::error;
107//! use logger_rust::current_time;
108//! error(&current_time(), "An error message");
109//! ```
110    log_message("ERROR", now, message);
111}
112
113pub fn warn(now: &str, message: &str) {
114//! # Warn
115//! Outputs an warn message via `log_warn!` macros.
116//! You can also use just an `warn` method instead, but it requires you to define any variable as `&str`
117//! > E.g:
118//! ```rust
119//! use logger_rust::warn;
120//! use logger_rust::current_time;
121//! warn(&current_time(), "A warn message");
122//! ```
123    log_message("WARN", now, message);
124}
125
126pub fn info(now: &str, message: &str) {
127//! # Info
128//! Outputs an info message via `log_info!` macros.
129//! You can also use just an `info` method instead, but it requires you to define any variable as `&str`
130//! > E.g:
131//! ```rust
132//! use logger_rust::info;
133//! use logger_rust::current_time;
134//! info(&current_time(), "An info message");
135//! ```
136    log_message("INFO", now, message);
137}
138
139pub fn debug(now: &str, message: &str) {
140//! # Debug
141//! Outputs an debug message via `log_debug` macros.
142//! You can also use just an `debug` method instead, but it requires you to define any variable as `&str`
143//! > E.g:
144//! ```rust
145//! use logger_rust::debug;
146//! use logger_rust::current_time;
147//! debug(&current_time(), "A debug message");
148//! ```
149    log_message("DEBUG", now, message);
150}
151
152pub fn trace(now: &str, message: &str) {
153//! # Debug
154//! Outputs an debug message via `log_debug` macros.
155//! You can also use just an `debug` method instead, but it requires you to define any variable as `&str`
156//! > E.g:
157//! ```rust
158//! use logger_rust::debug;
159//! use logger_rust::current_time;
160//! debug(&current_time(), "A debug message");
161//! ```
162    log_message("TRACE", now, message);
163}
164    
165
166#[macro_export]
167/// ## Macro rules - log_error!
168/// The log_error macro takes any number of arguments and formats them using the format! macro. 
169/// It then gets the current time using the current_time function from the crate and calls the error function from the crate with the current time and formatted message.
170macro_rules! log_error {
171    ($($arg:tt)*) => {{
172        let now = $crate::current_time();
173        $crate::error(&now, &format!($($arg)*));
174    }}
175}
176
177#[macro_export]
178/// ## Macro rules - log_warn!
179/// The log_warn macro takes any number of arguments and formats them using the format! macro. 
180/// It then gets the current time using the current_time function from the crate and calls the warn function from the crate with the current time and formatted message.
181macro_rules! log_warn {
182    ($($arg:tt)*) => {{
183        let now = $crate::current_time();
184        $crate::warn(&now, &format!($($arg)*));
185    }}
186}
187
188#[macro_export]
189/// ## Macro rules - log_info!
190/// The log_info macro takes any number of arguments and formats them using the format! macro. 
191/// It then gets the current time using the current_time function from the crate and calls the info function from the crate with the current time and formatted message.
192macro_rules! log_info {
193    ($($arg:tt)*) => {{
194        let now = $crate::current_time();
195        $crate::info(&now, &format!($($arg)*));
196    }}
197}
198
199#[macro_export]
200/// ## Macro rules - log_debug!
201/// The log_debug macro takes any number of arguments and formats them using the format! macro. 
202/// It then gets the current time using the current_time function from the crate and calls the debug function from the crate with the current time and formatted message.
203macro_rules! log_debug {
204    ($($arg:tt)*) => {{
205        let now = $crate::current_time();
206        $crate::debug(&now, &format!($($arg)*));
207    }}
208}
209
210#[macro_export]
211/// `log_trace!` is a macro that logs trace-level messages.
212///
213/// ## Usage
214///
215/// The `log_trace!` macro can be used in three different ways:
216///
217/// 1. `log_trace!(debug_object)`: This logs the debug representation of the `debug_object` along with its type name and location information (file, line, column, module path).
218///
219/// 2. `log_trace!(debug_object, context)`: This logs the same information as the first form, but also includes a context string that can provide additional information about the log message.
220///
221/// 3. `log_trace!(format_string, args...)`: This logs a formatted message using the given format string and arguments. The format string should follow the same syntax as the standard `format!` macro.
222///
223/// ## Examples
224///
225/// ```rust
226/// use logger_rust::*;
227/// let x: i32 = 42;
228/// log_trace!(x); // Logs: "TRACE 2023-06-09 14:57:47 [TRACE] src\<module>:L29/C1 - used: x ->> (42): 42 | Type: <i32> | ThreadId(4) ->> Timestamp: UN1686304667694020IX | Module <module>"
229///
230/// let y = "Hello, world!";
231/// log_trace!(y, "greeting"); // Logs: "2023-06-09 14:57:47 [TRACE] src\<module>:L32/C1 - used: y ->> ("Hello, world!"): "Hello, world!" | Type: <&str> | ThreadId(4) ->> Timestamp: UN1686304667694335IX ->> Context: <greeting> | Module: <module>"
232///
233/// log_trace!(x, "{}"); // Logs: "TRACE used: x ->> (42): 42 | Type: <i32> ... <context is empty>"
234/// ```
235macro_rules! log_trace {
236    ($debug_object:expr) => {{
237        log_trace!($debug_object, "");
238    }};
239    ($debug_object:expr, $context:expr) => {{
240        let now = $crate::current_time();
241        let line = line!();
242        let file = file!();
243        let module_path = module_path!();
244        let thread_id = std::thread::current().id();
245        let timestamp = std::time::SystemTime::now()
246            .duration_since(std::time::UNIX_EPOCH)
247            .unwrap()
248            .as_micros();
249        let context_str = if $context.is_empty() {
250            String::new()
251        } else {
252            format!("\x1b[36m ->> Context: \x1b[0m\x1b[1m<{}>", $context)
253        };
254        let type_name = $debug_object.type_name();
255        let column = column!();
256        let debug_info = format!(
257            "\x1b[34m{}:L{}/C{} - used: \x1b[32m{}\x1b[36m ->> ({:?}): \x1b[31m{:?}\x1b[36m | \x1b[32mType: \x1b[0m\x1B[1m<{}>\x1b[0m | \x1b[32m{:?} \x1b[36m->> \x1b[34mTimestamp: UN{}IX{}\x1b[0m\x1b[36m |\x1b[33m Module: \x1b[0m{}",
258            file, line,
259            column,
260            stringify!($debug_object), 
261            &$debug_object, 
262            $debug_object,
263            type_name,
264            thread_id,
265            timestamp,
266            context_str,
267            module_path,
268        );
269        $crate::log_message("TRACE", &now, &debug_info);
270    }};
271    ($($arg:tt)*) => {{
272        let now = $crate::current_time();
273        $crate::log_message("TRACE", &now, &format!($($arg)*));
274    }}
275}