1.简单的将日志打印到屏幕

import logginglogging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')屏幕上打印:
WARNING:root:This is warning message

默认情况下,logging将日志打印到屏幕,日志级别为WARNING;
日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,当然也可以自己定义日志级别。

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

import logginglogging.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函数各参数:
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.将日志同时输出到文件和屏幕

import logginglogging.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)
#################################################################################################logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')屏幕上打印:
root        : INFO     This is info message
root        : 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

4.logging之日志回滚

import logging
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有一个日志处理的主对象,其它处理方式都是通过addHandler添加进去的。
logging的几种handle方式如下:

logging.StreamHandler: 日志输出到流,可以是sys.stderr、sys.stdout或者文件
logging.FileHandler: 日志输出到文件
日志回滚方式,实际使用时用RotatingFileHandler和TimedRotatingFileHandler
logging.handlers.BaseRotatingHandler
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服务器

由于StreamHandler和FileHandler是常用的日志处理方式,所以直接包含在logging模块中,而其他方式则包含在logging.handlers模块中,
上述其它处理方式的使用请参见python2.5手册

#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=

上例3:

import logging
import logging.configlogging.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')

上例4:

import logging
import logging.configlogging.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')

转载于:https://www.cnblogs.com/alan-babyblog/p/5211451.html

Python logging模块详解相关推荐

  1. python logging模块详解_python logging模块使用总结

    目录 logging模块 日志级别 CRITICAL 50 ERROR 40 WARNING 30 INFO 20 DEBUG 10 logging.basicConfig()函数中的具体参数含义 f ...

  2. python time模块详解

    python time模块详解 转自:http://blog.csdn.net/kiki113/article/details/4033017 python 的内嵌time模板翻译及说明    一.简 ...

  3. Python—requests模块详解

    Python-requests模块详解 来源(博客园@小L小 ):Python-requests模块详解

  4. python re正则_正则表达式+Python re模块详解

    正则表达式(Regluar Expressions)又称规则表达式,在代码中常简写为REs,regexes或regexp(regex patterns).它本质上是一个小巧的.高度专用的编程语言. 通 ...

  5. python cx_oracle模块详解_cx_Oracle模块详解

    1.安装cx_Oracle模块 1-1.环境准备: 1-1-1.oracle client最小安装 instantclient-sqlplus-linux.x64-11.2.0.4.0 instant ...

  6. Python shutil 模块详解

    Python shutil 模块详解 1.模块介绍 2.copytree 示例 3.move 示例 1.模块介绍 import shutil# copy data from file-like obj ...

  7. python中logging模块详解_python logging日志模块详解

    logging 日志模块详解 用Python写代码的时候,在想看的地方写个print xx 就能在控制台上显示打印信息,这样子就能知道它是什么了,但是当我需要看大量的地方或者在一个文件中查看的时候,这 ...

  8. Python timeit 模块详解(准确测量小段代码的执行时间)

    timeit 模块详解 -- 准确测量小段代码的执行时间 timeit 模块提供了测量 Python 小段代码执行时间的方法.它既可以在命令行界面直接使用,也可以通过导入模块进行调用.该模块灵活地避开 ...

  9. Python Tkinter模块详解(后续持续补充)

    声明:该文章是个人学习中写的,目的是总结及当作工具参考,有一定的借鉴成分,后续若有新发现则补充 目录 Tkinter简介 创建组件基本语法 Tkinter组件汇总 Variable 类 常见参数详解 ...

最新文章

  1. 为什么使用HashMap需要重写hashcode和equals方法_为什么要重写hashcode和equals方法?你能说清楚了吗...
  2. python map reduce filter_Python map, reduce, filter和sorted
  3. java比较语句常犯错误和三个数比较大小
  4. 【机器学习】这次终于彻底理解了奇异值分解(SVD)原理及应用
  5. 卡塔尔大学发布全景分割 2021 年最新综述
  6. k8s pod和service的关系及常用service类型:ClusterIP/NodePort/LoadBalancer
  7. HH SaaS电商系统的采购功能模块设计
  8. LeetCode 1263. 推箱子(BFS+DFS / 自定义哈希set)
  9. mysql导出表结构_mysql导入导出表结构及表数据及执行sql文件
  10. Anaconda下如何创建python2等虚拟环境
  11. 列举php magic方法,如何在PHP中實現__isset()魔術方法?
  12. Python包管理整理:setuptool管理python相关的包
  13. 软件测试文档模板 ppt,软件工程课件:软件测试用例文档模板.doc
  14. matlab进化树的下载,MEGA官网下载|MEGA进化树 V7.0.26 官方最新版 下载_当下软件园_软件下载...
  15. C# int和byte[]之间的互转
  16. 全球十大程序化交易系统 ( 有源码 )
  17. 【Matplotlib绘制图像目录】Python数据可视化之美
  18. python2在线编译器_C/C++/Python在线编译器
  19. Unity LineRenderer 画运动轨迹
  20. 百度地图画出手机GPS行驶轨迹——Web端

热门文章

  1. HTTP Server Error 500 内部服务器错误
  2. php 自带 web server 如何重写 rewrite .htaccess
  3. android 4.4以上能够实现的沉浸式状态栏效果
  4. C#利用Socket实现客户端之间直接通信
  5. 分析纯文本外链在SEO优化方面的作用
  6. H3C 5510 交换机DHCP设置
  7. 51中断编程c语言,[新人求指教]51C语言编程可否用中断令循环结束提早结束
  8. SpringBoot入门 (一) HelloWorld
  9. 独家 | 蚂蚁金服TRaaS技术风险防控平台解密
  10. C语言程序设计第三次作业