Documentation
use std::str::FromStr;

use time::{format_description, UtcOffset};
use tracing::{info, Level};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_appender::{non_blocking, rolling};
use tracing_error::ErrorLayer;
use tracing_subscriber::fmt::{self, time::OffsetTime};
use tracing_subscriber::prelude::*;

/// WorkerGuard 移除作用域,文件写入就会关闭
pub fn init_log(dir: &str, file_name: &str, leve: &str) -> WorkerGuard {
    let format = "[year]-[month]-[day] [hour]:[minute]:[second].[subsecond digits:3]";
    let local_time = OffsetTime::new(
        UtcOffset::from_hms(8, 0, 0).unwrap(),
        format_description::parse(format).expect("fmt error"),
    );
    let file_appender = rolling::never(dir, file_name);
    let (non_blocking_appender, guard) = non_blocking(file_appender);

    let file_layer = fmt::layer()
        .with_timer(local_time.clone())
        .with_file(true)
        .with_line_number(true)
        //是否允许颜色输出,默认true
        // .with_ansi(false)
        .with_writer(non_blocking_appender);
    tracing_subscriber::registry()
        .with(tracing_subscriber::filter::LevelFilter::from_level(
            Level::from_str(leve).unwrap_or(Level::INFO),
        ))
        .with(ErrorLayer::default())
        .with(
            fmt::layer()
                // .pretty()
                .with_file(true)
                .with_line_number(true)
                .with_timer(local_time),
        )
        .with(file_layer)
        .init();
    info!("init log success");
    guard
    // tracing_subscriber::registry().with(fmt::layer()).init();
}