python设置日志

问题

为python设置日志, 设置日志格式, 并打印到文件中

解答

log.py


import logging
import os
from logging import config

BASE_DIR = os.path.abspath(os.path.dirname(__file__))

DEFAULT_LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "standard": {
            "format": "[%(asctime)s][%(levelname)s] %(pathname)s %(lineno)d : %(message)s",
            "datefmt": "%Y-%m-%d %H:%M:%S",
        }
    },
    "handlers": {
        "default": {
            "level": logging.DEBUG,
            "formatter": "standard",
            "class": "logging.StreamHandler",
        },
        "file": {
            "level": logging.DEBUG,
            "formatter": "standard",
            "class": "logging.handlers.RotatingFileHandler",
            "maxBytes": 1024 * 1024 * 10,
            "backupCount": 5,
            "filename": os.path.join(BASE_DIR, "logs/web.log"),
        },
    },
    "loggers": {
        "": {"handlers": ["default", "file"], "level": "DEBUG"},
        "uvicorn": {
            "handlers": ["default", "file"],
            "level": "DEBUG",
            "propagate": False,
        },
    },
}

dir_name = os.path.dirname(DEFAULT_LOGGING["handlers"]["file"]["filename"])
if not os.path.exists(dir_name):
    os.makedirs(dir_name)


def configure_logging():
    logging.config.dictConfig(DEFAULT_LOGGING)

使用

import logging

from log import configure_logging

configure_logging()
logger = logging.getLogger(__name__)