duskphantom_utils/
log.rs

1// Copyright 2024 Duskphantom Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15// SPDX-License-Identifier: Apache-2.0
16
17// 实现一个fprintln宏用于写入文件
18#[macro_export]
19macro_rules! fprint {
20    ($file:expr, $($arg:tt)*) => {
21        #[cfg(feature = "log_enabled")]
22        {
23            let s=format!($($arg)*);
24            $crate::utils::log::must_write($file, &s,false);
25        }
26    };
27    ($file:expr;$mode:literal;$($arg:tt)*) => {
28        #[cfg(feature = "log_enabled")]
29        {
30            let s=format!($($arg)*);
31            let append=$mode=='a';
32            $crate::utils::log::must_write($file, &s,append);
33        }
34    };
35}
36#[macro_export]
37macro_rules! fprintln {
38    ($file:expr, $($arg:tt)*) => {
39        #[cfg(feature = "log_enabled")]
40        {
41            let mut s=format!($($arg)*);
42            s.push('\n');
43            $crate::log::must_write($file, &s,false);
44        }
45    };
46    ($file:expr;$mode:literal;$($arg:tt)*) => {
47        #[cfg(feature = "log_enabled")]
48        {
49            let mut s=format!($($arg)*);
50            s.push('\n');
51            let append=$mode=='a';
52            $crate::log::must_write($file, &s,append);
53        }
54    };
55}
56// 控制台打印(条件编译)
57#[macro_export]
58macro_rules! cprintln {
59    ($($arg:tt)*) => {
60        #[cfg(feature = "log_enabled")]
61        {
62            println!($($arg)*);
63        }
64    };
65}
66
67#[allow(unused)]
68pub fn must_write(path: &str, content: &str, append: bool) {
69    use std::fs::OpenOptions;
70    use std::io::Write;
71    // if dir not exists, create it
72    let path = std::path::Path::new(path);
73    if let Some(dir) = path.parent() {
74        if !dir.exists() {
75            std::fs::create_dir_all(dir).unwrap();
76        }
77    }
78    let mut file = OpenOptions::new()
79        .create(true)
80        .write(true)
81        .append(append)
82        .open(path)
83        .unwrap();
84    file.write_all(content.as_bytes()).unwrap();
85    file.flush().unwrap();
86}