1:  自定义日志文件.py----------几个文件需要创建日志,就需要重新定义几份

#1 定义一个日志文件 创建一个操作日志对象logger 

file_1 = logging.FileHandler('text_1.log', 'a', encoding='utf-8')  # text_1.log 定义日志文件名 

fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s") # 定义创建时间,哪个文件,错误level,··
file_1 .setFormatter(fmt)   # 建立执行


# 定义日志  
logger1 = logging.Logger('s1', level=logging.ERROR) # 设置日志
logger1.addHandler(file_1 )

2:将定义好的定义日志导入需要存放报错的文件,并且使用traceback模块具体化报错地点:

# 导入模块
import logging
import traceback
# 导入定义好的日志变量
from Api.utils.自定义日志 import logger1

# 测试1:
def func():
    try:
        a = a + 1
    except Exception as e:
        msg = traceback.format_exc()
        logger1.error(msg)

func()


#报错结果:(自动创建文件并且写入错误信息)
2019-11-26 14:25:10,196 - s1 - ERROR -logging2:  Traceback (most recent call last):
  File "C:/Users/user/Desktop/framework/django-rest-framework/Api/utils/logging2.py", line 17, in func
    a = a + 1
UnboundLocalError: local variable 'a' referenced before assignment

3:直接定义logging(不推荐),需要创建多个日志文件:

import logging

# logging
logging.basicConfig(
filename='loggingdemo.txt', # 日志文件名
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
level=10
)


logging.debug('None')
logging.info('None') # 正常的信息
logging.warning('None') # 警告(不出错)
logging.error('None') # 报错
logging.critical('None') # 非常严重的错误


# logging.log(10,'log')

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

def func():
try:
a = a + 1
except Exception as e:
print(e)
logging.error(str(e))
func()

 4:Django里指定任意日志文件位置:

# 取执行文件全局绝对路径(不管在哪里启动Django都会取到这个路径) 红色的字体表示自定义名称
 path= os.path.abspath(os.path.dirname(__file__))

# 拼接路径
 files_path = path + "/keywords_logging/文件名.log"  # 路径+设定的日志文件名


# 设置日志
keyword_expect_debug = logging.FileHandler(files_path, 'a', encoding='utf-8')
fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s")
keyword_expect_debug.setFormatter(fmt)

keyword_debug = logging.Logger('keyword_debug', level=logging.DEBUG)
keyword_debug.addHandler(keyword_expect_debug)


# 定义文件日志
 form 文件 import keyword_debug
    try:
        a = a + 1
    except Exception as e:
        msg = traceback.format_exc()
        logging_main.keyword_debug.debug(msg)