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

#!/usr/bin/env python# -*- coding:utf-8 -*-"""本地记录日志配置文件"""import osimport platformBASEDIR = 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        }    }}

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

在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_configfrom 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
©著作权归作者所有:来自51CTO博客作者mob604756e88498的原创作品,如需转载,请注明出处,否则将追究法律责任

更多相关文章

  1. CI/CD笔记-Gitlab安装部署
  2. Docker_学习笔记系列之CentOs7安装docker
  3. CI/CD笔记-Jenkins的安装部署
  4. nginx搭建web服务器,配置端口复用
  5. 《MySQL》系列 - 十张图详解 MySQL 日志(建议收藏)
  6. 弃繁就简!一行代码搞定 Python 日志!
  7. Kafka日志清理之Log Deletion
  8. Kafka日志清理之Log Compaction
  9. Kafka参数broker.id详解

随机推荐

  1. gdb学习(二)[第二版]
  2. Linux命令备忘实例(10)——目录管理
  3. linux下安装weblogic无图形化界面
  4. 鸟哥的linux私房菜学习笔记《三十九》Lin
  5. linux进程和线程排查 · 记一次JVM CPU高
  6. Linux服务器禁用ping
  7. linux 中 开放端口,以及防火墙的相关命令
  8. linux下如何杀掉D状态进程
  9. linux命令行程序
  10. 连接到Linux服务器时首先要运行的5个命令