学习 python logging(1): 基本用法

栏目: Python · 发布时间: 6年前

内容简介:日志在编程中是十分重要,可以帮助我们跟踪事件、应用的运行情况、查问题、统计数据等。在记录日志时,通常表示某件事情的发生。这五个方法的严重等级依次增加,对应关系:

简介

日志在编程中是十分重要,可以帮助我们跟踪事件、应用的运行情况、查问题、统计数据等。在记录日志时,通常表示某件事情的发生。

python 中 logging 模块提供记录的基础方法:

debug , info , warning , error , critical

这五个方法的严重等级依次增加,对应关系:

LEVEL value used time
DEBUG 10 分析问题的时候
INFO 20 确定程序是否在按预想的运行
WARNING 30 程序运行超出预设,但是,程序还可以运行
ERROR 40 有严重的错误,程序无法正常运行一些方法
CRITICAL 50 一个严重的错误,导致程序无法继续运行了

默认等级为 WARNING ,只有高于你所指定的等级,才会被日志模块输出。

基本使用

  1. 直接打印

    import logging
       logging.info('info log')
       logging.warning('warning log')

    运行之后看到的是 WARNING:root:warning log ,因为默认等级是 WARNING , 所以 `info

    log` 是不会显示的。

  2. 将日志记录到文件中

    import logging
    logging.basicConfig(filename='logging_example.log',level=logging.DEBUG)
    logging.debug('Write debug to file')
    logging.info('Write info to file')
    logging.warning('Write warning to file')

    可以在日志文件中看到:

    DEBUG:root:Write debug to file
    INFO:root:Write info to file
    WARNING:root:Write warning to file
    DEBUG:root:Write debug to file
    INFO:root:Write info to file
    WARNING:root:Write warning to file

参考:

  1. https://docs.python.org/3/how...
  2. https://docs.python.org/3/lib...
  3. https://docs.python.org/3/how...

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

A Byte of Python

A Byte of Python

Swaroop C H / Lulu Marketplace / 2008-10-1 / USD 27.98

'A Byte of Python' is a book on programming using the Python language. It serves as a tutorial or guide to the Python language for a beginner audience. If all you know about computers is how to save t......一起来看看 《A Byte of Python》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换