Python logging管理不同级别log打印和存储实例

yipeiwu_com6年前Python基础

Python内置模块logging管理不同级别log打印和存储,非常方便,从此告别了使用print打桩记录,我们来看下logging的魅力吧

import logging 
 
logging.basicConfig(level = logging.DEBUG, 
          format = '%(asctime)s %(filename)s[line:%(lineno)d]%(levelname)s %(message)s', 
          datefmt = '%a, %d %b %Y %H:%M:%S', 
          filename = './logcheck.log', 
          filemode = 'w') 
 
############################################################################### 
#define one StreamHandler, set the log mode 
console = logging.StreamHandler() 
console.setLevel(logging.INFO) 
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') 
console.setFormatter(formatter) 
logging.getLogger('').addHandler(console) 
############################################################################### 
 
filePath = r'C:\ddms.bat' 
 
logging.error('Open file failed!') 
logging.warn('sort mode disabled') 
logging.debug('%s' % filePath) 
logging.info('xml file generated successfully!') 

运行结果:

root    : ERROR  Open file failed! 
root    : WARNING sort mode disabled 
root    : INFO   xml file generated successfully! 

总结

以上就是本文关于Python logging管理不同级别log打印和存储实例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

python简单实现操作Mysql数据库

用python编写数据库的代码很方便,但是如果不想自己写sql语句,其实还有更多的讨巧办法。使用webpy的db库就是不错的一个选择。当然为了使用webpy的db,之前你还需要安装MyS...

zbar解码二维码和条形码示例

复制代码 代码如下:#!/usr/bin/env python# coding: u8import osimport zbarimport Imageimport urllibimpor...

利用Pycharm断点调试Python程序的方法

利用Pycharm断点调试Python程序的方法

1.代码 准备没有语法错误的Python程序: #!/usr/bin/python import numpy as np class Network: def __init__(...

python+opencv+caffe+摄像头做目标检测的实例代码

python+opencv+caffe+摄像头做目标检测的实例代码

首先之前已经成功的使用Python做图像的目标检测,这回因为项目最终是需要用摄像头的, 所以实现摄像头获取图像,并且用Python调用CAFFE接口来实现目标识别 首先是摄像头请选择支持...

使用Python调取任意数字资产钱包余额功能

使用Python调取任意数字资产钱包余额功能

当我们的资产放在交易所的时候,可以通过链接交易所的API使用Python来监控余额。 那资产放在钱包的时候,如何来监控余额呢? 任何数字资产都可以使用区块浏览器来查询余额,那我们只要从此...