123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- # Author renyupeng
- # coding=utf-8
- # @Time : 2021/9/15 11:14 上午
- # @Site :
- # @File : ConfConstant.py
- # @Software: PyCharm
- # @contact: renyupeng@c-top.com.cn
- # @Tel 1501435553
- """
- logging配置
- """
- import logging.config
- import os
- import time
- from Apietl.constant.ConfConstant import ConfConstant
- class Loggers:
- def __init__(self, log_name):
- """初始化日志"""
- self.__ini_log(log_name=log_name)
- @staticmethod
- def __get_local_time():
- # 获取当前时间
- time_now = int(time.time())
- # 转换成localtime
- time_local = time.localtime(time_now)
- # 转换成新的时间格式(2016-05-09 18:59:20)
- dt = time.strftime("%Y%m%d", time_local)
- return dt
- def __ini_log(self, log_name):
- # 定义三种日志输出格式 开始
- standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
- '[%(levelname)s][%(message)s]' # 其中name为getlogger指定的名字
- simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
- # id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'
- # 定义日志输出格式 结束
- # logfile_dir = os.path.dirname(os.path.abspath(__file__)) # log文件的目录
- logfile_dir = os.path.dirname(ConfConstant.LOG_DIR) # log文件的目录
- logfile_name = '{}_{}.log'.format(log_name, self.__get_local_time()) # log文件名
- # 如果不存在定义的日志目录就创建一个
- if not os.path.isdir(logfile_dir):
- os.mkdir(logfile_dir)
- # log文件的全路径
- logfile_path = os.path.join(logfile_dir, logfile_name)
- # log配置字典
- logging_dic = {
- 'version': 1,
- 'disable_existing_loggers': False,
- 'formatters': {
- 'standard': {
- 'format': standard_format
- },
- 'simple': {
- 'format': simple_format
- },
- },
- 'filters': {},
- 'handlers': {
- # 打印到终端的日志
- 'console': {
- 'level': 'DEBUG',
- 'class': 'logging.StreamHandler', # 打印到屏幕
- 'formatter': 'simple'
- },
- # 打印到文件的日志,收集info及以上的日志
- 'default': {
- 'level': 'DEBUG',
- 'class': 'logging.handlers.RotatingFileHandler', # 保存到文件
- 'formatter': 'standard',
- 'filename': logfile_path, # 日志文件
- # 'maxBytes': 1024*1024*5, # 日志大小 5M
- 'backupCount': 5,
- 'encoding': 'utf-8', # 日志文件的编码,再也不用担心中文log乱码了
- },
- },
- 'loggers': {
- '': {
- 'handlers': ['default', 'console'], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
- 'level': ConfConstant.LOG_LEVEL,
- 'propagate': True, # 向上(更高level的logger)传递
- },
- },
- }
- logging.config.dictConfig(logging_dic) # 导入上面定义的logging配置
- logging.getLogger(__name__) # 生成一个log实例
|