pythonlogging基础手册

原文: http://docs.python.org/2.7/howto/logging.html#logging-basic-tutorial


1.When to use logging

logging是跟踪运行状态,开发者加上log来表明事件确实执行了。每个事件都有描述性的信息,同时也可以包含变量数据(数据对每个发生事件来说都不一样),时间都有优先级,叫做level或severity。

logging提供一系列简单的方法来使用, debug(), info(), warning(), error() and critical().什么时候使用logging就要参考下表了。对于不同的任务,使用最好的工具。

1.控制台展示输出——————print()
2.程序普通操作中的程序运行报告————————logging.info() (or logging.debug() 输出详细的输出)
3.特定运行事件中发出警告————————logging.warning() 需要时刻提示
4.关于特定的运行错误——————————抛出异常
5.长期运行的服务程序运行错误且不抛出异常——————————logging.error(), logging.exception() or logging.critical() 适用于特定的错误和领域。

下面是他们的日志等级和使用范围:

1.debug——————详细,通常用于调试问题。
2.INFO————————确认程序按期望运行。
3.WARNING——————程序提示一些意外的信息或即将出现的问题(eg:磁盘空间低)。
4.ERROR——————由于一个严重的问题,不能执行一些方法了。
5.CRITICAL————————一个严重的错误,程序可能无法继续执行下去了。

默认等级是 WARNING ,大于这个等级的会被跟踪。
事件可以用不同的方式处理。最简单的事输出终端,还有磁盘文件输出。

2.A very simple example

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!

先不关心root 是什么,一会解释。输出内容可以自由配置格式。

3.Logging to a file

一般记录方式是将日志记入文件。

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

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

因为设置的等级是DEBUG ,所以所有的信息都接收了。
命令行设置日志等级 --log=INFO
获得命令行的日志等级 getattr(logging, loglevel.upper())

# 从命令行获取日志等级参数,转换成大写
# 指定--log=DEBUG or --log=debug
numeric_level = getattr(logging, loglevel.upper(), None)
if not isinstance(numeric_level, int):
    raise ValueError('Invalid log level: %s' % loglevel)
logging.basicConfig(level=numeric_level, ...)

basicConfig()需要在debug()和info()之前使用。

logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
和上面一样,但是日志会覆盖,不是追加。

4.多模块记录

5.Logging variable data

使用字符串来我作为描述信息,,添加变量作为参数。例如
import logging
logging.warning('%s before you %s', 'Look', 'leap!')

print:

WARNING:root:Look before you leap!

使用%的风格是向后兼容:

6.Changing the format of displayed messages

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

which would print:

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

这里 root没有了。

7.Displaying the date/time in messages

输出时间的格式是:‘%(asctime)s’
更深层次的定制:format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p'
datefmt和 time.strftime()支持的一样.

8.下一步

上面的信息已经够用了,logging还提供了很多包,想用好它,你需要花更多的时间来看它。
如果你简单的用用,上面的例子就够用了。
下一节是稍高级的应用,看完之后,你可以看一眼cookbook。

原文地址:https://www.cnblogs.com/wanself/p/2795182.html