zoukankan      html  css  js  c++  java
  • python 之 logger日志 字典配置文件

    import os
    import logging.config   #不能只导入logging
    
    BASE_DIR=os.path.dirname(os.path.dirname(__file__))
    # DB_PATH=os.path.join(BASE_DIR,'db')
    # DB_PATH=r'%sdb' %BASE_DIR
    
    # 定义日志文件的路径
    LOG_PATH=os.path.join(BASE_DIR,'log','access.log')
    # LOG_PATH=r'%slogaccess.log' %BASE_DIR
    # BOSS_LOG_PATH=r'%slogoss.log' %BASE_DIR
    
    # 定义三种日志输出格式 开始
    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_name = 'all2.log'  # 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,
        # 禁用已经存在的logger实例
        'disable_existing_loggers': False, 
        # 定义日志 格式化的 工具
        'formatters': {
            'standard': {
                'format': standard_format
            },
            'simple': {
                'format': simple_format
            },
            'id_simple': {
                'format': id_simple_format
            },
        },
        # 过滤
        'filters': {},  # jango此处不同
        'handlers': {
            #打印到终端的日志
            'stream': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',  # 打印到屏幕
                'formatter': 'simple'
            },
            #打印到文件的日志,收集info及以上的日志
            'access': {
                'level': 'DEBUG',
                'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
                'formatter': 'standard',
                'filename': logfile_path,       # 日志文件路径
                'maxBytes': 1024*1024*5,  # 日志大小 5M
                'backupCount': 5,
                'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
            },
            #打印到文件的日志,收集error及以上的日志
            'boss': {
                        'level': 'ERROR',
                        'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
                        'formatter': 'id_simple',
                        'filename': BOSS_LOG_PATH,  # 日志文件
                        # 'maxBytes': 1024*1024*5,  # 日志大小 5M
                        'maxBytes': 300,  # 日志大小 5M
                        'backupCount': 5,
                        'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
                    },
        },
        # logger实例
        'loggers': {
            # 默认的logger应用如下配置
            '': {
                'handlers': ['stream', 'access','boss'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
                'level': 'DEBUG',
                'propagate': True,  # 向上(更高level的logger)传递
            },
            # logging.getLogger(__name__)拿到的logger配置       
            # 这样我们再取logger对象时logging.getLogger(__name__),不同的文件__name__不同,这保证了打印日志时标识信息不同,
            # 但是拿着该名字去loggers里找key名时却发现找不到,于是默认使用key=''的配置
        },
    }
    
    
    def load_my_logging_cfg():
        logging.config.dictConfig(LOGGING_DIC)  # 导入上面定义的logging配置
        logger = logging.getLogger(__name__)  # 生成一个log实例
        logger.info('It works!')  # 记录该文件的运行状态
    
    if __name__ == '__main__':
        load_my_logging_cfg()
    
    #从common.py引用,要传入name,且有返回log实例
    # import logging.config
    # import logging
    # from conf import setting
    
    # def get_logger(name):
        #logging.config.dictConfig(setting.LOGGING_DIC)  # 导入上面定义的logging配置
        #l1=logging.getLogger(name)
        #return l1
    
    #src.py
    # logger1 = common.get_logger('查看余额')
    # logger1.debug( dic_user_check['money'] )

    Django版log日志:

    settings.py:

    # 日志配置
    BASE_LOG_DIR = os.path.join(BASE_DIR, "log")
    LOGGING = {
        'version': 1,
        # 禁用已经存在的logger实例
        'disable_existing_loggers': False,
        # 定义日志 格式化的 工具
        'formatters': {
            'standard': {
                'format': '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]'
                          '[%(levelname)s][%(message)s]'
            },
            'simple': {
                'format': '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
            },
            'collect': {
                'format': '%(message)s'
            }
        },
        # 过滤
        'filters': {
            'require_debug_true': {
                '()': 'django.utils.log.RequireDebugTrue',
            },
        },
        # 日志处理器
        'handlers': {
            'console': {
                'level': 'DEBUG',
                'filters': ['require_debug_true'],  # 只有在Django debug为True时才在屏幕打印日志
                'class': 'logging.StreamHandler',
                'formatter': 'simple'
            },
    
            'default': {
                'level': 'INFO',
                'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件,自动切
                'filename': os.path.join(BASE_LOG_DIR, "info.log"),  # 日志文件
                'maxBytes': 1024 * 1024 * 50,  # 日志大小 50M
                'backupCount': 3,
                'formatter': 'standard',
                'encoding': 'utf-8',
            },
    
            'error': {
                'level': 'ERROR',
                'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件,自动切
                'filename': os.path.join(BASE_LOG_DIR, "err.log"),  # 日志文件
                'maxBytes': 1024 * 1024 * 50,  # 日志大小 50M
                'backupCount': 5,
                'formatter': 'standard',
                'encoding': 'utf-8',
            },
    
            'collect': {
                'level': 'INFO',
                'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件,自动切
                'filename': os.path.join(BASE_LOG_DIR, "xxx_collect.log"),
                'maxBytes': 1024 * 1024 * 50,  # 日志大小 50M
                'backupCount': 5,
                'formatter': 'collect',
                'encoding': "utf-8"
            }
        },
        # logger实例
        'loggers': {
           # 默认的logger应用如下配置
            '': {
                'handlers': ['default', 'console', 'error'],  # 上线之后可以把'console'移除
                'level': 'DEBUG',
                'propagate': True,
            },
            # 名为 'collect'的logger还单独处理
            'collect': {
                'handlers': ['console', 'collect'],
                'level': 'INFO',
            }
        },
    }
    日志字典配置

    views.py:

    import logging
    
    # 生成一个以当前文件名命名的logger实例
    logger = logging.getLogger(__name__)
    # 生成一个名为collect的logger实例
    collect_logger = logging.getLogger("collect")
    
    logger.info("xxx")
    collect_logger.info("xxx")
    在视图函数中使用
  • 相关阅读:
    FileUpload1上传控件
    docker如何push镜像到docker hub个人的仓库
    docker的ubuntu镜像无ifconfig和ping命令
    keystone同步数据库的时候提示error
    openstack安装dashboard后访问horizon出错 500 or 504
    装了ubuntu之后,只能进入ubuntu系统,不能进入windows系统
    Kernal Panic
    无法获得锁 /var/lib/dpkg/lock -open
    用户 'NT AUTHORITYIUSR' 登录失败
    配置错误:不能在此路径中使用此配置节。
  • 原文地址:https://www.cnblogs.com/mylu/p/11116437.html
Copyright © 2011-2022 走看看