自备工具---log


日志工具

使用:

logger = my_log(file_path="basic.log", error_path="errors.log")

文件:
import logging
import logging.config
import os


def my_log(handlers=['console', 'file', 'errors'], level='DEBUG', file_path="d:/my.log", error_path="d:/errors.log"):
    """
    日志处理类
    :param handlers: 'console', 'file','errors','mail'
    :param level: 'DEBUG','INFO','WARN','ERROR'
    :param file_path: if handlers is 'file' then default file path is 'd:/my.log'
    :param error_path: if handlers is 'error' then default file path is 'd:/errors.log'
    :return: logger
    """
    file_path = file_path.replace('\\', '/')
    error_path = error_path.replace('\\', '/')
    file_directory = file_path[:file_path.rfind('/')]
    error_directory = error_path[:error_path.rfind('/')]
    if not os.path.exists(file_directory):
        os.makedirs(file_directory)
    if not os.path.exists(error_directory):
        os.makedirs(error_directory)
    config = {
        'version': 1,
        'formatters': {
            'basic': {
                'format': '%(asctime)s %(levelname)s %(pathname)s %(filename)s %(module)s %(funcName)s [line:%(lineno)d] %(message)s'},
            'simple': {'format': '%(asctime)s %(levelname)s %(filename)s %(message)s'},
        },
        'handlers': {
            'console': {
                'class': 'logging.StreamHandler',
                'level': 'DEBUG',
                'formatter': 'simple'
            },
            'file': {
                'class': 'logging.handlers.TimedRotatingFileHandler',
                'filename': file_path,
                'when': 'MIDNIGHT',
                'interval': 1,
                'backupCount': 0,
                'level': 'DEBUG',
                'formatter': 'simple',
            },
            'errors': {
                'class': 'logging.FileHandler',
                'filename': error_path,
                'level': 'ERROR',
                'formatter': 'basic',
            },
            'mail': {
                'class': 'logging.handlers.SMTPHandler',
                'mailhost': 'smtp.qq.com',
                'fromaddr': '999@qq.com',
                'toaddrs': ['9@qq.com'],
                'subject': '日志',
                'credentials': ('666@qq.com', '111111'),
                'secure': None,
                'timeout': 50,
                'level': 'ERROR',
                'formatter': 'basic',
            },
        },
        'loggers': {
            'my': {
                'handlers': handlers,
                'level': level,
                'propagate': True,  # 继承父类信息
            },
            'mail': {
                'handlers': ['console', 'mail'],
                'level': 'ERROR',
                'propagate': True,
            }
        }
    }
    logging.config.dictConfig(config)
    logger = logging.getLogger('my')
    return logger