From 6f3df5fc516717020d7295768fbd1d3abf8b5d05 Mon Sep 17 00:00:00 2001 From: wangjiacai Date: Tue, 18 Apr 2023 01:28:58 +0800 Subject: [PATCH] fix wrong ip address behind proxy --- project/__init__.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/project/__init__.py b/project/__init__.py index 2f1f7b0..e84244b 100644 --- a/project/__init__.py +++ b/project/__init__.py @@ -60,6 +60,13 @@ logger = logging.getLogger('waitress') logger.setLevel(app.config['LOGGING_LEVEL']) +def get_actual_addr(request): + ip = request.remote_addr + if request.headers.getlist("X-Forwarded-For"): + ip = request.headers.getlist("X-Forwarded-For")[0] + return ip + + @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static'), @@ -69,14 +76,14 @@ def favicon(): @app.before_request def before_request(): timestamp = time.strftime('[%Y-%b-%d %H:%M]') - logger.info('%s > %s %s %s %s', timestamp, request.remote_addr, + logger.info('%s > %s %s %s %s', timestamp, get_actual_addr(request), request.method, request.scheme, request.full_path) @app.after_request def after_request(response): timestamp = time.strftime('[%Y-%b-%d %H:%M]') - logger.info('%s < %s %s %s %s %s', timestamp, request.remote_addr, + logger.info('%s < %s %s %s %s %s', timestamp, get_actual_addr(request), request.method, request.scheme, request.full_path, response.status) return response @@ -86,5 +93,5 @@ def exceptions(e): tb = traceback.format_exc() timestamp = time.strftime('[%Y-%b-%d %H:%M]') logger.error('%s %s %s %s %s 5xx INTERNAL SERVER ERROR\n%s', timestamp, - request.remote_addr, request.method, request.scheme, request.full_path, tb) + get_actual_addr(request), request.method, request.scheme, request.full_path, tb) return e.status_code