码尚云_西安云计算培训_云计算运维培训机构

标题: python的几种写日志方法 [打印本页]

作者: 云鼎    时间: 2022-9-19 14:24
标题: python的几种写日志方法
方法1:
  • class Logger(object):
  •     level_relations = {
  •     'debug':logging.DEBUG,
  •     'info':logging.INFO,
  •     'warning':logging.WARNING,
  •     'error':logging.ERROR,
  •     'crit':logging.CRITICAL
  •      }#日志级别关系映射
  •     def __init__(self,filename,level='info',when='D',backCount=3,fmt='%(asctime)s - %(levelname)s: %(message)s'):
  •         self.logger = logging.getLogger(filename)
  •         format_str = logging.Formatter(fmt)#设置日志格式
  •         self.logger.setLevel(self.level_relations.get(level))#设置日志级别
  •         sh = logging.StreamHandler()#往屏幕上输出
  •         sh.setFormatter(format_str) #设置屏幕上显示的格式
  •         th = handlers.TimedRotatingFileHandler(filename=filename,when=when,backupCount=backCount,encoding='utf-8')
  •         th.setFormatter(format_str)#设置文件里写入的格式
  •         self.logger.addHandler(sh) #把对象加到logger里
  •         self.logger.addHandler(th)
  •     if __name__ == '__main__':
  •         log = Logger('all.log',level='debug')
  •         log.logger.debug('debug')
  •         log.logger.info ('info')
  •         log.logger.warning('警告')
  •         log.logger.error('报错')
  •         log.logger.critical('严重')
  •         Logger('error.log', level='error').logger.error('error')

[color=rgb(15, 199, 122) !important]复制代码

方法2:
  • logging.basicConfig(level=logging.DEBUG,
  • filename=filename,
  • filemode='a',
  • format=
  • '%(asctime)s - %(levelname)s: %(message)s'
  • )
  • logging.debug('debug 信息')
  • http://logging.info('info 信息')
  • logging.warning('warning 信息')
  • log.logger.error('error 信息')
  • logging.critical('critial 信息')

[color=rgb(15, 199, 122) !important]复制代码

方法3:
  • with open(filename,'wb',buffering=0) as logfile:
  •     logfile.write("123")

[color=rgb(15, 199, 122) !important]复制代码

方法4:
  • logfile = open(filename, 'w')
  • logfile.write("123",file=logfile)

[color=rgb(15, 199, 122) !important]复制代码








欢迎光临 码尚云_西安云计算培训_云计算运维培训机构 (http://www.mashangcloud.com/) Powered by Discuz! X3.4