python logging类库使用例子
作者:junjie 发布时间:2023-10-31 11:17:11
一、简单使用
def TestLogBasic():
import logging
logging.basicConfig(filename = 'log.txt', filemode = 'a', level = logging.NOTSET, format = '%(asctime)s - %(levelname)s: %(message)s')
logging.debug('this is a message')
logging.info("this is a info")
logging.disable(30)#logging.WARNING
logging.warning("this is a warnning")
logging.critical("this is a critical issue")
logging.error("this is a error")
logging.addLevelName(88,"MyCustomError")
logging.log(88,"this is an my custom error")
try:
raise Exception('this is a exception')
except:
logging.exception( 'exception')
logging.shutdown()
TestLogBasic()
说明:(此实例为最简单的用法,用来将log记录到log文件中)
1)logging.basicConfig()中定义默认的log到log.txt,log文件为append模式,处理所有的level大于logging.NOTSET的logging,log的格式定义为'%(asctime)s - %(levelname)s: %(message)s';
2)使用logging.debug()...等来log相应level的log;
3)使用logging.disable()来disable某个logging level;
4)使用logging.addLevelName增加自定义的logging level;
5)使用logging.log来log自定义的logging level的log;
输出的text的log如下:
2011-01-18 10:02:45,415 - DEBUG: this is a message
2011-01-18 10:02:45,463 - INFO: this is a info
2011-01-18 10:02:45,463 - CRITICAL: this is a critical issue
2011-01-18 10:02:45,463 - ERROR: this is a error
2011-01-18 10:02:45,463 - MyCustomError: this is an my custom error
2011-01-18 10:02:45,463 - ERROR: exception
Traceback (most recent call last):
File "testlog.py", line 15, in TestLogBasic
raise Exception('this is a exception')
Exception: this is a exception
二、logging的level
#logging level
#logging.NOTSET 0
#logging.DEBUG 10
#logging.INFO 20
#logging.WARNING 30
#logging.ERROR 40
#logging.CRITICAL 50
logging的level对应于一个int,例如10,20...用户可以自定义logging的level。
可以使用logging.setLevel()来指定要处理的logger级别,例如my_logger.setLevel(logging.DEBUG)表示只处理logging的level大于10的logging。
三、Handlers
Handler定义了log的存储和显示方式。
NullHandler不做任何事情。
StreamHandler实例发送错误到流(类似文件的对象)。
FileHandler实例发送错误到磁盘文件。
BaseRotatingHandler是所有轮徇日志的基类,不能直接使用。但是可以使用RotatingFileHandler和TimeRotatingFileHandler。
RotatingFileHandler实例发送信息到磁盘文件,并且限制最大的日志文件大小,并适时轮徇。
TimeRotatingFileHandler实例发送错误信息到磁盘,并在适当的事件间隔进行轮徇。
SocketHandler实例发送日志到TCP/IP socket。
DatagramHandler实例发送错误信息通过UDP协议。
SMTPHandler实例发送错误信息到特定的email地址。
SysLogHandler实例发送日志到UNIX syslog服务,并支持远程syslog服务。
NTEventLogHandler实例发送日志到WindowsNT/2000/XP事件日志。
MemoryHandler实例发送日志到内存中的缓冲区,并在达到特定条件时清空。
HTTPHandler实例发送错误信息到HTTP服务器,通过GET或POST方法。
NullHandler,StreamHandler和FileHandler类都是在核心logging模块中定义的。其他handler定义在各个子模块中,叫做logging.handlers。
当然还有一个logging.config模块提供了配置功能。
四、FileHandler + StreamHandler
def TestHanderAndFormat():
import logging
logger = logging.getLogger("simple")
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler("simple.log")
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)
# "application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")
TestHanderAndFormat()
说明:(此实例同时使用FileHandler和StreamHandler来实现同时将log写到文件和console)
1)使用logging.getLogger()来新建命名logger;
2)使用logging.FileHandler()来生成FileHandler来将log写入log文件,使用logger.addHandler()将handler与logger绑定;
3)使用logging.StreamHandler()来生成StreamHandler来将log写到console,使用logger.addHandler()将handler与logger绑定;
4)使用logging.Formatter()来构造log格式的实例,使用handler.setFormatter()来将formatter与handler绑定;
运行结果
simple.txt
2011-01-18 11:25:57,026 - simple - DEBUG - debug message
2011-01-18 11:25:57,072 - simple - INFO - info message
2011-01-18 11:25:57,072 - simple - WARNING - warn message
2011-01-18 11:25:57,072 - simple - ERROR - error message
2011-01-18 11:25:57,072 - simple - CRITICAL - critical message
console
2011-01-18 11:25:57,072 - simple - ERROR - error message
2011-01-18 11:25:57,072 - simple - CRITICAL - critical message
五、RotatingFileHandler
def TestRotating():
import glob
import logging
import logging.handlers
LOG_FILENAME = 'logging_rotatingfile_example.out'
# Set up a specific logger with our desired output level
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=20, backupCount=5)
my_logger.addHandler(handler)
# Log some messages
for i in range(20):
my_logger.debug('i = %d' % i)
# See what files are created
logfiles = glob.glob('%s*' % LOG_FILENAME)
for filename in logfiles:
print(filename)
TestRotating()
说明:
RotatingFileHandler指定了单个log文件的size的最大值和log文件的数量的最大值,如果文件大于最大值,将分割为多个文件,如果log文件的数量多于最多个数,最老的log文件将被删除。例如此例中最新的log总是在logging_rotatingfile_example.out,logging_rotatingfile_example.out.5中包含了最老的log。
运行结果:
logging_rotatingfile_example.out
logging_rotatingfile_example.out.1
logging_rotatingfile_example.out.2
logging_rotatingfile_example.out.3
logging_rotatingfile_example.out.4
logging_rotatingfile_example.out.5
六、使用fileConfig来使用logger
import logging
import logging.config
logging.config.fileConfig("logging.conf")
# create logger
logger = logging.getLogger("simpleExample")
# "application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")
logging.conf文件如下:
[loggers]
keys=root,simpleExample
[handlers]
keys=consoleHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=
运行结果:
2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
2005-03-19 15:38:55,979 - simpleExample - INFO - info message
2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
猜你喜欢
- python图像爬虫包 最近在做一些图像分类的任务时,为了扩充我们的数据集,需要在搜索引擎下爬取额外的图片来扩充我们的训练集。搞人工智能真的
- 获取数据(四种方式)1. url: 需要正则去匹配 url(r'^index/(num)/$
- function checkPhoto(fnUpload) { var filename = fnUpload.value; alert(f
- 很多人在使用AJAX调用别人站点内容的时候,JS会提示"没有权限"错误,这是XMLHTTP组件的限制-安全起见禁止访问非
- Selenium一、简介selenium是一个用于Web应用自动化程序测试的工具,测试直接运行在浏览器中,就像真正的用户在操作一样selen
- 前言:本篇博客要采集的站点:【看历史,通天下-历史剧网】目标数据是该站点下的热门历史事件,列表页分页规则如下所示:http://www.li
- Python中and、or是Python中的逻辑运算符,它们的用法如何呢?and:在Python 中,and 和 or 执行布尔逻辑演算,如
- 本文实例为大家分享了js实现全选取消效果的具体代码,供大家参考,具体内容如下<!DOCTYPE html><html la
- 一个朋友给她的朋友买礼物。撕心裂肺、绞尽脑汁。最后蹦出来一个主意:“送打火机”我不知道小妞们通过哪的投票,就这么断定男人都喜欢打火机。导致一
- 本文实例讲述了Python变量、数据类型、数据类型转换相关函数用法。分享给大家供大家参考,具体如下:python变量的使用不需要进行类型声明
- //-------------------------------------------- // 删除千分点。 //-----------
- 本文实例主要实现给出任意字符串,获取字符串中某字符的位置以及出现的总次数。实现该功能代码的时候可以使用函数enumerate来将字符串分离成
- 本文实例讲述了php文件上传类。分享给大家供大家参考,具体如下:/**$file=new class_file($file_array,&q
- 之前在豆瓣上听到有友邻在抱怨卓越的配送速度慢得跟蜗牛一样,超过配送时间期限几天还没送到,当时不太相信,因为此前在卓越网上购买的物品基本上是在
- Selenium简介Selenium是一个用于测试网站的自动化测试工具,支持各种浏览器包括Chrome、Firefox、Safari等主流界
- python中eval和int的区别是什么?下面给大家介绍一下:1.eval()函数eval(<字符串>)能够以Python表达
- 在本篇文章中,我们将介绍回归树及其基本数学原理,并从头开始使用Python实现一个完整的回归树模型。为了简单起见这里将使用递归来创建树节点,
- sql2000的服务器版本是8.0,sql2005是9.0首先要读安装必须配置(见后记)1.我是先装2000的,安装好后打上sp4补丁,(s
- 本文实例讲述了Python进程的通信Queue、Pipe。分享给大家供大家参考,具体如下:内容相关:概念:进程的通信Queue:创建与使用P
- 批量创建文件其实很简单,只需要按照需要创建写文件、写完关闭当前写文件、创建新的写文件、写完关闭当前文件、、、不断循环即可,以下是一个简单例子