Python 中的Log模块的使用
(1)首先定义公共的log获取方法:
#!/usr/bin/python import logging.handlers LEVELS={'debug':logging.DEBUG, 'info':logging.INFO, 'warning':logging.WARNING, 'error':logging.ERROR, 'critical':logging.CRITICAL} LOG_BACKUPCOUNT = 5 LOG_LEVEL = 'debug' def getLogger(logFile, threadName): logger = None try: logger = logging.getLogger(threadName) handler = logging.handlers.RotatingFileHandler(logFile, \ maxBytes=10*1024*1024, \ backupCount=LOG_BACKUPCOUNT) formatter = logging.Formatter("[ %(asctime)s ][ %(levelname)s ] %(message)s\n") handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(LEVELS.get(LOG_LEVEL)) except Exception, exInfo: print "Get logger failed: [%s]" %exInfo return logger
(2)在其它文件中import这个公共模块,并调用该方法获取到logger对象,即可使用。
self.logger = Logger.getLogger('test.log', 'global.test') self.logger.info("Test log begin:")