Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update server log messages to include specific addresses #2521

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,9 @@ async def test_request_than_limit_max_requests_warn_log(
responses = await asyncio.gather(*tasks)
assert len(responses) == 2
assert "Maximum request limit of 1 exceeded. Terminating process." in caplog.text


async def test_log_messages_for_all_addresses(unused_tcp_port: int, caplog: pytest.LogCaptureFixture):
config = Config(app=app, host="0.0.0.0", port=unused_tcp_port)
async with run_server(config):
assert f"Running on http://127.0.0.1:{unused_tcp_port}" in caplog.text
24 changes: 24 additions & 0 deletions uvicorn/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,24 @@
logger = logging.getLogger("uvicorn.error")


def get_interface_ip(family: socket.AddressFamily) -> str:
"""Get the IP address of an external interface. Used when binding to
0.0.0.0 or ::1 to show a more useful URL.

:meta private:
"""
# arbitrary private address
host = "fd31:f903:5ab5:1::1" if family == socket.AF_INET6 else "10.253.155.219"

with socket.socket(family, socket.SOCK_DGRAM) as s:
try:
s.connect((host, 58162))
except OSError:
return "::1" if family == socket.AF_INET6 else "127.0.0.1"

return s.getsockname()[0]


class ServerState:
"""
Shared servers state that is available between all protocol instances.
Expand Down Expand Up @@ -219,6 +237,12 @@ def _log_started_message(self, listeners: Sequence[socket.SocketType]) -> None:
extra={"color_message": color_message},
)

if host == "0.0.0.0":
localhost = "127.0.0.1"
display_hostname = get_interface_ip(socket.AF_INET)
logger.info(f"Running on {protocol_name}://{localhost}:{port}")
logger.info(f"Running on {protocol_name}://{display_hostname}:{port}")

async def main_loop(self) -> None:
counter = 0
should_exit = await self.on_tick(counter)
Expand Down
Loading