我的账户
码尚云教育

云计算企业项目实战营

亲爱的游客,欢迎!

已有账号,请

如尚未注册?

python的几种写日志方法

[复制链接]
云鼎 发表于 2022-9-19 14:24:42 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题
方法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]复制代码



回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注我们
码尚云云计算培训

客服电话:18710061913

周一至周日: 7:00-24:00

码尚云教育( 陕ICP备2023009934号-2 )

Powered by Discuz! X3.4© 2016-2023 Comsenz Inc.