Python Logging 官方教程

LevelWhen it’s used
DEBUGDetailed information, typically of interest only when diagnosing problems.
INFOConfirmation that things are working as expected.
WARNINGAn 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.
ERRORDue to a more serious problem, the software has not been able to perform some function.
CRITICALA serious error, indicating that the program itself may be unable to continue running.

定义了5个等级,这些都是自己来判断的,默认是warning

日志输出等级

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

输出结果是

WARNING:root:Watch out!

因为默认的level是warning,所以info的日志并没有被输出,以此我们可以来控制哪些要输出,哪些不要输出.
例如:
我们设置level为ERROR,则在程序遇到WARNING时,日志是不会起作用的,而在遇到ERROR时,日志则会输出logging.error()所输入参数的内容

将日志输出为文件

通过basicConfig来控制输出文件名,和level

import logging
logging.basicConfig(filename='example.log',filemode='w',level=logging.INFO) # 注意INFO必须大写,filemode是选择追加还是覆盖文件
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

打开example.log文件可以看到输出的结果,由于levelINFO所以DEBUG级别灭有输出:

INFO:root:So should this
WARNING:root:And this, too

多模块日志

只要在一处设置basicConfig即可,logging是全局的

主模块

# myapp.py
import logging
import mylib

def main():
    logging.basicConfig(filename='myapp.log', level=logging.INFO)
    logging.info('Started')
    mylib.do_something()
    logging.info('Finished')

if __name__ == '__main__':
    main()

子模块

# mylib.py
import logging

def do_something():
    logging.info('Doing something')

输出结果myapp.log,主模块和子模块都输出到同一个文件中:

INFO:root:Started
INFO:root:Doing something
INFO:root:Finished

日志变量

日志变量使用%-style风格

import logging
logging.warning('%s before you %s', 'Look', 'leap!')  # 第一个%s指代look,第二个%s指代leap

改变日志的输出格式

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')

输出结果是,按照’%(levelname)s:%(message)s’的格式,%与s中间的括号levelnamelogging模块内置的变量,可以在LogRecord attributes查询,
其中message就是debug,info输入的参数

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

进阶教程

模块名称
Loggers
Handlers控制日志的输出
Filters过滤输出的内容
Formatters输出的格式

可以给logger类取名字,可以通过这样查看是日志出于哪个模块.
所有的logger都继承于名字为root的logger

logger = logging.getLogger(__name__)

可以通过handler将日志输出到不同的地方,比如文件,HTTP,email,sockeets,queues等.
默认情况下,日志讲输出到os.stderr,可以使用basicConfig控制输出到文件

logger

logger对象有两类方法,一类是配置方法,一类是消息方法

配置方法描述
Logger.setLevel()
Logger.addHandler()
Logger.removeHandler()
Logger.addFilter()
Logger.removeFilter()
消息方法描述
Logger.debug()
Logger.info()
Logger.warning()
Logger.error()
Logger.critical()
Logger.exception()比Logger.error更详细
Logger.log()参数指定level,太冗长,推荐上面的便利方法
getLogger()获得指定名称的logger对象,foo.bar,foo.bam都继承于foo,而所有的都继承于root.等级继承于父类

handler

可以通过handler将不同的日志信息输出到不同的地方,比如讲所有的日志信息放在一个文件里,讲error信息输出到标准输出,讲critical信息发送邮件

handler描述
StreamHandler将消息发送到流
FileHandler将消息发送到文件
BaseRotatingHandler
RotatingFileHandler
TimedRotatingFileHandler
SocketHandler发送到socket,tcp
DatagramHandlerudp
SMTPHandler发送邮件
SysLogHandler
NTEventLogHandler
MemoryHandler
HTTPHandler发送到http,get/post
WatchedFileHandler
QueueHandler
NullHandler

formatters

configuring logging

参考:
https://docs.python.org/3/howto/logging.html#logging-basic-tutorial
https://www.cnblogs.com/louis-w/p/8567434.html
https://www.cnblogs.com/jackadam/p/9228116.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值