日志

发布时间 2023-12-13 01:46:18作者: 我才是最帅的那个男人

  日志是给开发者记录问题的一个文件。

格式:

 1 import logging
 2   
 3   
 4 logging.basicConfig(filename='log.log',
 5                     format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
 6                     datefmt='%Y-%m-%d %H:%M:%S %p',
 7                     level=10) #格式,level指的是记录的级别,大于才可以记录
 8   
 9 logging.debug('debug') #测试信息
10 logging.info('info') #正常信息
11 logging.warning('warning') #警告,可以用
12 logging.error('error') #错误
13 logging.critical('critical') #非常错误,需要立即处理

import traceback

    def func():
  try:
   a = a +1
  except Exception as e:
   # 获取当前错误的堆栈信息
   msg = traceback.format_exc()
   logging.error(msg)
    func()

错误级别

CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0

二,如果需要多个日志文件记录不同等级的情况,需要自定义

# 定义文件
file_1_1 = logging.FileHandler('l1_1.log', 'a', encoding='utf-8')
fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s")
file_1_1.setFormatter(fmt)

file_1_2 = logging.FileHandler('l1_2.log', 'a', encoding='utf-8')
fmt = logging.Formatter()
file_1_2.setFormatter(fmt)

# 定义日志
logger1 = logging.Logger('s1', level=logging.ERROR)
logger1.addHandler(file_1_1)
logger1.addHandler(file_1_2)


# 写日志
logger1.critical('1111')

日志一

# 定义文件
file_2_1 = logging.FileHandler('l2_1.log', 'a')
fmt = logging.Formatter()
file_2_1.setFormatter(fmt)

# 定义日志
logger2 = logging.Logger('s2', level=logging.INFO)
logger2.addHandler(file_2_1)

日志(二)