Python logger 的使用

实现环境:Python-3.7, fastapi-0.64.0,uvicorn-0.13.4

目录结构

--config.py

--logger.py

--main.py

--log.log

具体代码:

config.py

  主要是进行日志功能的相关环境的设置

import os
import pathlib

BACKEND_PATH = pathlib.Path(__file__).parent.parent

SUPER_USER = 1


class Config:
    LOGGING_FILE_D = os.path.dirname(os.path.dirname(__file__))
    LOGGING_FILE_DIR = os.path.join(LOGGING_FILE_D)
    LOGGING_FILE_NAME = 'log.log'
    LOGGING_FILE_PATH = os.path.join(LOGGING_FILE_DIR, LOGGING_FILE_NAME)
    LOGGING_LEVEL = 'INFO'
    # LOGGING_FORMAT = '{time} [{level}] {message}'
    LOGGING_FORMAT = "%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s"


settings = Config()

logger.py

  主要是对 Python 原始的 logging 模块进行封装

import os
import sys
import time
import logging
from config import settingsclass Logger:
    def __init__(self, set_level="INFO",
                 name=os.path.split(os.path.splitext(sys.argv[0])[0])[-1],
                 use_console=True):
        """
        :param set_level: 日志级别["NOTSET"|"DEBUG"|"INFO"|"WARNING"|"ERROR"|"CRITICAL"],默认为INFO
        :param name: 日志中打印的name,默认为运行程序的name
        :param log_name: 日志文件的名字,默认为当前时间(年-月-日.log)
        :param log_path: 日志文件夹的路径,默认为logger.py同级目录中的log文件夹
        :param use_console: 是否在控制台打印,默认为True
        """
        if not set_level:
            set_level = self._exec_type()  # 设置set_level为None,自动获取当前运行模式
        self.__logger = logging.getLogger(name)
        self.setLevel(
            getattr(logging, set_level.upper()) if hasattr(logging, set_level.upper()) else logging.INFO)  # 设置日志级别
        if not os.path.exists(settings.LOGGING_FILE_DIR):  # 创建日志目录
            os.makedirs(settings.LOGGING_FILE_DIR)
        formatter = logging.Formatter(settings.LOGGING_FORMAT)
        handler_list = list()
        handler_list.append(logging.FileHandler(settings.LOGGING_FILE_PATH, encoding="utf-8"))
        if use_console:
            handler_list.append(logging.StreamHandler())
        for handler in handler_list:
            handler.setFormatter(formatter)
            self.addHandler(handler)

    def __getattr__(self, item):
        return getattr(self.logger, item)

    @property
    def logger(self):
        return self.__logger

    @logger.setter
    def logger(self, func):
        self.__logger = func

    def _exec_type(self):
        return "DEBUG" if os.environ.get("IPYTHONENABLE") else "INFO"

main.py

  对封装的logger进行调用

from fastapi import FastAPI
import uvicorn
import logger

_logger = logger.Logger('info')
app = FastAPI()


@app.get('/')
def get_a():
    _logger.info('sss')
    return 'a'


if __name__ == '__main__':
    uvicorn.run(app, host='127.0.0.1', port=8000)

log.log 打印内容如下

2021-05-08 13:43:07,409 - mian.py[line:11] - INFO: sss
2021-05-08 13:43:08,611 - mian.py[line:11] - INFO: sss
2021-05-08 13:43:10,138 - mian.py[line:11] - INFO: sss

 

posted @ 2021-05-08 15:06  独丨恋  阅读(2768)  评论(1编辑  收藏  举报