Rust日志学习(三)——simple_logger

来源:互联网 发布:php 统计文章浏览次数 编辑:程序博客网 时间:2024/06/08 03:53

simple_logger——A rust logger that prints all messages with a readable output format.

simple_logger的Github链接:https://github.com/borntyping/rust-simple_logger

下面是simple_logger的简单示例:

示例1:

最简单用法

#[macro_use]extern crate log;extern crate simple_logger;fn main() {    simple_logger_fn();}#[warn(dead_code)]fn simple_logger_fn(){    simple_logger::init().unwrap();    warn!("This is an example message.");}

编译、运行结果如下:
这里写图片描述

示例2:

初始化时改变默认日志level等级:

#[macro_use]extern crate log;extern crate simple_logger;fn main() {    simple_logger_level();}#[warn(dead_code)]fn simple_logger_level(){    simple_logger::init_with_level(log::LogLevel::Warn).unwrap();    warn!("This will be logged.");    info!("This will NOT be logged.");//过滤掉了}

编译、运行结果如下:
这里写图片描述

源代码分析

因为这个源代码较少,所以就把所有源代码都列出来了:

//! A logger that prints all messages with a readable output format.#[macro_use]extern crate log;extern crate time;use log::{Log,LogLevel,LogMetadata,LogRecord,SetLoggerError};struct SimpleLogger {    log_level: LogLevel,}//实现Log特性impl Log for SimpleLogger {    fn enabled(&self, metadata: &LogMetadata) -> bool {        metadata.level() <= self.log_level    }    fn log(&self, record: &LogRecord) {        if self.enabled(record.metadata()) {            println!(                "{} {:<5} [{}] {}",                time::strftime("%Y-%m-%d %H:%M:%S", &time::now()).unwrap(),                record.level().to_string(),                record.location().module_path(),                record.args());        }    }}//2种初始化logger的方式:/// Initializes the global logger with a SimpleLogger instance with/// `max_log_level` set to a specific log level.pub fn init_with_level(log_level: LogLevel) -> Result<(), SetLoggerError> {    log::set_logger(|max_log_level| {        max_log_level.set(log_level.to_log_level_filter());//设置日志level        return Box::new(SimpleLogger { log_level: log_level });    })}/// Initializes the global logger with a SimpleLogger instance with/// `max_log_level` set to `LogLevel::Trace`.pub fn init() -> Result<(), SetLoggerError> {    init_with_level(LogLevel::Trace)//默认等级为Trace}

果然是simple logger,代码很simple,功能很simple。

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 崩坏3邮箱验证码过期怎么办 快递员被顾客恶意投诉怎么办 5岁幼儿逻辑思维差怎么办 脸一边胖一边瘦怎么办 夏天穿鞋子脚痒怎么办 脚痒怎么办但不是脚气 脚气脚趾缝烂了怎么办 凉鞋穿久了臭怎么办 运动鞋穿久了臭怎么办 体恤穿久了发臭怎么办 十七八岁青少年逆反心理怎么办 挨刚煮好的粥烫伤改怎么办? 5e的demo有水印怎么办 宝宝湿疹激素一停药复发怎么办 木工家装没事做怎么办 取票之后票丢了怎么办 补牙咬合低了点怎么办 留学生上美国网课上不了网怎么办 大四绩点不够2.0怎么办 ucas申请成绩下来后怎么办 在本校读研毕业东西怎么办 美国硕士gpa低于3.0怎么办 英国t4签证拒签怎么办 abc洗液过敏了怎么办 护士电子化注册忘记用户名怎么办 手机重力感应坏了怎么办 电脑所有驱动都删除了怎么办 毕业生没有签工作档案怎么办 澳洲两年工作签怎么办 上班一年没签劳动合同怎么办 公司拖欠工资怎么办没签劳动合同 brp丢了怎么办回国补 被怀疑假结婚该怎么办 中考作弊被捉了怎么办 露娜注册错了怎么办 去泰国开民宿怎么办工作签证 绩点2.7想出国怎么办 香港过境想去澳门怎么办 加拿大博士资格考试没通过怎么办 外国人没有学历怎么办工作签证 澳洲语言班挂了怎么办