Chinaunix首页 | 论坛 | 博客
  • 博客访问: 657040
  • 博文数量: 149
  • 博客积分: 3901
  • 博客等级: 中校
  • 技术积分: 1558
  • 用 户 组: 普通用户
  • 注册时间: 2009-02-16 14:33
文章分类

全部博文(149)

文章存档

2014年(2)

2013年(10)

2012年(32)

2011年(21)

2010年(84)

分类: Python/Ruby

2010-07-07 15:56:37




使用 :

log = loggingUtils.loggingUtils('/tmp/ttx.log')
log.debug('debug')
try :
    1/0
except :
    log.error('异常')
    log.error_sys()


代码:

#!/usr/bin/python
#encoding: utf-8
import sys,traceback

class loggingUtils :
    def __init__(self,logfile) :
        import logging
        self.logger = logging.getLogger(logfile)
        self.hdlr = logging.FileHandler(logfile)
        formatter = logging.Formatter('%(asctime)s %(levelname)s - %(message)s')
        self.hdlr.setFormatter(formatter)
        self.logger.addHandler(self.hdlr)
        self.logger.setLevel(logging.DEBUG)

    def debug(self,msg):
        self.logger.debug( msg )
        self.hdlr.flush()
        #logger.removeHandler( hdlr )网络上的实现基本为说明这条语句的使用和作用

    def error(self,eline):
        self.logger.error(eline)
        self.hdlr.flush()

    def error_sys(self,limit=None):
        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
        if limit is None:
            if hasattr(sys, 'tracebacklimit'):
                limit = sys.tracebacklimit
        n = 0
        eline = '\n'
        while exceptionTraceback is not None and (limit is None or n < limit):
            f = exceptionTraceback.tb_frame
            lineno = exceptionTraceback.tb_lineno
            co = f.f_code
            filename = co.co_filename
            name = co.co_name
            eline += ' File "%s", line %d, in %s \n ' % (filename,lineno,name)
            exceptionTraceback = exceptionTraceback.tb_next
            n = n+1

        eline+= "\n".join(traceback.format_exception_only(exceptionType, exceptionValue))
        self.logger.error(eline)
        self.hdlr.flush()


阅读(1479) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~