常用的logging配置

centos 6.5,python 2.6

习惯封装一个log.py

#!/usr/bin/python  
# -*- coding: UTF-8 -*-

import logging
from logging.handlers import RotatingFileHandler

LOG = logging.getLogger('TheLogger')
LOG.setLevel(logging.DEBUG) # 这个级别是基础

# 输出日志到控制台
ch = logging.StreamHandler()
cfmt = logging.Formatter('%(threadName)s - %(levelname)s - %(message)s')
ch.setFormatter(cfmt)
ch.setLevel(logging.ERROR)  # 设置级别如果低于LOG设置的级别则无效
LOG.addHandler(ch)  # 如果不需要打印到控制台,注释这行即可

# 输出日志到文件,文件最大1M,最多保存两个
fh = logging.handlers.RotatingFileHandler('/var/log/thelogger.log', maxBytes=1*1024*1024, backupCount=2)
ffmt = logging.Formatter('%(asctime)s - %(name)s - %(threadName)s - %(levelname)s - %(message)s')
fh.setFormatter(ffmt)
fh.setLevel(logging.INFO)   # 设置级别如果低于LOG设置的级别则无效
LOG.addHandler(fh)  # 如果不需要记录到文件,注释这行即可

调用

#!/usr/bin/python  
# -*- coding: UTF-8 -*-

from log import *

LOG.debug('debug')
LOG.info('info')
LOG.warning('warning')
LOG.error('error')

over

posted @ 2016-12-23 16:23  晚来秋  阅读(872)  评论(0编辑  收藏  举报