前言

在python程序中,出于调试监测或者追踪(track)的目的,一般会在关键的部位加print语句来输出监测的变量值,但对于复杂的程序来讲,这样的调试手段就远远不够了,这也是logging库存在的意义,也有必要进行学习一番。

Logging 提供了一套函数组来满足简单记录的需求,比如debug(),info(),error(),和critical().

这些个函数其实是有层次的,这也是logging的重要理念之一,也就是可以设置一定的阈值,当低于该阈值时候,不管它,当等于或者高于该阈值时,才进行记录。

Level When it’s used
DEBUG Detailed information, typically of interest only when diagnosing problems.
INFO Confirmation that things are working as expected.
WARNING An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.
ERROR Due to a more serious problem, the software has not been able to perform some function.
CRITICAL A serious error, indicating that the program itself may be unable to continue running.

注意:上表的层次就是由低到高。

默认的level是WARNING,追踪事件的方式多种多样,最简单的就是直接输出到console,另一个常见的方式是写入文件中。

初级应用

初级应用就是简单的通过logging.basicConfig进行简单的设置(或者不设置,用默认的),然后直接用logging.debug(),logging.info(),logging.warning()等输出。

小例子

import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything

outputs:

WARNING:root:Watch out!

因为默认层是WARINING,所以logging.info()不输出。

Logging 到文件

import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

outputs:

DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too

改变输出的格式

import logging
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this, too')

outputs:

DEBUG:This message should appear on the console
INFO:So should this
WARNING:And this, too

这里注意'root'不见了,因为我们重新设置了输出格式,格式中只有levelname和messages。

显示时间

import logging
logging.basicConfig(format='%(asctime)s %(message)s')
logging.warning('is when this event was logged.')

outputs:

2020-09-13 14:45:26,252 is when this event was logged

高级用法

logging实际上采用了模块化的方法,提供了几个组件:loggers,handlers,filters,和formatters.

官网是这样定义几个组件的作用的:

  • Loggers expose the interface that application code directly uses.
  • Handlers send the log records (created by loggers) to the appropriate destination.
  • Filters provide a finer grained facility for determining which log records to output.
  • Formatters specify the layout of log records in the final output.

被追踪的信息就是在Logger,Handler,Filter,Formatter之间传递:

首先Logging是通过调用Logger类实例的方法进行的,每个实例都有个名称,用'.'来作为命名空间的继承关系。

常用的对于module-level的logger的创建方法是

logger = logging.getLogger(__name__)

然后需要为log message设定destination,比如file,http get/post,email, sockets,queue等。destination是通过handler来确定的。默认是没有任何的destination的,可通过basicConfig()来进行简单的设置:

装配

有3种装配方法:

  • 用logger,handler,filter,formatter对象的装配方法进行装配
import logging

# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG) # create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG) # create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # add formatter to ch
ch.setFormatter(formatter) # add ch to logger
logger.addHandler(ch) # 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
  • 用fileConfig()方法

logging.conf文件

[loggers] #声明logger
keys=root,rotateFileDemo #键值对
[handlers] #声明handler
keys=consoleHandler,rotateHandler #键值对
[formatters] #声明formatter
keys=simpleFormatter#键值对 [logger_root] #对于root的配置,必须是looger_xxx的形式
level=DEBUG
handlers=consoleHandler [logger_rotateFileDemo]#对于rotateFileDemo的配置
level=DEBUG
handlers=rotateHandler
qualname=rotateDemo #logger名称,应用程序通过 logging.getLogger获取。对于不能获取的名称,记录到root模块。
propagate=0 # 是否继承父类的log 信息,0:否 1:是.其父类这里是root [handler_consoleHandler] #对于consoleHandler的配置,必须是handler_xxx的形式
class=StreamHandler #类
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,) #类参数 [handler_rotateHandler]
class=handlers.RotatingFileHandler #这里注意是 handlers.RotatingfileHandler
level=DEBUG
formatter=simpleFormatter
args=('app.log','a',1024,5) #该类的参数 [formatter_simpleFormatter] #simpleFormatter的定义及配置
format=%(asctime)s-%(name)s-%(levelname)s-%(message)s

loggingDemo.py

import logging
import logging.config
import time
logging.config.fileConfig('logging.conf')
logger=logging.getLogger('rotateDemo') while True:
logger.info('info message')
time.sleep(0.1)

对于RotatingFileHandler,这里args=('app.log','a',1024,5) ,即记录到app.log中,当超过1024 bytes后,分别备份为app.log.01,app.log.02,app.log.03,app.log.04,app.log.05,然后再有的话不再增加。

  • 运用dictConfig()进行配置

传入dictConfig()的dict,必须包含以下的键:

  • version,当前唯一合法值是1,主要考虑到向后兼容性。
  • formatters
  • filters
  • handlers
    • class(强制必须有)
    • level(可选)
    • formatter(可选)
    • filter(可选)
  • loggers
    • level(可选)
    • propagare(可选)
    • filters(可选)
    • handlers(可选)
  • root,设定root logger。
  • incremental,配置是否解释为在已经存在的配置上增加,默认为False,意思就是设定的配置将代替原来的配置。
  • disable_existing_loggers:是否使得已经存在loggers失效,默认为True,如果incremental 是True,则忽略该项。

例子:

import logging
import logging.config
LOGGING={
'version':1,
'formatters':{
'simple':{
'format':'[%(asctime)s]%(levelname)s%(message)s',
'datefmt':'%Y-%m-%d %H:%M:%S'
},
'verbose':{
'format':'[%(asctime)s]%(levelname)s[%(name)s.%(funcName)s%(lineno)d%(message)s',
'datefmt':'%Y-%m-%d %H:%M:%S'
}
},
'handlers':{
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
'formatter':'simple'
},
'development_logfile':{
'level':'DEBUG',
'class':'logging.FileHandler',
'filename':'test.log',
'formatter':'verbose', },
'production_logfile':{
'level':'ERROR',
'class':'logging.handlers.RotatingFileHandler',
'filename':'test_production.log',
'maxBytes':1024,
'backupCount':3,
'formatter':'simple'
},
'dba_logfile':{
'level':'DEBUG',
'class':'logging.handlers.WatchedFileHandler',
'filename':'test_dba.log',
'formatter':'simple'
},
},
'root':{
'level':'DEBUG',
'handlers':['console'],
},
'loggers':{
'coffee':{
'handlers':['development_logfile'],
# 'propagare':0,
# 'qualname':'coffee'
},
'dba':{
'handlers':['dba_logfile']
}
} } logging.config.dictConfig(LOGGING)
logger=logging.getLogger('coffee')
logger.info('dictlogger info')

Python标准库学习之logging的更多相关文章

  1. python标准库学习-SimpleHTTPServer

    这是一个专题 记录学习python标准库的笔记及心得 简单http服务 SimpleHTTPServer 使用 python -m SimpleHTTPServer 默认启动8000端口 源码: &q ...

  2. Python标准库学习之zipfile模块

    ZipFile模块里有两个非常重要的class, 分别是 ZipFile和ZipInfo. ZipFile是主要的类,用来创建和读取zip文件,而ZipInfo是存储的zip文件的每个文件的信息的. ...

  3. python标准库学习-ftplib

    源码: """An FTP client class and some helper functions. Based on RFC 959: File Transfer ...

  4. 【python标准库学习】thread,threading(一)多线程的介绍和使用

    在单个程序中我们经常用多线程来处理不同的工作,尤其是有的工作需要等,那么我们会新建一个线程去等然后执行某些操作,当做完事后线程退出被回收.当一个程序运行时,就会有一个进程被系统所创建,同时也会有一个线 ...

  5. python标准库00 学习准备

    Python标准库----走马观花 python有一套很有用的标准库.标准库会随着python解释器一起安装在你的电脑上的.它是python的一个组成部分.这些标准库是python为你准备的利器,可以 ...

  6. Python标准库的学习准备

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! Python标准库是Python强大的动力所在,我们已经在前文中有所介绍.由于标准 ...

  7. Python 标准库一览(Python进阶学习)

    转自:http://blog.csdn.net/jurbo/article/details/52334345 写这个的起因是,还是因为在做Python challenge的时候,有的时候想解决问题,连 ...

  8. python第六天 函数 python标准库实例大全

    今天学习第一模块的最后一课课程--函数: python的第一个函数: 1 def func1(): 2 print('第一个函数') 3 return 0 4 func1() 1 同时返回多种类型时, ...

  9. Python标准库07 信号 (signal包,部分os包)

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 在了解了Linux的信号基础之后,Python标准库中的signal包就很容易学习 ...

  10. Python标准库——走马观花

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! Python有一套很有用的标准库(standard library).标准库会随着 ...

随机推荐

  1. autMan奥特曼机器人-autMan的PHP环境

    直装版请自行安装php环境. docker版本预置了php环境,如下图: 如果使用插件"test php"测试环境时,实时日志有报错如下: 可进入终端,输入两条命令 apk add ...

  2. Edge浏览器网站页面如何设置自动刷新

    1.浏览器设置 要在Edge浏览器中设置网站页面自动刷新,可以按照以下步骤操作: 打开Edge浏览器,进入你想要自动刷新的网站页面. 在地址栏上方点击"设置和更多选项"(三个水平点 ...

  3. 洛谷P10112 [GESP202312 八级] 奖品分配 题解

    题目传送门. 看了题解才发现我有多蠢. 我的做法真是唐完了. 在此之前请学习扩展欧几里得定理和扩展欧几里得定理求逆元. 发现奖品要么 \(N\) 个,要么 \(N+1\) 个,于是分类讨论,当奖品只有 ...

  4. git上传大文件!git push 报错 ! [remote rejected] main -> main (pre-receive hook declined) error_ failed to push some refs to 'xxx

    前言 今天在用git push项目的时候,出现了一个报错,记录一下解决方案,以后报同样的错误可以回来看. 错误信息 下面是git push的详细报错信息: 20866@DESKTOP-7R0VL04 ...

  5. 【由技及道】CI/CD的量子纠缠术:Jenkins与Gitea的自动化交响曲【人工智障AI2077的开发日志】

    摘要:当代码提交触发量子涟漪,当构建流水线穿越时空维度--欢迎来到自动化构建的十一维世界.本文记录一个未来AI如何用Jenkins和Gitea搭建量子纠缠式CI/CD管道,让每次代码提交都成为时空交响 ...

  6. 全面的C#/.NET/.NET Core面试宝典(永久免费)

    前言 C#/.NET/.NET Core相关技术常见面试题汇总,不仅仅为了面试而学习,更多的是查漏补缺.扩充知识面和大家共同学习.携手进步. 该知识库主要由自己平时学习和工作实践总结.网上优秀文章资料 ...

  7. nginx 禁止直接访问目录或文件

    前言 Nginx 默认是不允许列出整个目录的. 如需此功能,打开 nginx.conf 文件或你要启用目录浏览虚拟主机的配置文件,在 location server 或 http 段中加入 autoi ...

  8. go 结构体根据某个字段进行排序

    前言 在任何编程语言中,关乎到数据的排序都会有对应的策略,我们来看下 Golang 是怎样对数据进行排序,以及我们如何优化处理使用 go 排序 go 可以针对任何对象排序,虽然很多情况下是一个 sli ...

  9. jupyterhub nginx proxy pass----ipv6转ipv4实现内网穿透

    jupyterhub 很多人应该已经对jupyter和notebook已经有所了解了.如果是多人共享服务器的话,就需要用到jupyter的多用户版本jupyterhub.jupyterhub架构如图所 ...

  10. 安装卸载GNOME

    只需要三步:sudo yum -y groups install "GNOME Desktop"sudo systemctl set-default graphical.targe ...