第一种方法:(推荐)
- import logging.handlers
- LOG_FILE = rtst.log
- handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=1024 * 1024, backupCount=5, encoding=utf-8) # 实例化 handler
- fmt = %(asctime)s - %(levelname)s - %(message)s
- formatter = logging.Formatter(fmt) # 实例化 formatter
- handler.setFormatter(formatter) # 为 handler 添加 formatter
- logger = logging.getLogger(tst) # 获取名为 tst 的 logger
- logger.addHandler(handler) # 为 logger 添加 handler
- logger.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.")
来源: http://www.bubuko.com/infodetail-2537868.html