rigela_utils/
logger.rs

1/*
2 * Copyright (c) 2024. The RigelA open source project team and
3 * its contributors reserve all rights.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software distributed under the
10 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 * See the License for the specific language governing permissions and limitations under the License.
12 */
13
14use crate::fs::get_rigela_program_directory;
15use log::LevelFilter;
16use log4rs::{
17    append::{
18        console::{ConsoleAppender, Target},
19        rolling_file::{
20            policy::compound::{
21                roll::delete::DeleteRoller, trigger::size::SizeTrigger, CompoundPolicy,
22            },
23            RollingFileAppender,
24        },
25    },
26    config::{Appender, Config, Root},
27    encode::pattern::PatternEncoder,
28    filter::threshold::ThresholdFilter,
29    init_config,
30};
31
32const LOG_FILE_NAME: &str = "run.log";
33
34/**
35初始化日志收集器。
36`path` 日志文件存放的文件夹路径,是相对于本项目用户目录的路径。
37*/
38pub fn init_logger(path: Option<&str>) {
39    let level = LevelFilter::Info;
40    let file_path = get_rigela_program_directory()
41        .join("logs")
42        .join(path.unwrap_or(LOG_FILE_NAME));
43
44    // 创建一个标准错误日志器
45    let stderr = ConsoleAppender::builder()
46        // Pattern: https://docs.rs/log4rs/*/log4rs/encode/pattern/index.html
47        .encoder(Box::new(PatternEncoder::new("{l} - {m}\n")))
48        .target(Target::Stderr)
49        .build();
50
51    //输出到文件
52    let logfile = RollingFileAppender::builder()
53        .build(
54            file_path,
55            Box::new(CompoundPolicy::new(
56                Box::new(SizeTrigger::new(1024 * 1024)), // 超过1MB后滚动
57                Box::new(DeleteRoller::new()),
58            )),
59        )
60        .unwrap();
61
62    // 将跟踪级别输出记录到文件中,其中跟踪是默认级别,以编程方式指定的级别记录到stderr。
63    let config = Config::builder()
64        .appender(Appender::builder().build("logfile", Box::new(logfile)))
65        .appender(
66            Appender::builder()
67                .filter(Box::new(ThresholdFilter::new(level)))
68                .build("stderr", Box::new(stderr)),
69        )
70        .build(
71            Root::builder()
72                .appender("logfile")
73                .appender("stderr")
74                .build(LevelFilter::Trace),
75        )
76        .unwrap();
77
78    // 使用此选项可以在运行时更改日志级别。这意味着您可以更改默认日志级别以进行跟踪,如果您正在尝试调试某个问题,并且需要打开更多日志,则在完成后将其关闭。
79    init_config(config).expect("Can't initialize the logger.");
80}