Python loguru 的使用

结构目录:

--config.py

--log.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, 'log_test')
    LOGGING_FILE_NAME = 'iotdash.log'
    LOGGING_FILE_PATH = os.path.join(LOGGING_FILE_DIR, LOGGING_FILE_NAME)
    LOGGING_LEVEL = 'INFO'
    LOGGING_FORMAT = '{time} [{level}] {message}'


settings = Config()

log.py

from config import settings
import os
from loguru import logger


if not os.path.exists(settings.LOGGING_FILE_DIR):
    os.mkdir(settings.LOGGING_FILE_DIR)


logger.add(settings.LOGGING_FILE_PATH, rotation="12:00", retention="5 days", enqueue=True, format=settings.LOGGING_FORMAT)

mian.py

from fastapi import FastAPI
import uvicorn
from log import logger
app = FastAPI()


@app.get('/')
def get_name():
    logger.info('get name of this api')
    return {'name':'ccc'}


@app.get('/a/')
def get_a():
    logger.error('get a of this')
    return "a"


@app.get('/z/')
def get_a():
    logger.debug('get z')
    return "z"

log.log

2021-05-08T15:15:06.043833+0800 [ERROR] get a of this
2021-05-08T15:16:51.516771+0800 [DEBUG] get z
2021-05-08T15:16:58.142395+0800 [INFO] get name of this api

 

posted @ 2021-05-08 15:18  独丨恋  阅读(278)  评论(0编辑  收藏  举报