python3日志模块

在程序运行的时候,为了跟踪执行过程中的数据,及时修改错误的代码,一般都会生成一些程序日志,最基本的就是print,但是这个函数有很大的局限性,所以需要用到logging这个模块,该模块定义了为应用程序和库实现灵活事件记录系统的函数和类。

1.日志等级:

print()             这是程序自带的函数,用于输出到控制台

logging.debug()     报告在程序正常运行期间发生的事件

logging.info()      报告在程序正常运行期间发生的事件

logging.warning()   发出有关特定运行时事件的警告

logging.error()     报告抑制错误而不引发异常

logging.critical()  报告抑制错误而不引发异常

 

2.什么时候使用:

DEBUG   ->  详细信息,通常仅在诊断问题时才有意义,是最低级别

INFO    ->  确认事情按预期工作,第二低级别

WARNING ->  表明发生了意外情况,或表明在不久的将来出现了一些问题(例如“最终数据非理想值”)。该软件仍在按预期工作

ERROR   ->  由于更严重的问题,该软件无法执行某些功能。

CRITICAL    ->  严重错误,表明程序本身可能无法继续运行,最高级别日志。

 

注意:默认级别为WARNING,这意味着将仅跟踪此级别及更高级别的事件,除非日志包已配置为执行其他操作。

 

3.简单使用

import logging

logging.warning('Watch out!')  # will print a message to the console

logging.info('I told you so')  # will not print anything

 

解释:这里只输出warning部分的日志,因为默认是warning级别,低于该级别不输出

 

4.输出到日志文件

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

 

解释:定义一个文件(filename='example.log'),并定义级别为DEBUG(level=logging.DEBUG),该级别为最低级别,所以所有日志全部输出

basicConfig的默认格式是:severity:logger name:message

 

5.写入模式(覆盖、追加)

logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)

logging.basicConfig(filename='example.log', filemode='a', level=logging.DEBUG)

 

注:如果不设置写入模式,多次运行上述脚本,则连续运行的消息将附加到文件example.log中

 

6.从多个模块记录

脚本示例:

# 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.py,日志输出到:myapp.log,内容如下:

INFO:root:Started

INFO:root:Doing something

INFO:root:Finished

 

7.记录变量数据

注:变量数据仅支持字符串格式

import logging

logging.warning('%s before you %s', 'Look', 'leap!')

 

8.更改显示消息的格式

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

 

9.增加时间显示

import logging

logging.basicConfig(format='%(asctime)s %(message)s')

logging.warning('is when this event was logged.')

 

输出结果:2019-01-06 15:54:53,182 is when this event was logged.

 

10.更丰富的时间显示

import logging

logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')

logging.warning('is when this event was logged.')

 

 

11.比较成熟的写法

import logging

logger = logging.getLogger(__name__)

logger.setLevel(level = logging.INFO)

handler = logging.FileHandler("log.txt")

handler.setLevel(logging.INFO)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

handler.setFormatter(formatter)

logger.addHandler(handler)

 

logger.info("Start print log")

logger.debug("Do something")

logger.warning("Something maybe fail.")

logger.info("Finish")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值