ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# [log][2] [参考博客][1] ## 在文件中记录日志 ~~~ #coding: utf-8 import logging # 获取logger实例,如果参数为空则返回root logger logger = logging.getLogger("App") # 指定logger输出格式 formatter = logging.Formatter('[%(name)s] %(asctime)s %(levelname)-8s %(filename)s @line: %(lineno)d: %(message)s') # 文件日志 ## 设置日志名称 file_handler = logging.FileHandler("test.log") ## 实例化日志格式 file_handler.setFormatter(formatter) # 可以通过setFormatter指定输出格式 # 为logger添加的日志处理器 logger.addHandler(file_handler) # 指定日志的最低输出级别,默认为WARN级别 logger.setLevel(logging.ERROR) # 输出不同级别的log logger.debug('this is debug info') logger.info('this is information') logger.warn('this is warning message') logger.error('this is error message') logger.fatal('this is fatal message, it is same as logger.critical') logger.critical('this is critical message') try: 1 / 0 except: logger.exception("error") # 移除日志处理器 logger.removeHandler(file_handler) ~~~ ## 在控制台输出日志 ~~~ #coding: utf-8 import logging import sys # 获取logger实例,如果参数为空则返回root logger logger = logging.getLogger("AppName") # 指定logger输出格式 formatter = logging.Formatter('[%(name)s] %(asctime)s %(levelname)-8s %(filename)s @line: %(lineno)d: %(message)s') # 控制台日志 console_handler = logging.StreamHandler(sys.stdout) console_handler.formatter = formatter # 也可以直接给formatter赋值 # 为logger添加的日志处理器 logger.addHandler(console_handler) # 指定日志的最低输出级别,默认为WARN级别 logger.setLevel(logging.ERROR) # 输出不同级别的log logger.debug('this is debug info') logger.info('this is information') logger.warn('this is warning message') logger.error('this is error message') logger.fatal('this is fatal message, it is same as logger.critical') logger.critical('this is critical message') try: 1 / 0 except: logger.exception("error") # 移除日志处理器 logger.removeHandler(console_handler) ~~~ [1]:http://python.jobbole.com/86887/ [2]:https://docs.python.org/2/library/logging.html