In [1]:
import logging
In [2]:
#!/usr/local/bin/python
# -*- coding:utf-8 -*-
import logging
logging.warning('Watch out!') # print message to console
logging.info('I told you so') # will not print anything
Log
写入文件更常见的情形是把信息记录在log
文件里。需要用logging.basicConfig()
设置文件名以及level
等参数,常见的level
见下表。
Level | Value | Usage |
---|---|---|
CRITICAL | 50 | 严重错误,表明程序已不能继续运行了。 |
ERROR | 40 | 严重的问题,程序已不能执行一些功能了 |
WARNING | 30 | 有意外,将来可能发生问题(如‘磁盘满了’),但依然可用 |
INFO | 20 | 证明事情按预期工作。 |
DEBUG | 10 | 详细信息,调试问题时会感兴趣。 |
如果设置level
为INFO
,那么DEBUG
级别的信息就不会输出。常见的函数接口有debug()
, info()
, warning()
, error()
and critical()
,分别对应log
不同严重级别的信息。
注意把下面代码写入脚本(直接在terminal
里不会生成文件),比如test_log.py
。
In [3]:
import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG,filemode='w')
# filemode = 'w' 每次运行,重写log
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
In [4]:
cat example.log
In [5]:
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')
DEBUG:This message should appear on the console
INFO:So should this
WARNING:And this, too
In [6]:
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.')
07/16/2016 12:10:35 AM is when this event was logged.
首先,创建一个logger
,记录器,然后给其添加不同的handler
,输出到不同的渠道。
In [7]:
import logging
# create logger with name
# if not specified, it will be root
logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)
# create a handler, write to log.txt
# logging.FileHandler(self, filename, mode='a', encoding=None, delay=0)
# A handler class which writes formatted logging records to disk files.
fh = logging.FileHandler('log.txt')
fh.setLevel(logging.DEBUG)
# create another handler, for stdout in terminal
# A handler class which writes logging records to a stream
sh = logging.StreamHandler()
sh.setLevel(logging.DEBUG)
# set formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
sh.setFormatter(formatter)
# add handler to logger
logger.addHandler(fh)
logger.addHandler(sh)
# log it
logger.debug('Debug')
logger.info('Info')