0.基本用法
原文地址0:http://blog.csdn.net/langb2014/article/details/53397164
可以定义不同的handler来控制日志的输出(格式、等级)
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import sys
# 定义控制台输出handler
console = logging.StreamHandler(sys.stderr)
# 定义文本输出handler
file_handler = logging.FileHandler('log_data.log')
# 日志输出到文本和控制台
def log_config():
# 获取logger实例,如果参数为空则返回root logger
logger = logging.getLogger("")
# 指定logger输出格式
formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
# 文件日志
file_handler.setLevel(logging.ERROR)
file_handler.setFormatter(formatter) # 可以通过setFormatter指定输出格式
# 控制台日志
console.formatter = formatter # 也可以直接给formatter赋值
# 指定日志的最低输出级别,默认为WARN级别
logger.setLevel(logging.INFO)
# 为logger添加的日志处理器
logger.addHandler(file_handler)
logger.addHandler(console)
# 移除一些日志处理器
# logger.removeHandler(file_handler)
return logging
原文地址1:http://python.jobbole.com/81666/
原文地址2:http://www.cnblogs.com/dkblog/archive/2011/08/26/2155018.html
1.简单的将日志打印到屏幕
import logging
records = {'john': 55, 'tom': 66}
# 使用 DEBUG 获取详细的调试信息
logging.debug('Records: %s', records)
# 状态变化等日常事务中,使用 INFO 等级
logging.info('Updating records ...')
logging.info('Finish updating records')
# 很重要的事件,但是并不是错误时,使用 WARNING
logging.warning('434534')
# 有错误发生时肯定会使用 ERROR 等级了。比如抛出异常,IO 操作失败或者连接问题等
logging.error('434534')
默认情况下,logging将日志打印到屏幕,日志级别为WARNING;
日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,当然也可以自己定义日志级别。
2通过logging.basicConfig函数对日志的输出格式及方式做相关配置
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='myapp.log',
filemode='w')
logger = logging.getLogger(__name__)
logging.basicConfig函数各参数:
filename: 指定日志文件名
filemode: 和file函数意义相同,指定日志文件的打开模式,'w'或'a'
format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:
%(levelno)s: 打印日志级别的数值
%(levelname)s: 打印日志级别名称
%(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
%(filename)s: 打印当前执行程序名
%(funcName)s: 打印日志的当前函数
%(lineno)d: 打印日志的当前行号
%(asctime)s: 打印日志的时间
%(thread)d: 打印线程ID
%(threadName)s: 打印线程名称
%(process)d: 打印进程ID
%(message)s: 打印日志信息
datefmt: 指定时间格式,同time.strftime()
level: 设置日志级别,默认为logging.WARNING
stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略
方法二:
# -*- coding:utf-8 -*-
import logging
logger = logging.getLogger(__name__)
# 创建日志文件
handler = logging.FileHandler('tt_project.log')
# 设置日志输出等级
handler.setLevel(logging.DEBUG)
# 创建日志格式
formatter = logging.Formatter('%(asctime)s - %(filename)s - %(levelname)s - %(message)s')
# 为日志设置格式
handler.setFormatter(formatter)
# 将handler添加到日志
logger.addHandler(handler)
3.将日志同时输出到文件和屏幕
# -*- coding:utf-8 -*-
import logging
# 对日志的输出格式及方式做相关配置
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
# datefmt='%a, %d %b %Y %H:%M:%S',
filename='myapp.log',
filemode='w')
logger = logging.getLogger(__name__)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(filename)-12s[line:%(lineno)d]: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
4.通过logging.config模块配置日志
#logger.conf
###############################################
[loggers]
keys=root,example01,example02
[logger_root]
level=DEBUG
handlers=hand01,hand02
[logger_example01]
handlers=hand01,hand02
qualname=example01
propagate=0
[logger_example02]
handlers=hand01,hand03
qualname=example02
propagate=0
###############################################
[handlers]
keys=hand01,hand02,hand03
[handler_hand01]
class=StreamHandler
level=INFO
formatter=form02
args=(sys.stderr,)
[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form01
args=('myapp.log', 'a')
[handler_hand03]
class=handlers.RotatingFileHandler
level=INFO
formatter=form02
args=('myapp.log', 'a', 10*1024*1024, 5)
###############################################
[formatters]
keys=form01,form02
[formatter_form01]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt=%a, %d %b %Y %H:%M:%S
[formatter_form02]
format=%(name)-12s: %(levelname)-8s %(message)s
datefmt=
例1:
import logging
import logging.config
logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example01")
logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')
例2:
import logging
import logging.config
logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example02")
logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')
因为一些原因不能把日志模块写成配置文件,在定义日志配置后调用日志方法
问题1:打印到屏幕上信息会重复打印
原因:因为每次调用logger()方法时都会给它加一个新的handler
解决方法:全局只配置logger一次
原网址: http://python.jobbole.com/86887/定义日志方法domo(logg.py):
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
import time
o_path = os.getcwd().encode('utf-8')
now_time = time.strftime('%Y%m%d-%H%M%S', time.localtime(time.time()))
console = logging.StreamHandler()
def log_config():
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename=o_path + '\\' + now_time + '.log',
filemode='w')
# 定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象#
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
return logging
调用日志方法
logg.log_config().error('2f')
logg.log_config().warning('3d')
logg.log_config().info('4d')
logg.log_config().debug('5d')
2017-06-23 15:55:00,984 test.py[line:25] ERROR 2f
2017-06-23 15:55:00,984 test.py[line:26] WARNING 3d
2017-06-23 15:55:00,984 test.py[line:27] INFO 4d