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打印和存储实例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

centos 安装Python3 及对应的pip教程详解

安装Python3 安装Python依赖: yum install openssl-devel bzip2-devel expat-devel gdbm-devel readline-d...

Python中矩阵创建和矩阵运算方法

Python中矩阵创建和矩阵运算方法

矩阵创建 1、from numpyimport *; a1=array([1,2,3]) a2=mat(a1) 矩阵与方块列表的区别如下: 2、data2=mat(ones((2,4)...

TensorFLow用Saver保存和恢复变量

本文为大家分享了TensorFLow用Saver保存和恢复变量的具体代码,供大家参考,具体内容如下 建立文件tensor_save.py, 保存变量v1,v2的tensor到checkp...

浅谈Django中的数据库模型类-models.py(一对一的关系)

如下所示: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import...

分数霸榜! python助你微信跳一跳拿高分

前言 最近微信的跳一跳很火,大家看到排行榜上几百上千的分数,再看看自己百分左右的分数肯定很难过,我手残怪我吗?没关系,如果你跟着我来,也能让你分数霸榜。 原理 首先大家是有一个直观感受,...