python自定义日志log类,记录不同级别的错误信息和行号,自定义的log类继承自logging.Logger,使用时可以记录具体日志出现的代码行号
class CheloExtendedLogger(logging.Logger): """ Custom logger class with additional levels and methods """ WARNPFX = logging.WARNING+1 def __init__(self, name): logging.Logger.__init__(self, name, logging.DEBUG) logging.addLevelName(self.WARNPFX, 'WARNING') console = logging.StreamHandler() console.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatter = logging.Formatter("%(asctime)s [%(funcName)s: %(filename)s,%(lineno)d] %(message)s") console.setFormatter(formatter) # add the handlers to logger self.addHandler(console) return def warnpfx(self, msg, *args, **kw): self.log(self.WARNPFX, "! PFXWRN %s" % msg, *args, **kw) logging.setLoggerClass(CheloExtendedLogger) rrclogger = logging.getLogger("rrcheck") rrclogger.setLevel(logging.INFO) def test(): rrclogger.debug("DEBUG message") rrclogger.info("INFO message") rrclogger.warnpfx("warning with prefix") test()
输出格式如下:
2011-02-10 14:36:51,482 [test: log4.py,35] INFO message 2011-02-10 14:36:51,497 [warnpfx: log4.py,26] ! PFXWRN warning with prefix