第一种方法:(推荐)
import logging.handlersLOG_FILE = r'tst.log'handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=1024 * 1024, backupCount=5, encoding='utf-8') # 实例化handlerfmt = '%(asctime)s - %(levelname)s - %(message)s'formatter = logging.Formatter(fmt) # 实例化formatterhandler.setFormatter(formatter) # 为handler添加formatterlogger = logging.getLogger('tst') # 获取名为tst的loggerlogger.addHandler(handler) # 为logger添加handlerlogger.setLevel(logging.DEBUG)logger.info(u'输出中文试一试')logger.debug('first debug message')
第二种方法:
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"logging.basicConfig(filename='my.log', level=logging.DEBUG, format=LOG_FORMAT, datefmt=DATE_FORMAT)logging.debug("This is a debug log.")logging.info("This is a info log.")logging.warning("This is a warning log.")logging.error("This is a error log.")logging.critical("This is a critical log.")