zoukankan      html  css  js  c++  java
  • python logging模块

    一、日志记录级别

      critical      关键错误/消息

      error         错误

      warning       警告

      info         信息

      debug        调试

    二、配置和使用

      django官方日志模块配置使用:

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,  # 是否禁用已经存在的日志器
        'formatters': {  # 日志信息显示的格式
            'verbose': {
                'format': '%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s'
            },
            'simple': {
                'format': '%(levelname)s %(module)s %(lineno)d %(message)s'
            },
        },
        'filters': {  # 对日志进行过滤
            'require_debug_true': {  # django在debug模式下才输出日志
                '()': 'django.utils.log.RequireDebugTrue',
            },
        },
        'handlers': {  # 日志处理方法
            'console': {  # 向终端中输出日志
                'level': 'INFO',
                'filters': ['require_debug_true'],
                'class': 'logging.StreamHandler',
                'formatter': 'simple'
            },
            'file': {  # 向文件中输出日志
                'level': 'INFO',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': os.path.join(os.path.dirname(BASE_DIR), "logs/meiduo.log"),  # 日志文件的位置
                'maxBytes': 300 * 1024 * 1024,
                'backupCount': 10,
                'formatter': 'verbose'
            },
        },
        'loggers': {  # 日志器
            'django': {  # 定义了一个名为django的日志器
                'handlers': ['console', 'file'],  # 可以同时向终端与文件中输出日志
                'propagate': True,  # 是否继续传递日志信息
                'level': 'INFO',  # 日志器接收的最低日志级别
            },
        }
    }
    setting.py详解
    #导入模块
    import logging
    import django.utils.log
    import logging.handlers
     
     
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': True,
        'formatters': {
           'standard': {
                'format': '%(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] [%(module)s:%(funcName)s] [%(levelname)s]- %(message)s'}  #日志格式 
        },
        'filters': {
        },
        'handlers': {
            'mail_admins': {
                'level': 'ERROR',
                'class': 'django.utils.log.AdminEmailHandler',
                'include_html': True,
            },
            'default': {
                'level':'DEBUG',
                'class':'logging.handlers.RotatingFileHandler',
                'filename': '/sourceDns/log/all.log',     #日志输出文件
                'maxBytes': 1024*1024*5,                  #文件大小 
                'backupCount': 5,                         #备份份数
                'formatter':'standard',                   #使用哪种formatters日志格式
            },
            'error': {
                'level':'ERROR',
                'class':'logging.handlers.RotatingFileHandler',
                'filename': '/sourceDns/log/error.log',
                'maxBytes':1024*1024*5,
                'backupCount': 5,
                'formatter':'standard',
            },
            'console':{
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
                'formatter': 'standard'
            },
            'request_handler': {
                'level':'DEBUG',
                'class':'logging.handlers.RotatingFileHandler',
                'filename': '/sourceDns/log/script.log', 
                'maxBytes': 1024*1024*5, 
                'backupCount': 5,
                'formatter':'standard',
            },
            'scprits_handler': {
                'level':'DEBUG',
                'class':'logging.handlers.RotatingFileHandler',
                'filename':'/sourceDns/log/script.log', 
                'maxBytes': 1024*1024*5, 
                'backupCount': 5,
                'formatter':'standard',
            }
        },
        'loggers': {
            'django': {
                'handlers': ['default', 'console'],
                'level': 'DEBUG',
                'propagate': False 
            },
            'django.request': {
                'handlers': ['request_handler'],
                'level': 'DEBUG',
                'propagate': False,
            },
            'scripts': { 
                'handlers': ['scprits_handler'],
                'level': 'INFO',
                'propagate': False
            },
            'sourceDns.webdns.views': {
                'handlers': ['default', 'error'],
                'level': 'DEBUG',
                'propagate': True
            },
            'sourceDns.webdns.util':{
                'handlers': ['error'],
                'level': 'ERROR',
                'propagate': True
            }
        } 
    }
    setting.py
    logger = logging.getLogger('sourceDns.webdns.views')    #刚才在setting.py中配置的logger
     
    try:
        mysql= connectMysql('127.0.0.1', '3306', 'david')
    except Exception,e:
                logger.error(e)        #直接将错误写入到日志文件
    view.py

      

      自己封装的日志模块

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    import os
    import logging
    from config import settings
    
    
    class Logger(object):
        __instance = None
    
        def __init__(self):
            self.run_log_file = settings.RUN_LOG_FILE
            self.error_log_file = settings.ERROR_LOG_FILE
            self.run_logger = None
            self.error_logger = None
    
            self.initialize_run_log()
            self.initialize_error_log()
    
        def __new__(cls, *args, **kwargs):
            if not cls.__instance:
                cls.__instance = object.__new__(cls, *args, **kwargs)
            return cls.__instance
    
        @staticmethod
        def check_path_exist(log_abs_file):
            log_path = os.path.split(log_abs_file)[0]
            if not os.path.exists(log_path):
                os.mkdir(log_path)
    
        def initialize_run_log(self):
            self.check_path_exist(self.run_log_file)
            file_1_1 = logging.FileHandler(self.run_log_file, 'a', encoding='utf-8')
            fmt = logging.Formatter(fmt="%(asctime)s - %(levelname)s :  %(message)s")
            file_1_1.setFormatter(fmt)
            logger1 = logging.Logger('run_log', level=logging.INFO)
            logger1.addHandler(file_1_1)
            self.run_logger = logger1
    
        def initialize_error_log(self):
            self.check_path_exist(self.error_log_file)
            file_1_1 = logging.FileHandler(self.error_log_file, 'a', encoding='utf-8')
            fmt = logging.Formatter(fmt="%(asctime)s  - %(levelname)s :  %(message)s")
            file_1_1.setFormatter(fmt)
            logger1 = logging.Logger('run_log', level=logging.ERROR)
            logger1.addHandler(file_1_1)
            self.error_logger = logger1
    
        def log(self, message, mode=True):
            """
            写入日志
            :param message: 日志信息
            :param mode: True表示运行信息,False表示错误信息
            :return:
            """
            if mode:
                self.run_logger.info(message)
            else:
                self.error_logger.error(message)
    lib/log.py
    # 错误日志
    ERROR_LOG_FILE = os.path.join(BASEDIR, "log", 'error.log')
    # 运行日志
    RUN_LOG_FILE = os.path.join(BASEDIR, "log", 'run.log')
    settings.py
    from lib.log import Logger
    Logger().log('成功创建',True)   # 运行日志
    Logger().log('创建失败',False)  # 错误日志
    run.py 记录日志
  • 相关阅读:
    以链表为载体学习C++(1)
    以链表为载体学习C++(2)
    20191304商苏赫Python程序设计实验一
    Python实验二 20191304商苏赫
    七大基本排序算法之插入排序
    七大基本排序算法之归并排序
    《富爸爸,穷爸爸》
    七大基本排序算法之冒泡排序
    七大基本排序算法之选择排序
    七大基本排序算法之希尔排序
  • 原文地址:https://www.cnblogs.com/ppzhang/p/10020006.html
Copyright © 2011-2022 走看看