From 66c02ab647365d84e007750b0b583bd55091dc1d Mon Sep 17 00:00:00 2001 From: Batkhuu Date: Thu, 14 Sep 2023 14:15:07 +0900 Subject: [PATCH] :fire: Removed polluted codes. --- README.md | 2 -- beans_logging/fastapi/_formats.py | 6 +----- beans_logging/fastapi/_handlers.py | 26 ++++++++++++++++---------- beans_logging/fastapi/_middlewares.py | 10 +--------- examples/advanced/app.py | 1 - examples/advanced/configs/logger.yml | 1 - 6 files changed, 18 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 96e3c2a..c188850 100644 --- a/README.md +++ b/README.md @@ -251,7 +251,6 @@ logger: http_std_debug_format: '[{request_id}] {client_host} {user_id} "{method} {url_path} HTTP/{http_version}"' http_std_msg_format: '[{request_id}] {client_host} {user_id} "{method} {url_path} HTTP/{http_version}" {status_code} {content_length}B {response_time}ms' http_file_enabled: true - http_file_msg_format: '{client_host} {request_id} {user_id} [{datetime}] "{method} {url_path} HTTP/{http_version}" {status_code} {content_length} "{h_referer}" "{h_user_agent}" {response_time}' http_log_path: "http/{app_name}.http.access.log" http_err_path: "http/{app_name}.http.err.log" http_json_enabled: true @@ -325,7 +324,6 @@ app.add_middleware( has_proxy_headers=True, debug_format=logger_loader.config.extra.http_std_debug_format, msg_format=logger_loader.config.extra.http_std_msg_format, - file_msg_format=logger_loader.config.extra.http_file_msg_format, ) @app.get("/") diff --git a/beans_logging/fastapi/_formats.py b/beans_logging/fastapi/_formats.py index b8c8b01..a9c842e 100644 --- a/beans_logging/fastapi/_formats.py +++ b/beans_logging/fastapi/_formats.py @@ -22,11 +22,7 @@ def http_file_format(record: dict) -> str: _http_info["datetime"] = record["time"].isoformat() record["extra"]["http_info"] = _http_info - _msg_format = _MSG_FORMAT - if "http_file_msg_format" in record["extra"]: - _msg_format = record["extra"]["http_file_msg_format"] - - _msg = _msg_format.format(**_http_info) + _msg = _MSG_FORMAT.format(**_http_info) record["http_message"] = _msg return "{http_message}\n" diff --git a/beans_logging/fastapi/_handlers.py b/beans_logging/fastapi/_handlers.py index 2fc9fb4..a8eae50 100644 --- a/beans_logging/fastapi/_handlers.py +++ b/beans_logging/fastapi/_handlers.py @@ -1,5 +1,7 @@ # -*- coding: utf-8 -*- +from typing import Union, Callable + from pydantic import validate_call from beans_logging import LoggerLoader @@ -13,20 +15,22 @@ def add_http_file_handler( logger_loader: LoggerLoader, log_path: str = "http/{app_name}.http.access.log", err_path: str = "http/{app_name}.http.err.log", + formatter: Union[Callable, str] = http_file_format, ): """Add http access log file and error file handler. Args: - logger_loader (LoggerLoader, required): LoggerLoader instance. - log_path (str, optional): Log file path. Defaults to "http/{app_name}.http.access.log". - err_path (str, optional): Error log file path. Defaults to "http/{app_name}.http.err.log". + logger_loader (LoggerLoader, required): LoggerLoader instance. + log_path (str, optional): Log file path. Defaults to "http/{app_name}.http.access.log". + err_path (str, optional): Error log file path. Defaults to "http/{app_name}.http.err.log". + formatter (Union[Callable, str], optional): Log formatter. Defaults to `http_file_format` function. """ logger_loader.add_custom_handler( handler_name="FILE.HTTP", sink=log_path, filter=use_http_filter, - format=http_file_format, + format=formatter, ) logger_loader.add_custom_handler( @@ -34,7 +38,7 @@ def add_http_file_handler( sink=err_path, level="WARNING", filter=use_http_filter, - format=http_file_format, + format=formatter, ) @@ -43,20 +47,22 @@ def add_http_file_json_handler( logger_loader: LoggerLoader, log_path: str = "json.http/{app_name}.json.http.access.log", err_path: str = "json.http/{app_name}.json.http.err.log", + formatter: Union[Callable, str] = http_file_json_format, ): """Add http access json log file and json error file handler. Args: - logger_loader (LoggerLoader, required): LoggerLoader instance. - log_path (str, optional): Json log file path. Defaults to "http.json/{app_name}.json.http.access.log". - err_path (str, optional): Json error log file path. Defaults to "http.json/{app_name}.json.http.err.log". + logger_loader (LoggerLoader, required): LoggerLoader instance. + log_path (str, optional): Json log file path. Defaults to "http.json/{app_name}.json.http.access.log". + err_path (str, optional): Json error log file path. Defaults to "http.json/{app_name}.json.http.err.log". + formatter (Union[Callable, str], optional): Log formatter. Defaults to `http_file_json_format` function. """ logger_loader.add_custom_handler( handler_name="FILE.JSON.HTTP", sink=log_path, filter=use_http_filter, - format=http_file_json_format, + format=formatter, ) logger_loader.add_custom_handler( @@ -64,5 +70,5 @@ def add_http_file_json_handler( sink=err_path, level="WARNING", filter=use_http_filter, - format=http_file_json_format, + format=formatter, ) diff --git a/beans_logging/fastapi/_middlewares.py b/beans_logging/fastapi/_middlewares.py index 2f686d2..1a01729 100644 --- a/beans_logging/fastapi/_middlewares.py +++ b/beans_logging/fastapi/_middlewares.py @@ -20,18 +20,15 @@ class HttpAccessLogMiddleware(BaseHTTPMiddleware): Attributes: _DEBUG_FORMAT (str ): Default http access log debug message format. Defaults to '[{request_id}] {client_host} {user_id} "{method} {url_path} HTTP/{http_version}"'. _MSG_FORMAT (str ): Default http access log message format. Defaults to '[{request_id}] {client_host} {user_id} "{method} {url_path} HTTP/{http_version}" {status_code} {content_length}B {response_time}ms'. - _FILE_MSG_FORMAT (str ): Default http access log file message format. Defaults to '{client_host} {request_id} {user_id} [{datetime}] "{method} {url_path} HTTP/{http_version}" {status_code} {content_length} "{h_referer}" "{h_user_agent}" {response_time}'. has_proxy_headers (bool): If True, use proxy headers to get http request info. Defaults to False. has_cf_headers (bool): If True, use cloudflare headers to get http request info. Defaults to False. debug_format (str ): Http access log debug message format. Defaults to `HttpAccessLogMiddleware._DEBUG_FORMAT`. msg_format (str ): Http access log message format. Defaults to `HttpAccessLogMiddleware._MSG_FORMAT`. - file_msg_format (str ): Http access log file message format. Defaults to `HttpAccessLogMiddleware._FILE_MSG_FORMAT`. """ _DEBUG_FORMAT = '[{request_id}] {client_host} {user_id} "{method} {url_path} HTTP/{http_version}"' _MSG_FORMAT = '[{request_id}] {client_host} {user_id} "{method} {url_path} HTTP/{http_version}" {status_code} {content_length}B {response_time}ms' - _FILE_MSG_FORMAT = '{client_host} {request_id} {user_id} [{datetime}] "{method} {url_path} HTTP/{http_version}" {status_code} {content_length} "{h_referer}" "{h_user_agent}" {response_time}' def __init__( self, @@ -40,14 +37,12 @@ def __init__( has_cf_headers: bool = False, debug_format: str = _DEBUG_FORMAT, msg_format: str = _MSG_FORMAT, - file_msg_format: str = _FILE_MSG_FORMAT, ): super().__init__(app) self.has_proxy_headers = has_proxy_headers self.has_cf_headers = has_cf_headers self.debug_format = debug_format self.msg_format = msg_format - self.file_msg_format = file_msg_format async def dispatch(self, request: Request, call_next) -> Response: _logger = logger.opt(colors=True, record=True) @@ -236,10 +231,7 @@ async def dispatch(self, request: Request, call_next) -> Response: _msg = _msg_format.format(**_http_info) # _logger.bind(http_info=_http_info).log(_LEVEL, _msg) await run_in_threadpool( - _logger.bind( - http_info=_http_info, - http_file_msg_format=self.file_msg_format, - ).log, + _logger.bind(http_info=_http_info).log, _LEVEL, _msg, ) diff --git a/examples/advanced/app.py b/examples/advanced/app.py index e9269d8..70cba6f 100755 --- a/examples/advanced/app.py +++ b/examples/advanced/app.py @@ -33,7 +33,6 @@ async def lifespan(app: FastAPI): has_proxy_headers=True, debug_format=logger_loader.config.extra.http_std_debug_format, msg_format=logger_loader.config.extra.http_std_msg_format, - file_msg_format=logger_loader.config.extra.http_file_msg_format, ) diff --git a/examples/advanced/configs/logger.yml b/examples/advanced/configs/logger.yml index 40b94fb..e1d60c0 100644 --- a/examples/advanced/configs/logger.yml +++ b/examples/advanced/configs/logger.yml @@ -34,7 +34,6 @@ logger: http_std_debug_format: '[{request_id}] {client_host} {user_id} "{method} {url_path} HTTP/{http_version}"' http_std_msg_format: '[{request_id}] {client_host} {user_id} "{method} {url_path} HTTP/{http_version}" {status_code} {content_length}B {response_time}ms' http_file_enabled: true - http_file_msg_format: '{client_host} {request_id} {user_id} [{datetime}] "{method} {url_path} HTTP/{http_version}" {status_code} {content_length} "{h_referer}" "{h_user_agent}" {response_time}' http_log_path: "http/{app_name}.http.access.log" http_err_path: "http/{app_name}.http.err.log" http_json_enabled: true