# main.py
from fastapi import FastAPI
from logging_config import setup_logging
app = FastAPI()
logger = setup_logging()
@app.on_event("startup")
async def startup_event():
logger.info("Starting up the application")
@app.on_event("shutdown")
async def shutdown_event():
logger.info("Shutting down the application")
@app.get("/")
async def root():
logger.debug("Handling root endpoint.")
return {"message": "Hello World"}
步骤 3: 在其他模块中使用日志
你可以在其他模块中通过获取同名的日志记录器来使用具有相同配置的日志记录器。
python
# some_module.py
import logging
# 获取已经配置的 logger
logger = logging.getLogger("myapp_logger")
def some_function():
logger.info("Doing some work in the function")
现在,whenever some_function in some_module.py is called, it will log an information level message to both the console and the file, depending on how you configured your logger in logging_config.py.
# main.py
from fastapi import FastAPI
from logger_config import logger
app = FastAPI()
@app.on_event("startup")
def startup_event():
logger.info("Starting up the application")
@app.on_event("shutdown")
def shutdown_event():
logger.error("Shutting down the application, but this is an error for demo.")
@app.get("/")
def read_root():
logger.info("Handling root endpoint.")
return {"Hello": "World"}
@app.get("/error")
def trigger_error():
try:
raise ValueError("This is a manually triggered error")
except ValueError as e:
logger.error(f"Caught an error: {e}")
return {"error": str(e)}