tklog is a high-performance structured logging library for Rust [中文]
tklog featuring ease-of-use, efficiency, and a rich feature suite. It supports functionalities such as console logging, file logging, both synchronous and asynchronous logging modes, alongside advanced capabilities like log slicing by time or size and compressed backup of log files.
Features
- Function support includes console logging, file logging, synchronous logging, asynchronous logging.
- Log level settings mirror those of the standard library: trace, debug, info, warn, error, fatal.
- Formatted output with customizable formats that can include log level flags, formatted timestamps, and log file locations.
- Log file slicing by time intervals: hourly, daily, or monthly.
- Log file slicing by specified file size.
- File rolling mechanism that automatically deletes older log files once a maximum backup count is reached to prevent excess logs from accumulating.
- Compression of archived backup log files.
- Supports the official log library standard API
official website
Simple Usage Description
Use tklog
tklog = "0.0.9" # "0.0.x" current version
The simplest way to use tklog involves direct macro calls:
use ;
By default, it will print console log, not files. Execution Result:
[TRACE] 2024-05-26 11:47:22 testlog.rs 27:trace>>>>,aaaaaaaaa,1,2,3,4
[DEBUG] 2024-05-26 11:47:22 testlog.rs 28:debug>>>>,bbbbbbbbb,1,2,3,5
[INFO] 2024-05-26 11:47:22 testlog.rs 29:info>>>>,ccccccccc,1,2,3,5
[WARN] 2024-05-26 11:47:22 testlog.rs 30:warn>>>>,dddddddddd,1,2,3,6
[ERROR] 2024-05-26 11:47:22 testlog.rs 31:error>>>>,eeeeeeee,1,2,3,7
[FATAL] 2024-05-26 11:47:22 testlog.rs 32:fatal>>>>,ffffffff,1,2,3,8
For initialization and customization, tklog furnishes methods to configure options such as console output, log levels, formatting styles, cutting strategies, and custom formatters.
use ;
This illustrates global, singleton-style logging setup. Additionally, tklog facilitates custom multi-instance logging configurations, useful in systems requiring distinct logging structures across different components.
Multi-Instance Logging
tklog also accommodates multiple instances for scenarios that require distinct logging configurations. Each instance can possess its unique settings for console output, log level, file rotation, and a custom formatter.
use ;
Execution Result
debugs>>>>,BBBBBBBBB,1,2,3,5 | 2024-05-26 14:13:25 testlog.rs 70[DEBUG]
infos>>>>,CCCCCCCCC,1,2,3,5 | 2024-05-26 14:13:25 testlog.rs 71[INFO]
warns>>>>,DDDDDDDDDD,1,2,3,6 | 2024-05-26 14:13:25 testlog.rs 72[WARN]
errors>>>>,EEEEEEEE,1,2,3,7 | 2024-05-26 14:13:25 testlog.rs 73[ERROR]
fatals>>>>,FFFFFFFF,1,2,3,8 | 2024-05-26 14:13:25 testlog.rs 74[FATAL]
Note: The structured log output above conforms to the format specified by "{message} | {time} {file}{level}\n". The formatter includes identifiers like {message}, {time}, {file}, {level}, and any additional text or separators outside these placeholders.
Detailed Usage Guide
1. Log Levels: Trace < Debug < Info < Warn < Error < Fatal.
Example:
LOG.set_level //Sets the log level to Info
2. Console Logging: Enable or disable via .set_console(bool).
LOG.set_console //Disables console logging (default is true)
3. Log Formats:
Nano : No formatting
Date : Outputs date
Time : Outputs time to seconds
Microseconds :Outputs time with microseconds
LongFileName :Full file path with line number
ShortFileName : Abbreviated file path with line number
LevelFlag : Log level marker .
For custom formats:
LOG.set_format
4. Custom Format Strings:
Default is "{level}{time} {file}:{message}\n".
-
{level}: Log level indicator, e.g., [Debug]. -
{time}: Logged timestamp. -
{file}: Filename and line number. -
{message}: Log content.
Example:
LOG.set_formatter
Reminder: Text outside the {level}, {time}, {file}, and {message} tags is output verbatim, including delimiters, spaces, and newlines.
5. Time-Based Log File Rotation:
Modes: MODE::HOUR, MODE::DAY, MODE::MONTH.
Use .set_cutmode_by_time() with:
- File path
- Time mode
- Maximum backup count
- Compression option
Example:
let mut log = new;
log.set_cutmode_by_time;
This configures the log to be stored at /usr/local/tklogs.log, rotated daily, with no limit on backups, and without compressing daily logs.
Backup Naming Conventions:
- Daily:
tklogs_20240521.logtklogs_20240522.log
- Hourly:
tklogs_2024052110.logtklogs_2024052211.log
- Monthly:
tklogs_202403.logtklogs_202404.log
6. Size-Based Log File Rotation:
Utilize .set_cutmode_by_size() with the following parameters:
- File path
- Roll size
- Max backups
- Compress backups
Example:
let mut log = new;
log.set_cutmode_by_size;
Here, tklogs.log denotes the path, with files rolling at 100 MB each, retaining 10 backups, and compressing them.
Backup File Naming Convention:
tklogs_1.log.gz
tklogs_2.log.gz
tklogs_3.log.gz
Log Printing Methods:
-
Global Singleton:
trace!,debug!,info!,warn!,error!,fatal!
-
Multiple Instances:
traces!,debugs!,infos!,warns!,errors!,fatals!
Asynchronous Logging
-
Global Singleton Async:
async_trace!,async_debug!,async_info!,async_warn!,async_error!,async_fatal!
-
Multiple Instances Async:
async_traces!,async_debugs!,async_infos!,async_warns!,async_errors!,async_fatals!
Example: Global Asynchronous Usage
use ;
async
async
Execution Result:
[TRACE] 20:03:32 testasynclog.rs 20:trace>>>>,aaaaaaa,1,2,3
[DEBUG] 20:03:32 testasynclog.rs 21:debug>>>>,aaaaaaa,1,2,3
[INFO] 20:03:32 testasynclog.rs 22:info>>>>,bbbbbbbbb,1,2,3
[WARN] 20:03:32 testasynclog.rs 23:warn>>>>,cccccccccc,1,2,3
[ERROR] 20:03:32 testasynclog.rs 24:error>>>>,ddddddddddddd,1,2,3
[FATAL] 20:03:32 testasynclog.rs 25:fatal>>>>,eeeeeeeeeeeeee,1,2,3
Multiple Instance Asynchronous
use Arc;
use ;
async
Execution Result:
async_debugs>>>>,BBBBBBBBBB,1,2,3 | 2024-05-26 20:10:24 testasynclog.rs 45[DEBUG]
async_infos>>>>,CCCCCCCCCC,1,2,3 | 2024-05-26 20:10:24 testasynclog.rs 46[INFO]
async_warns>>>>,DDDDDDDDDD,1,2,3 | 2024-05-26 20:10:24 testasynclog.rs 47[WARN]
async_errors>>>>,EEEEEEEEEEE,1,2,3 | 2024-05-26 20:10:24 testasynclog.rs 48[ERROR]
async_fatals>>>>,FFFFFFFFFFFF,1,2,3 | 2024-05-26 20:10:24 testasynclog.rs 49[FATAL]
Supports the official log library standard API
- tklog implements the regular use of the official Log interface API
- Implement the official log library API to be used in asynchronous scenarios
How to enable the official log library API:
tklog enables API support for official logs by calling the uselog() function
Use example
use ;
use ;
Enable the log library API in asynchronous scenarios
use ;
use ;
async
The module sets log parameters
- tklog provides
set_optionandset_mod_optionto set the global log parameters of the Logger object and specify the log parameters of the mod - In the project, you can use the global LOG object to set log parameters for multiple mod at the same time
- Different mod can set different log level, log formats, log file, etc
- The log parameter of mod for ASYNC_LOG is the same as LOG object
set_option example:
tklog::LOG.set_option(LogOption{level:Some(LEVEL::Debug),console: Some(false),format:None,formatter:None,fileoption: Some(Box::new(FileTimeMode::new("day.log",tklog::MODE::DAY,0,true)))});
LogOption instruction
- level level of log
- format format of log
- formatter user-defined log output format
- console console log setting
- fileoption file log setting
set_mod_option File log setting:
tklog::LOG.set_mod_option("testlog::module1",LogOption{level:Some(LEVEL::Debug),console: Some(false),format:None,formatter:None,fileoption: Some(Box::new(FileTimeMode::new("day.log", tklog::MODE::DAY, 0,true)))});
testlog::module1is the module name,you can usemodule_path!()to print out the current module name- When tklog is used in the module
testlog::module1, tklog will use the LogOption object
Complete mod example
Execution Result:
[DEBUG] 2024-06-19 10:54:07 testlog.rs 54:module1,tklog api,LOG debug log>>,123
[INFO] 2024-06-19 10:54:07 testlog.rs 55:module1,tklog api,LOG info log>>,456
[DEBUG] 2024-06-19 10:54:07 testlog.rs 56:module1,log api,debug log>>111
[INFO] 2024-06-19 10:54:07 testlog.rs 57:module1,log api,info log>>222
[INFO] 2024-06-19 10:54:08 testlog.rs 68:module2,tklog api,LOG info log>>,456
[INFO] 2024-06-19 10:54:08 testlog.rs 70:module2,log api,info log>>222
Example 2: Asynchronous logging
async
Execution Result:
[DEBUG] 2024-06-19 10:59:26 testlog.rs 85:async module3,tklog api,LOG debug log>>,123
[INFO] 2024-06-19 10:59:26 testlog.rs 86:async module3,tklog api,LOG info log>>,456
[DEBUG] 2024-06-19 10:59:26 testlog.rs 87:async module3,log api,debug log>>333
[INFO] 2024-06-19 10:59:26 testlog.rs 88:async module3,log api,info log>>444
[INFO] 2024-06-19 10:59:27 testlog.rs 98:async module4,tklog api,LOG info log>>,456
[INFO] 2024-06-19 10:59:27 testlog.rs 100:async module4,log api,info log>>444
tklog supports multi-instance formatting format! And asynchronous format!
Example:
Execution Result:
2024-06-06 15:54:07 testsynclog.rs 80:Debug>>>1,2>>>
2024-06-06 15:54:07 testsynclog.rs 83:Info>>>1,2>>
2024-06-06 15:54:07 testsynclog.rs 84:Warn>>>1,2
2024-06-06 15:54:07 testsynclog.rs 85:Error>>>1,2
2024-06-06 15:54:07 testsynclog.rs 86:Fatal>>>1,2
asynchronous Example
async
Execution Result:
2024-06-06 16:09:26 testasynclog.rs 61:Debug>>>1,2>>>
2024-06-06 16:09:26 testasynclog.rs 64:Info>>>1,2>>
2024-06-06 16:09:26 testasynclog.rs 65:Warn>>>1,2
2024-06-06 16:09:26 testasynclog.rs 66:Error>>>1,2
2024-06-06 16:09:26 testasynclog.rs 67:Fatal>>>1,2
tklog supports custom log processing functions.
tklog allows the addition of external custom functions through set_custom_handler(), enabling control over the log processing flow and logic.
Example
Execution Result
---- test_custom stdout ----
level >>>>>>>>>>>>>>>>>Debug
message >>>>>>>>>>>>>>>>>"000000000000000000"
filename >>>>>>>>>>>>>>>>>"tests\\testsynclog.rs"
line >>>>>>>>>>>>>>>>>143
modname >>>>>>>>>>>>>>>>>"testsynclog"
debug now
level >>>>>>>>>>>>>>>>>Info
message >>>>>>>>>>>>>>>>>"1111111111111111111"
filename >>>>>>>>>>>>>>>>>"tests\\testsynclog.rs"
line >>>>>>>>>>>>>>>>>144
modname >>>>>>>>>>>>>>>>>"testsynclog"
2024-08-05 15:39:07 testsynclog.rs 144:1111111111111111111
Explanation
When the function fn custom_handler(lc: &LogContext) -> bool returns true, tklog calls the custom_handler to execute the custom function and then continues with tklog's logging process. When it returns false, tklog does not proceed with its logging process and directly returns. As shown in the example, when the log level is Debug, it returns false, so tklog does not print the Debug log.
Benchmark Test
log_benchmark time: [2.9703 µs 2.9977 µs 3.0256 µs]
change: [-95.539% -95.413% -95.268%] (p = 0.00 < 0.05)
Performance has improved.
Found 9 outliers among 100 measurements (9.00%)
4 (4.00%) high mild
5 (5.00%) high severe
log_benchmark time: [2.9685 µs 3.0198 µs 3.0678 µs]
change: [-3.6839% -1.2170% +1.0120%] (p = 0.34 > 0.05)
No change in performance detected.
Found 7 outliers among 100 measurements (7.00%)
7 (7.00%) high mild
test_debug time: [3.3747 µs 3.4599 µs 3.5367 µs]
change: [-69.185% -68.009% -66.664%] (p = 0.00 < 0.05)
Performance has improved.
Found 9 outliers among 100 measurements (9.00%)
6 (6.00%) high mild
3 (3.00%) high severe
test_debug time:
change:
Performance has improved.
Found 2 outliers among 100 measurements
2 high mild
Explanation: The time range gives three data points representing the minimum test execution time (2.9055 microseconds), the value near the average (2.9444microseconds-3.8881microseconds ), and the maximum (3.9408 microseconds).
Conclusion: Log printing function performance: 2 µs /op - 3.9 µs /op (microsecond/time)