刚用Python log模块写了一个例子,记录一下。
import logging import logging.handlers import os from datetime import datetime basedir=r'D:log' LOG_LEVEL = 0 resultPath = os.path.join(basedir,'result') if not os.path.exists(resultPath): os.mkdir(resultPath) LOG_PATH = os.path.join(resultPath, str(datetime.now().strftime('%Y-%m-%d-%H-%M-%S'))) if not os.path.exists(LOG_PATH): os.mkdir(LOG_PATH) LOG_FILE_PATH = os.path.join(LOG_PATH, 'output.log') LOG_MAX_SIZE = 10*1024*1024 LOG_BACKUP_COUNT = 5 FILE_LOG_LEVEL = 10 STREAM_LOG_LEVEL = 20 class LOG: logger = None @staticmethod def getLogger(): if LOG.logger is not None: return LOG.logger LOG.logger = logging.getLogger() LOG.logger.setLevel(LOG_LEVEL) Rthandler = logging.handlers.RotatingFileHandler( LOG_FILE_PATH, maxBytes=LOG_MAX_SIZE, backupCount=LOG_BACKUP_COUNT, encoding='utf-8', ) StreamHandler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s-[%(levelname)s][%(module)s][%(funcName)s]-%(message)s') Rthandler.setFormatter(formatter) StreamHandler.setFormatter(formatter) Rthandler.setLevel(FILE_LOG_LEVEL) StreamHandler.setLevel(STREAM_LOG_LEVEL) LOG.logger.addHandler(Rthandler) LOG.logger.addHandler(StreamHandler) return LOG.logger log=LOG.getLogger() log.info('log test')