Python内置模块logging用法实例分析


Posted in Python onFebruary 12, 2018

本文实例讲述了Python内置模块logging用法。分享给大家供大家参考,具体如下:

1、将日志直接输出到屏幕

import logging
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
# 默认情况下,logging将日志打印到屏幕,日志级别为WARNING;
#output====================================
# WARNING:root:This is warning message

2.通过logging.basicConfig函数对日志的输出格式及方式做相关配置

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='myapp.log',
        filemode='w')
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
#./myapp.log文件中内容为:
#Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message
#Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message
#Sun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message

logging.basicConfig参数:

#logging.basicConfig函数各参数:
filename: 指定日志文件名
filemode: 和file函数意义相同,指定日志文件的打开模式,'w'或'a'
format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:
    %(levelno)s:     打印日志级别的数值
    %(levelname)s:     打印日志级别名称
    %(pathname)s:     打印当前执行程序的路径,其实就是sys.argv[0]
    %(filename)s:     打印当前执行程序名
    %(funcName)s:     打印日志的当前函数
    %(lineno)d:     打印日志的当前行号
    %(asctime)s:     打印日志的时间
    %(thread)d:     打印线程ID
    %(threadName)s: 打印线程名称
    %(process)d:     打印进程ID
    %(message)s:     打印日志信息
datefmt:     指定时间格式,同time.strftime()
level:         设置日志级别,默认为logging.WARNING
stream:     指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略

3、将日志同时输出到多个Handler

先定义一个住handler,并使用addHander()添加到主handler,实现日志输出到多个handler.

a、同时输出到文件和屏幕

import logging
#设置一个basicConfig只能输出到一个Handler
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='myapp.log',
        filemode='w')
#定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象#
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
#输出到文件的log级别为debug,输出到stream的log级别为info
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

b、添加一个handler:输出到文件,并根据文件大小滚动存储

在a的基础上添加一个handler

from logging.handlers import RotatingFileHandler
#定义一个RotatingFileHandler,最多备份5个日志文件,每个日志文件最大10M
Rthandler = RotatingFileHandler('myapp.log', maxBytes=10*1024*1024,backupCount=5)
Rthandler.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
Rthandler.setFormatter(formatter)
logging.getLogger('').addHandler(Rthandler)

logging几种Handler类型:

logging.StreamHandler(默认):     日志输出到流,可以是sys.stderr、sys.stdout或者文件
logging.FileHandler:             日志输出到文件
logging.handlers.RotatingFileHandler    日志输出到文件,基于文件大小滚动存储日志
logging.handlers.TimedRotatingFileHandler    日志输出到文件,基于时间周期滚动存储日志
logging.handlers.SocketHandler:     远程输出日志到TCP/IP sockets
logging.handlers.DatagramHandler:      远程输出日志到UDP sockets
logging.handlers.SMTPHandler:          远程输出日志到邮件地址
logging.handlers.SysLogHandler:     日志输出到syslog
logging.handlers.NTEventLogHandler: 远程输出日志到Windows NT/2000/XP的事件日志
logging.handlers.MemoryHandler:     日志输出到内存中的制定buffer
logging.handlers.HTTPHandler:         通过"GET"或"POST"远程输出到HTTP服务器

4、通过配置文件配置logger

a、定义配置文件logger.conf

#logger.conf
###############################################
[loggers]
keys=root,example01,example02
[logger_root]
level=DEBUG
handlers=hand01,hand02
[logger_example01]
handlers=hand01,hand02
qualname=example01
propagate=0
[logger_example02]
handlers=hand01,hand03
qualname=example02
propagate=0
###############################################
[handlers]
keys=hand01,hand02,hand03
[handler_hand01]
class=StreamHandler
level=INFO
formatter=form02
args=(sys.stderr,)
[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form01
args=('myapp.log', 'a')
[handler_hand03]
class=handlers.RotatingFileHandler
level=INFO
formatter=form02
args=('myapp.log', 'a', 10*1024*1024, 5)
###############################################
[formatters]
keys=form01,form02
[formatter_form01]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt=%a, %d %b %Y %H:%M:%S
[formatter_form02]
format=%(name)-12s: %(levelname)-8s %(message)s
datefmt=

b、logging.config获取配置

import logging
import logging.config
logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example01")
logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')
import logging
import logging.config
logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example02")
logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Python实现从url中提取域名的几种方法
Sep 26 Python
Python中map和列表推导效率比较实例分析
Jun 17 Python
在Django的URLconf中进行函数导入的方法
Jul 18 Python
python3+PyQt5实现文档打印功能
Apr 24 Python
python 定时任务去检测服务器端口是否通的实例
Jan 26 Python
python调用其他文件函数或类的示例
Jul 16 Python
Python3爬虫中识别图形验证码的实例讲解
Jul 30 Python
五分钟学会怎么用python做一个简单的贪吃蛇
Jan 12 Python
Python字符串对齐方法使用(ljust()、rjust()和center())
Apr 26 Python
pytorch 6 batch_train 批训练操作
May 28 Python
Python常用配置文件ini、json、yaml读写总结
Jul 09 Python
Python可变集合和不可变集合的构造方法大全
Dec 06 Python
Request的中断和ErrorHandler实例解析
Feb 12 #Python
Python实现Kmeans聚类算法
Jun 10 #Python
Python request设置HTTPS代理代码解析
Feb 12 #Python
python实现聚类算法原理
Feb 12 #Python
python web.py开发httpserver解决跨域问题实例解析
Feb 12 #Python
python生成tensorflow输入输出的图像格式的方法
Feb 12 #Python
Flask解决跨域的问题示例代码
Feb 12 #Python
You might like
PHP中的正规表达式(一)
2006/10/09 PHP
遍历指定目录下的所有目录和文件的php代码
2011/11/27 PHP
PHP基于自定义类随机生成姓名的方法示例
2017/08/05 PHP
window.open 以post方式传递参数示例代码
2014/02/27 Javascript
jQuery实现隔行背景色变色
2014/11/24 Javascript
js实现可得到不同颜色值的颜色选择器实例
2015/02/28 Javascript
JavaScript是如何实现继承的(六种方式)
2016/03/31 Javascript
AngularJS压缩JS技巧分析
2016/11/08 Javascript
使用JS实现图片轮播的实例(前后首尾相接)
2017/09/21 Javascript
vue.js的computed,filter,get,set的用法及区别详解
2018/03/08 Javascript
vue采用EventBus实现跨组件通信及注意事项小结
2018/06/14 Javascript
详解使用React.memo()来优化函数组件的性能
2019/03/19 Javascript
将RGB值转换为灰度值的简单算法
2019/10/09 Javascript
浅谈layui 绑定form submit提交表单的注意事项
2019/10/25 Javascript
解决vue中的无限循环问题
2020/07/27 Javascript
Vue-router中hash模式与history模式的区别详解
2020/12/15 Vue.js
[09:37]DOTA2卡尔工作室 英雄介绍圣堂刺客篇
2013/06/13 DOTA
python 快速排序代码
2009/11/23 Python
Python实现去除代码前行号的方法
2015/03/10 Python
在Python中使用SimpleParse模块进行解析的教程
2015/04/11 Python
在Python中使用cookielib和urllib2配合PyQuery抓取网页信息
2015/04/25 Python
自动化Nginx服务器的反向代理的配置方法
2015/06/28 Python
python使用scrapy发送post请求的坑
2018/09/04 Python
Python查找数组中数值和下标相等的元素示例【二分查找】
2019/02/13 Python
Python tkinter三种布局实例详解
2020/01/06 Python
django Layui界面点击弹出对话框并请求逻辑生成分页的动态表格实例
2020/05/12 Python
COS美国官网:知名服装品牌
2019/04/08 全球购物
阿联酋最好的手机、电子产品和家用电器网上商店:Eros Digital Home
2020/08/09 全球购物
决定成败的关键——创业计划书
2014/01/24 职场文书
回门宴父母答谢词
2014/01/26 职场文书
企业标语大全
2014/07/01 职场文书
八年级英语教学计划
2015/01/23 职场文书
自荐信模板大全
2015/03/27 职场文书
离婚代理词范文
2015/05/23 职场文书
创业计划书之美容店
2019/09/16 职场文书
go类型转换及与C的类型转换方式
2021/05/05 Golang