python记录日志非常简单,单文件日志3行代码即可完成写入日志
1 2 3 4 5 6 7 8 9 10 11 12 import logginglogging.basicConfig(filename='log.log' , format ='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s' , datefmt='%Y-%m-%d %H:%M:%S %p' , level=10 ) logging.debug('详细错误:debug' ) logging.info('详细错误:info' ) logging.warning('详细错误:warning' ) logging.error('详细错误:error' ) logging.critical('详细错误:critical' ) logging.log(11 ,'详细错误:自定义的log' )
以上代码即可写入到log.log文件中
写入结果如下
1 2 3 4 5 6 2019 -04-12 10 :34 :13 AM - root - DEBUG -日志: 详细错误:debug2019 -04-12 10 :34 :13 AM - root - INFO -日志: 详细错误:info2019 -04-12 10 :34 :13 AM - root - WARNING -日志: 详细错误:warning2019 -04-12 10 :34 :13 AM - root - ERROR -日志: 详细错误:error2019 -04-12 10 :34 :13 AM - root - CRITICAL -日志: 详细错误:critical2019 -04-12 10 :34 :13 AM - root - Level 11 -日志: 详细错误:自定义的log
这种写入方式弊端很大,其一中文编码有问题,我在pycharm中测试时gbk写入的,直接乱码另外logging.basicConfig只有这一句配置代码,并无编码的参数;其二我们有时候不可能只有一个日志文件,可能根据功能,根据用户角色拥有不同的日志文件,这种方法就不可行了,接下来直接上第二种:
1 2 3 4 5 6 7 8 9 10 11 import logginghandle = logging.FileHandler(filename='log1.log' , mode='a' , encoding='utf8' ) fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(module)s:%(message)s' ) handle.setFormatter(fmt) log1 = logging.Logger('s1' , level=10 ) log1.addHandler(handle) log1.error('我是自定义的错误' ) log1.log(12 , '我才是的呢啊哈哈哈哈' )
写入日志如下:
1 2019 -04-12 10 :38 :56 ,530 - s1 - ERROR - 2019 -04-12 10 :38 :56 ,530 - s1 - Level 12 -
此种方法既解决了中文乱码的问题,又解决了多日志文件的问题。
其实在此基础上我们可以扩展下日志内容,毕竟直接写入错误内容,分析日志的时候并不能很直观的知道哪个文件,甚至哪行代码出现了错误,此时我们可以借助traceback模块
1 2 3 4 5 6 7 8 9 10 11 12 13 traceback handle2 = logging.FileHandler(===) fmt = logging.Formatter() handle2.setFormatter(fmt) log2 = logging.Logger(=) log2.addHandler(handle2) try : name except Exception: error_info = traceback.format_exc() log2.error(error_info)
写入日志内容如下
1 2 3 2019 -04-12 10 :43 :50 ,477 - s2 - ERROR - Traceback (most recent call last): File "E:/site/python/.py" , line 46 , in name NameError: name 'name' is not defined
这样很详细的将错误行也给写入到了日志中,选择哪种方法还是要看自己需求