1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
use super::constants::*;
use super::flexi_log::*;
use super::log_config::*;
use super::target::*;
use crate::debug_config::*;
use cyfs_base::BuckyResult;
use cyfs_util::get_cyfs_root_path;

use log::Log;
use std::path::PathBuf;
use std::str::FromStr;

pub struct CyfsLogger {
    config: LogConfig,
    logger: FlexiLogger,
}

pub enum CyfsLoggerCategory {
    Service,
    App,
}

pub struct CyfsLoggerBuilder {
    config: LogConfig,
    targets: Vec<Box<dyn CyfsLogTarget>>,
    disable_file_config: bool,
}

impl CyfsLoggerBuilder {
    pub fn new_service(name: &str) -> Self {
        Self::new(name, CyfsLoggerCategory::Service)
    }

    pub fn new_app(name: &str) -> Self {
        Self::new(name, CyfsLoggerCategory::App)
    }

    pub fn new(name: &str, category: CyfsLoggerCategory) -> Self {
        // simple_logger::SimpleLogger::default().init().unwrap();

        let log_dir = Self::get_log_dir(name, &category);
        let config = LogConfig::new(log_dir);
        Self {
            config,
            targets: vec![],
            disable_file_config: false,
        }
    }

    pub fn directory(mut self, dir: impl Into<PathBuf>) -> Self {
        self.config.set_log_dir(dir.into());
        self
    }

    pub fn level(mut self, level: &str) -> Self {
        self.config.global.set_level(level);
        self
    }

    pub fn console(mut self, level: &str) -> Self {
        self.config.global.set_console(level);
        self
    }

    pub fn file(mut self, enable: bool) -> Self {
        self.config.global.file = enable;
        self
    }

    pub fn file_max_count(mut self, file_max_count: u32) -> Self {
        self.config.global.set_file_max_count(file_max_count);
        self
    }

    pub fn file_max_size(mut self, file_max_size: u64) -> Self {
        self.config.global.set_file_max_size(file_max_size);
        self
    }

    pub fn enable_bdt(mut self, level: Option<&str>, console_level: Option<&str>) -> Self {
        let config =
            Self::bdt_module(level, console_level).expect(&format!("invalid bdt log config"));
        self.config.add_mod(config);

        self
    }

    pub fn module(mut self, name: &str, level: Option<&str>, console_level: Option<&str>) -> Self {
        let config = Self::new_module(name, name, level, console_level)
            .expect(&format!("invalid module log config"));
        self.config.add_mod(config);

        self
    }

    pub fn target(mut self, target: Box<dyn CyfsLogTarget>) -> Self {
        self.targets.push(target);
        self
    }

    pub fn disable_module(mut self, list: Vec<impl Into<String>>, level: LogLevel) -> Self {
        for name in list {
            let name = name.into();
            self.config.disable_module_log(&name, &level);
        }
        self
    }

    // do not use {cyfs}/etc/debug.toml
    pub fn disable_file_config(mut self, disable: bool) -> Self {
        self.disable_file_config = disable;
        self
    }

    pub fn build(mut self) -> BuckyResult<CyfsLogger> {
        self.config.disable_async_std_log();

        if !self.disable_file_config {
            if let Some(config_node) = DebugConfig::get_config("log") {
                if let Err(e) = self.config.load(config_node) {
                    println!("load log config error! {}", e);
                }
            }
        }

        let logger = FlexiLogger::new(&self.config, self.targets)?;

        let ret = CyfsLogger {
            config: self.config,
            logger,
        };

        Ok(ret)
    }

    pub fn get_log_dir(name: &str, category: &CyfsLoggerCategory) -> PathBuf {
        assert!(!name.is_empty());

        let mut root = get_cyfs_root_path();
        let folder = match *category {
            CyfsLoggerCategory::Service => "log",
            CyfsLoggerCategory::App => "log/app",
        };
        root.push(folder);

        root.push(name);
        root
    }

    fn new_module(
        name: &str,
        file_name: &str,
        level: Option<&str>,
        console_level: Option<&str>,
    ) -> BuckyResult<LogModuleConfig> {
        let mut config = LogModuleConfig::new_default(name);
        if let Some(level) = level {
            config.level = LogLevel::from_str(level)?;
        }
        if let Some(level) = console_level {
            config.console = LogLevel::from_str(level)?;
        }

        config.file_name = Some(file_name.to_owned());
        Ok(config)
    }

    fn bdt_module(
        level: Option<&str>,
        console_level: Option<&str>,
    ) -> BuckyResult<LogModuleConfig> {
        Self::new_module("cyfs_bdt", "bdt", level, console_level)
    }
}

impl Into<Box<dyn Log>> for CyfsLogger {
    fn into(self) -> Box<dyn Log> {
        Box::new(self.logger) as Box<dyn Log>
    }
}

impl CyfsLogger {
    pub fn start(self) {
        let max_level = self.logger.get_max_level();
        println!("log max level: {}", max_level);
        log::set_max_level(max_level.into());

        if let Err(e) = log::set_boxed_logger(self.into()) {
            let msg = format!("call set_boxed_logger failed! {}", e);
            println!("{}", msg);
        }

        Self::display_debug_info();
    }

    pub fn display_debug_info() {
        // 输出环境信息,用以诊断一些环境问题
        for argument in std::env::args() {
            info!("arg: {}", argument);
        }

        // info!("current exe: {:?}", std::env::current_exe());
        info!("current dir: {:?}", std::env::current_dir());

        info!("current version: {}", cyfs_base::get_version());

        for (key, value) in std::env::vars() {
            info!("env: {}: {}", key, value);
        }
    }

    pub fn flush() {
        log::logger().flush();
    }
}