python logging模块使用
两种模式,一种basic模式,一种配置log对象模式
basic模式,功能比较少
缺点:
1.解决不了中文乱码问题
2.不同同时输出屏幕和文件
因此不推荐此方法使用
import logging logging.basicConfig(level=logging.WARNING, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='test.log', filemode='a') try: int(input('num >>')) except ValueError: logging.error('输入的值不是一个数字')
第二种,配置log对象的方式
解决第一种方法的确定,推荐使用
import logging logger = logging.getLogger() fh = logging.FileHandler('log.log',encoding='utf-8') #创建一个log对象 sh = logging.StreamHandler() # 创建一个屏幕控制对象 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') #formatter2 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s [line:%(lineno)d] : %(message)s') # 文件操作符和格式关联 fh.setFormatter(formatter) sh.setFormatter(formatter) # logger 对象和文件操作符关联 logger.addHandler(fh) logger.addHandler(sh) logging.debug('debug message') # 低级别的 # 排错信息 logging.info('info message') # 正常信息 logging.warning('警告错误') # 警告信息 logging.error('error message') # 错误信息 logging.critical('critical message') # 高级别的 # 严重错误信息