Python_学习之项目日志管理

作为一个开发者,日志的作用相信大家对它的重要性,是毋庸置疑的,它是你代码优化及bug修复的最佳助手,也是"责任"的最佳证据,如果你是初学者或刚入职场,代码的编写还不够老练,没有关系,但日志记得一定一定要记得保留,最基本的原则就是,人过留声【谁访问你,什么时候,传了什么,来干嘛,你什么时候响应的,响应了什么】,重要的事情重复说,记日志,记日志,记日志!
废话不多说,直接干货送上,你要做的就是copy!
以下是前篇文章<<Python_学习之项目目录结构构建>>中说的日志配置log_config.py,本日志配置适合python任何项目。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""本地记录日志配置文件"""
import os
import platform

BASEDIR = os.path.dirname(
    os.path.dirname(
        os.path.dirname(
            os.path.abspath(__file__))))
# 本地项目日志路径
CURRENT_LOG_PATH = os.path.join(BASEDIR, 'log')

PREFIX = CURRENT_LOG_PATH if platform.system(
) != 'Windows' else '/opt/logs/python_apps_logs/{}'.format(os.path.basename(BASEDIR))

# 判断目录是否存在,若不存在则创建
if not os.path.exists(PREFIX):
    os.makedirs(PREFIX)

# 日志文件路径
LOG_PATH_DEBUG = r'%s\debug.log' % PREFIX if platform.system(
) == 'Windows' else '%s/debug.%s.log' % (PREFIX, os.getpid())
LOG_PATH_INFO = r'%s\info.log' % PREFIX if platform.system(
) == 'Windows' else '%s/info.%s.log' % (PREFIX, os.getpid())
LOG_PATH_WARN = r'%s\warn.log' % PREFIX if platform.system(
) == 'Windows' else '%s/warn.%s.log' % (PREFIX, os.getpid())
LOG_PATH_ERROR = r'%s\error.log' % PREFIX if platform.system(
) == 'Windows' else '%s/error.%s.log' % (PREFIX, os.getpid())

# 日志配置
LOGGING_CONFIG = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
            'format': '[%(asctime)s] %(levelname)s::(%(process)d %(thread)d)::%(module)s[line:%(lineno)d] - %(message)s'
        },
    },
    'handlers': {
        'error': {
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'level': 'ERROR',
            'formatter': 'standard',
            'filename': LOG_PATH_ERROR + '_file',
            'when': 'H',
            'interval': 1
        },
        'warn': {
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'level': 'WARN',
            'formatter': 'standard',
            'filename': LOG_PATH_WARN + '_file',
            'when': 'H',
            'interval': 1
        },
        'info': {
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'level': 'INFO',
            'formatter': 'standard',
            'filename': LOG_PATH_INFO + '_file',
            'when': 'H',
            'interval': 1
        },
        'debug': {
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'level': 'DEBUG',
            'formatter': 'standard',
            'filename': LOG_PATH_DEBUG + '_file',
            'when': 'H',
            'interval': 1
        }
    },
    'loggers': {
        'default': {
            'handlers': ['debug', 'info', 'warn', 'error'],
            'level': 'DEBUG',
            'propagate': True
        }
    }
}

为了更加的通用性,如果参照我的写法,建议目录结构如下图:

Python_学习之项目日志管理

在log_conf包中的init.py文件中,构建logger对象,如下:

#!/usr/bin/env python

-- coding:utf-8 --

import logging.config
from log_conf import log_config

logging.config.dictConfig(log_config.LOGGING_CONFIG)
logger = logging.getLogger('default')

这样一个完整的日志管理就完成了,剩下的就是用了,它的方法非常简单。


# 使用配置好的log_config
from log_conf import logger

# 能力接口
def test(request_data):
    code, desc, result = 0, 'success', None
    logger.debug("请求参数为:%s" % request_data)
    try:
        """do something"""
        pass
    except Exception as e:
        logger.error("xx能力接口发生异常,异常原因为:%s" % e.args)
        code, desc = 1, "系统异常"
    finally:
        return code, desc, result

猜你喜欢

转载自blog.51cto.com/15127518/2685168