安装 pip install loguru
简单使用 1 2 3 4 5 6 import loguruloguru.logger.info('info' ) loguru.logger.debug('debug' ) loguru.logger.error('error' ) loguru.logger.warning('warning' )
默认的输出格式是包含【时间、级别、模块名、行号以及日志信息】,不需要手动创建 logger ,直接使用即可,另外其输出还是彩色的,看起来会更加友好。
保留日志文件 一般情况,我们都需要将日志输出保存到文件中,loguru直接通过 add() 方法,就可以配置一个日志文件
1 2 3 4 5 6 7 8 9 10 11 12 13 import loguruloguru.logger.add("interface_log_{time}.log" , rotation="500MB" , encoding="utf-8" , enqueue=True , compression="zip" , retention="10 days" ) loguru.logger.info('info' ) loguru.logger.debug('debug' ) loguru.logger.error('error' ) loguru.logger.warning('warning' )
第一个参数是保存日志信息的文件路径,像我写的后缀多了个 {time} ,就是获取当前时间节点,这样就会自动创建新的日志;这个time应该是库里自带的变量,如果你想自己定义时间也可以的哦,具体可以看看下面封装类的实现形式!
当你需要输出中文日志的时候,请加上 encoding=“utf-8” ,避免出现乱码
enqueue=True 代表异步写入,官方的大概意思是:在多进程同时往日志文件写日志的时候使用队列达到异步功效
旋转
可以理解成日志的创建时机,可以有多种写法
rotation=“500 MB” :当日志文件达到500MB时就会重新生成一个文件 rotation=“12:00” :每天12点就会创建新的文件、 rotation=“1 week” :每隔一周创建一个log retention 配置日志的最长保留时间,官方例子: “1 week, 3 days”、“2 month”
compression 配置文件的压缩格式,可以配置常见的格式 zip、tar、gz、tar.gz 等
loguru字符串输出 loguru还提供了字符串格式化输出日志的功能
1 2 3 4 loguru.logger.info('If you are using Python {}, prefer {feature} of course!' , 3.6 , feature='f-strings' ) n1 = "cool" n2 = [1 , 2 , 3 ] loguru.logger.info(f'If you are using Python {n1} , prefer {n2} of course!' )
loguru封装类 日志输出路径:你的项目路径下的log文件夹下 注意:这个是工具类,需要放在项目路径下的util文件夹之类的,不能直接放项目路径下 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 """ 操作日志记录 """ import timefrom loguru import loggerfrom pathlib import Pathproject_path = Path.cwd().parent log_path = Path(project_path, "log" ) t = time.strftime("%Y_%m_%d" ) class Loggings : __instance = None logger.add(f"{log_path} /interface_log_{t} .log" , rotation="500MB" , encoding="utf-8" , enqueue=True , retention="10 days" ) def __new__ (cls, *args, **kwargs ): if not cls.__instance: cls.__instance = super (Loggings, cls).__new__(cls, *args, **kwargs) return cls.__instance def info (self, msg ): return logger.info(msg) def debug (self, msg ): return logger.debug(msg) def warning (self, msg ): return logger.warning(msg) def error (self, msg ): return logger.error(msg) loggings = Loggings() if __name__ == '__main__' : loggings.info("中文test" ) loggings.debug("中文test" ) loggings.warning("中文test" ) loggings.error("中文test" ) logger.info('If you are using Python {}, prefer {feature} of course!' , 3.6 , feature='f-strings' ) n1 = "cool" n2 = [1 , 2 , 3 ] logger.info(f'If you are using Python {n1} , prefer {n2} of course!' )