ue_pe_web/scripts/03_server/src/myserver/log.py
2024-03-05 09:44:45 +01:00

99 lines
2.7 KiB
Python

######################################################################
# Copyright (c) Adrien Luxey-Bitri, Boris Baldassari
#
# This program and the accompanying materials are made
# available under the terms of the Eclipse Public License 2.0
# which is available at https://www.eclipse.org/legal/epl-2.0/
#
# SPDX-License-Identifier: EPL-2.0
######################################################################
"""
A module for learning network programming in Python.
This functions handle the http messages.
"""
from myserver.date import now_rfc2616
def log(msg: str):
"""
Logs a message to stdout, with a timestamp.
Output is: `timestamp - message`.
Parameters
----------
- msg : str
The message string to print.
"""
_time = now_rfc2616()
print(f"{_time} - {msg}")
def log_address(addr: tuple[str, int], msg: str):
"""
Logs a message to stdout, with a timestamp and an address (host:port).
Output is: `timestamp - host:port - message`.
Parameters
----------
- addr: tuple[str, int]
The address to print, as a tuple (host, port)
- msg: str
The message string to print.
"""
_addr = f"{addr[0]}:{addr[1]}"
log(f"{_addr} - {msg}")
def log_request(addr: tuple[str, int], req: dict[str, dict]):
"""
Logs a request message to stdout, with a timestamp and an address (host:port).
Output is: `timestamp - host:port - message`.
Parameters
----------
- addr: tuple[str, int]
The address to print, as a tuple (host, port)
- req: dict[str, dict]
The request to print.
"""
assert 'head' in req \
and 'verb' in req['head'] and 'resource' in req['head']
verb = req['head']['verb']
res = req['head']['resource']
msg = f"{verb} {res}"
if 'params' in req and 'User-Agent' in req['params']:
msg += f" - {req['params']['User-Agent']}"
log_address(addr, msg)
def log_reply(addr: tuple[str, int], req: dict[str, dict], code: int):
"""
Logs a reply message to stdout, with a timestamp and an address (host:port).
Output is: `timestamp - host:port - message`.
Parameters
----------
- addr: tuple[str, int]
The address to print, as a tuple (host, port)
- req: dict[str, dict]
The request to print.
- code: int
The replied code to print.
"""
assert 'head' in req \
and 'verb' in req['head'] and 'resource' in req['head']
verb = req['head']['verb']
res = req['head']['resource']
msg = f"{verb} {res} - {code}"
if 'params' in req and 'User-Agent' in req['params']:
msg += f" - {req['params']['User-Agent']}"
log_address(addr, msg)