@@ -22,7 +22,6 @@ It is a `Loguru` based custom logging package for python projects.
2222- Custom logging ** formats**
2323- ** Multiprocess** compatibility (Linux, macOS - 'fork')
2424- Add custom ** handlers**
25- - ** FastAPI** HTTP access logging ** middleware**
2625- ** Base** logging module
2726- Support ** Pydantic-v1** and ** Pydantic-v2**
2827
@@ -211,157 +210,12 @@ Traceback (most recent call last):
211210ZeroDivisionError: division by zero
212211` ` `
213212
214- # ## **Advanced ( FastAPI) **
213+ # ## **FastAPI**
215214
216- [**`configs/logger.yml`**]( https://github.com/bybatkhuu/module.python -logging/blob/main/examples/advanced/configs/logger.yml) :
215+ Checkout `beans_logging_fastapi` package : < https://github.com/bybatkhuu/module.fastapi -logging>
217216
218- ` ` ` yaml
219- logger:
220- app_name: "fastapi-app"
221- level: "TRACE"
222- use_diagnose: false
223- stream:
224- use_color: true
225- use_icon: false
226- format_str: "[<c>{time:YYYY-MM-DD HH:mm:ss.SSS Z}</c> | <level>{level_short:<5}</level> | <w>{name}:{line}</w>]: <level>{message}</level>"
227- std_handler:
228- enabled: true
229- file:
230- logs_dir: "./logs"
231- rotate_size: 10000000 # 10MB
232- rotate_time: "00:00:00"
233- backup_count: 90
234- log_handlers:
235- enabled: true
236- format_str: "[{time:YYYY-MM-DD HH:mm:ss.SSS Z} | {level_short:<5} | {name}:{line}]: {message}"
237- log_path: "{app_name}.std.all.log"
238- err_path: "{app_name}.std.err.log"
239- json_handlers:
240- enabled: true
241- use_custom: false
242- log_path: "json/{app_name}.json.all.log"
243- err_path: "json/{app_name}.json.err.log"
244- intercept:
245- auto_load:
246- enabled: true
247- only_base: false
248- ignore_modules: []
249- include_modules: []
250- mute_modules: ["uvicorn.access", "uvicorn.error"]
251- extra:
252- http_std_debug_format: '<n>[{request_id}]</n> {client_host} {user_id} "<u>{method} {url_path}</u> HTTP/{http_version}"'
253- http_std_msg_format: '<n><w>[{request_id}]</w></n> {client_host} {user_id} "<u>{method} {url_path}</u> HTTP/{http_version}" {status_code} {content_length}B {response_time}ms'
254- http_file_enabled: true
255- http_log_path: "http/{app_name}.http.access.log"
256- http_err_path: "http/{app_name}.http.err.log"
257- http_json_enabled: true
258- http_json_path: "json.http/{app_name}.json.http.access.log"
259- http_json_err_path: "json.http/{app_name}.json.http.err.log"
260- ` ` `
261-
262- [**`.env`**](https://github.com/bybatkhuu/module.python-logging/blob/main/examples/advanced/.env) :
263-
264- ` ` ` sh
265- ENV=development
266- DEBUG=true
267- ` ` `
268-
269- [**`logger.py`**](https://github.com/bybatkhuu/module.python-logging/blob/main/examples/advanced/logger.py) :
270-
271- ` ` ` python
272- from beans_logging import Logger, LoggerLoader
273- from beans_logging.fastapi import add_http_file_handler, add_http_file_json_handler
274-
275-
276- logger_loader = LoggerLoader()
277- logger: Logger = logger_loader.load()
278-
279- if logger_loader.config.extra.http_file_enabled:
280- add_http_file_handler(
281- logger_loader=logger_loader,
282- log_path=logger_loader.config.extra.http_log_path,
283- err_path=logger_loader.config.extra.http_err_path,
284- )
285-
286- if logger_loader.config.extra.http_json_enabled:
287- add_http_file_json_handler(
288- logger_loader=logger_loader,
289- log_path=logger_loader.config.extra.http_json_path,
290- err_path=logger_loader.config.extra.http_json_err_path,
291- )
292- ` ` `
293-
294- [**`main.py`**](https://github.com/bybatkhuu/module.python-logging/blob/main/examples/advanced/main.py) :
295-
296- ` ` ` python
297- from typing import Union
298- from contextlib import asynccontextmanager
299-
300- from dotenv import load_dotenv
301- from fastapi import FastAPI, HTTPException
302- from fastapi.responses import RedirectResponse
303-
304- load_dotenv()
305-
306- from beans_logging.fastapi import HttpAccessLogMiddleware
307-
308- from logger import logger, logger_loader
309- from __version__ import __version__
310-
311-
312- @asynccontextmanager
313- async def lifespan(app: FastAPI):
314- logger.info("Preparing to startup...")
315- logger.success("Finished preparation to startup.")
316- logger.info(f"API version: {__version__}")
317-
318- yield
319- logger.info("Praparing to shutdown...")
320- logger.success("Finished preparation to shutdown.")
321-
322- app = FastAPI(lifespan=lifespan, version=__version__)
323- app.add_middleware(
324- HttpAccessLogMiddleware,
325- has_proxy_headers=True,
326- debug_format=logger_loader.config.extra.http_std_debug_format,
327- msg_format=logger_loader.config.extra.http_std_msg_format,
328- )
329-
330- @app.get("/")
331- def root():
332- return {"Hello": "World"}
333- ` ` `
334-
335- Run the [**`examples/advanced`**](https://github.com/bybatkhuu/module.python-logging/tree/main/examples/advanced) :
336-
337- ` ` ` sh
338- cd ./examples/advanced
339- # Install python dependencies for examples:
340- pip install -r ./requirements.txt
341-
342- uvicorn main:app --host=0.0.0.0 --port=8000
343- ` ` `
344-
345- **Output**:
346-
347- ` ` ` txt
348- [2023-09-01 00:00:00.000 +09:00 | TRACE | beans_logging._base:576]: Intercepted modules: ['watchfiles.watcher', 'dotenv', 'asyncio', 'dotenv.main', 'watchfiles.main', 'concurrent.futures', 'uvicorn', 'fastapi', 'concurrent', 'watchfiles']; Muted modules: ['uvicorn.access', 'uvicorn.error'];
349- [2023-09-01 00:00:00.000 +09:00 | INFO | uvicorn.server:76]: Started server process [17146]
350- [2023-09-01 00:00:00.000 +09:00 | INFO | uvicorn.lifespan.on:46]: Waiting for application startup.
351- [2023-09-01 00:00:00.000 +09:00 | INFO | main:21]: Preparing to startup...
352- [2023-09-01 00:00:00.000 +09:00 | OK | main:22]: Finished preparation to startup.
353- [2023-09-01 00:00:00.000 +09:00 | INFO | main:23]: API version: 0.0.1-000000
354- [2023-09-01 00:00:00.000 +09:00 | INFO | uvicorn.lifespan.on:60]: Application startup complete.
355- [2023-09-01 00:00:00.000 +09:00 | INFO | uvicorn.server:218]: Uvicorn running on http://0.0.0.0:9000 (Press CTRL+C to quit)
356- [2023-09-01 00:00:00.000 +09:00 | DEBUG | anyio._backends._asyncio:833]: [f635ebbc3f2348db9dcff681be1bd52a] 127.0.0.1 - "GET / HTTP/1.1"
357- [2023-09-01 00:00:00.000 +09:00 | OK | anyio._backends._asyncio:833]: [f635ebbc3f2348db9dcff681be1bd52a] 127.0.0.1 - "GET / HTTP/1.1" 200 17B 0.7ms
358- ^C[2023-09-01 00:00:00.000 +09:00 | INFO | uvicorn.server:264]: Shutting down
359- [2023-09-01 00:00:00.000 +09:00 | INFO | uvicorn.lifespan.on:65]: Waiting for application shutdown.
360- [2023-09-01 00:00:00.000 +09:00 | INFO | main:26]: Praparing to shutdown...
361- [2023-09-01 00:00:00.000 +09:00 | OK | main:27]: Finished preparation to shutdown.
362- [2023-09-01 00:00:00.000 +09:00 | INFO | uvicorn.lifespan.on:76]: Application shutdown complete.
363- [2023-09-01 00:00:00.000 +09:00 | INFO | uvicorn.server:86]: Finished server process [17146]
364- ` ` `
217+ - FastAPI HTTP access logging middleware
218+ - Install with pip : ` pip install -U beans-logging[fastapi]` or `pip install -U beans-logging-fastapi`
365219
366220---
367221
@@ -442,3 +296,4 @@ logger:
442296- <https://github.com/Delgan/loguru>
443297- <https://loguru.readthedocs.io/en/stable/api/logger.html>
444298- <https://loguru.readthedocs.io/en/stable/resources/recipes.html>
299+ - <https://github.com/bybatkhuu/module.fastapi-logging>
0 commit comments