Log remote address if available (#2207)

* Log remote address if available

* Add tests

* Fix testing version

Co-authored-by: Adam Hopkins <adam@amhopkins.com>
This commit is contained in:
Néstor Pérez 2021-08-02 11:41:47 +02:00 committed by GitHub
parent 7dd4a78cf2
commit 54ca6a6178
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 57 additions and 6 deletions

View File

@ -452,8 +452,8 @@ class Http:
"request": "nil", "request": "nil",
} }
if req is not None: if req is not None:
if req.ip: if req.remote_addr or req.ip:
extra["host"] = f"{req.ip}:{req.port}" extra["host"] = f"{req.remote_addr or req.ip}:{req.port}"
extra["request"] = f"{req.method} {req.url}" extra["request"] = f"{req.method} {req.url}"
access_logger.info("", extra=extra) access_logger.info("", extra=extra)

View File

@ -93,7 +93,7 @@ requirements = [
] ]
tests_require = [ tests_require = [
"sanic-testing>=0.7.0b1", "sanic-testing==0.7.0b1",
"pytest==5.2.1", "pytest==5.2.1",
"coverage==5.3", "coverage==5.3",
"gunicorn==20.0.4", "gunicorn==20.0.4",

View File

@ -5,6 +5,7 @@ import uuid
from importlib import reload from importlib import reload
from io import StringIO from io import StringIO
from unittest.mock import Mock
import pytest import pytest
@ -51,7 +52,7 @@ def test_log(app):
def test_logging_defaults(): def test_logging_defaults():
# reset_logging() # reset_logging()
app = Sanic("test_logging") Sanic("test_logging")
for fmt in [h.formatter for h in logging.getLogger("sanic.root").handlers]: for fmt in [h.formatter for h in logging.getLogger("sanic.root").handlers]:
assert ( assert (
@ -87,7 +88,7 @@ def test_logging_pass_customer_logconfig():
"format" "format"
] = "%(asctime)s - (%(name)s)[%(levelname)s]: %(message)s" ] = "%(asctime)s - (%(name)s)[%(levelname)s]: %(message)s"
app = Sanic("test_logging", log_config=modified_config) Sanic("test_logging", log_config=modified_config)
for fmt in [h.formatter for h in logging.getLogger("sanic.root").handlers]: for fmt in [h.formatter for h in logging.getLogger("sanic.root").handlers]:
assert fmt._fmt == modified_config["formatters"]["generic"]["format"] assert fmt._fmt == modified_config["formatters"]["generic"]["format"]
@ -208,6 +209,56 @@ def test_logging_modified_root_logger_config():
modified_config = LOGGING_CONFIG_DEFAULTS modified_config = LOGGING_CONFIG_DEFAULTS
modified_config["loggers"]["sanic.root"]["level"] = "DEBUG" modified_config["loggers"]["sanic.root"]["level"] = "DEBUG"
app = Sanic("test_logging", log_config=modified_config) Sanic("test_logging", log_config=modified_config)
assert logging.getLogger("sanic.root").getEffectiveLevel() == logging.DEBUG assert logging.getLogger("sanic.root").getEffectiveLevel() == logging.DEBUG
def test_access_log_client_ip_remote_addr(monkeypatch):
access = Mock()
monkeypatch.setattr(sanic.http, "access_logger", access)
app = Sanic("test_logging")
app.config.PROXIES_COUNT = 2
@app.route("/")
async def handler(request):
return text(request.remote_addr)
headers = {"X-Forwarded-For": "1.1.1.1, 2.2.2.2"}
request, response = app.test_client.get("/", headers=headers)
assert request.remote_addr == "1.1.1.1"
access.info.assert_called_with(
"",
extra={
"status": 200,
"byte": len(response.content),
"host": f"{request.remote_addr}:{request.port}",
"request": f"GET {request.scheme}://{request.host}/",
},
)
def test_access_log_client_ip_reqip(monkeypatch):
access = Mock()
monkeypatch.setattr(sanic.http, "access_logger", access)
app = Sanic("test_logging")
@app.route("/")
async def handler(request):
return text(request.ip)
request, response = app.test_client.get("/")
access.info.assert_called_with(
"",
extra={
"status": 200,
"byte": len(response.content),
"host": f"{request.ip}:{request.port}",
"request": f"GET {request.scheme}://{request.host}/",
},
)