Chinaunix首页 | 论坛 | 博客
  • 博客访问: 29308873
  • 博文数量: 2065
  • 博客积分: 10377
  • 博客等级: 上将
  • 技术积分: 21525
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-04 17:50
文章分类

全部博文(2065)

文章存档

2012年(2)

2011年(19)

2010年(1160)

2009年(969)

2008年(153)

分类: Python/Ruby

2010-07-18 10:33:21

使用 :
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()


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