Repository navigation
Expand file tree
/
Copy pathruntime.py
More file actions
156 lines (136 loc) · 4.91 KB
/
Copy pathruntime.py
File metadata and controls
156 lines (136 loc) · 4.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
"""Runtime logging and Uvicorn bootstrap helpers."""
from __future__ import annotations
import copy
import logging
from pathlib import Path
import re
import tempfile
import time
from typing import Any
import uvicorn
from fastapi import FastAPI
from utility.log import LOGI
from uvicorn.logging import AccessFormatter, DefaultFormatter
from config import BASE_DIR, environment_settings
LOG_DIRECTORY = BASE_DIR / "logs"
LOG_MAX_BYTES = 5 * 1024 * 1024
LOG_BACKUP_COUNT = 3
LOG_DATE_FORMAT = "%Y-%m-%dT%H:%M:%S%z"
_CONTROL_CHARACTER_PATTERN = re.compile(r"[\x00-\x1f\x7f]")
_QUERY_IN_MESSAGE_PATTERN = re.compile(r"\?[^\s\"']+")
def ensure_log_directory(log_directory: str | Path = LOG_DIRECTORY) -> Path:
path = Path(log_directory)
try:
path.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(prefix=".write-test-", dir=path):
pass
except OSError as exc:
raise RuntimeError(f"Log directory is not writable: {path}") from exc
return path
def _redact_access_path(full_path: object) -> str:
normalized = _CONTROL_CHARACTER_PATTERN.sub(
lambda match: {"\t": r"\t", "\n": r"\n", "\r": r"\r"}.get(
match.group(),
f"\\x{ord(match.group()):02x}",
),
str(full_path),
)
path, separator, _query = normalized.partition("?")
return f"{path}?<redacted>" if separator else path
class RedactingErrorFormatter(DefaultFormatter):
converter = time.gmtime
def format(self, record: logging.LogRecord) -> str:
message = super().format(record)
return _QUERY_IN_MESSAGE_PATTERN.sub("?<redacted>", message)
class RedactingAccessFormatter(AccessFormatter):
converter = time.gmtime
def formatMessage(self, record: logging.LogRecord) -> str:
if isinstance(record.args, tuple) and len(record.args) == 5:
record = copy.copy(record)
client_addr, method, full_path, http_version, status_code = record.args
record.args = (
client_addr,
method,
_redact_access_path(full_path),
http_version,
status_code,
)
return super().formatMessage(record)
def build_uvicorn_log_config(log_directory: str | Path) -> dict[str, Any]:
path = Path(log_directory)
return {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"default": {
"()": RedactingErrorFormatter,
"fmt": "%(asctime)s %(levelprefix)s %(message)s",
"datefmt": LOG_DATE_FORMAT,
"use_colors": False,
},
"access": {
"()": RedactingAccessFormatter,
"fmt": '%(asctime)s %(client_addr)s - "%(request_line)s" %(status_code)s',
"datefmt": LOG_DATE_FORMAT,
"use_colors": False,
},
},
"handlers": {
"default_console": {
"class": "logging.StreamHandler",
"formatter": "default",
"stream": "ext://sys.stderr",
},
"access_console": {
"class": "logging.StreamHandler",
"formatter": "access",
"stream": "ext://sys.stdout",
},
"error_file": {
"class": "logging.handlers.RotatingFileHandler",
"formatter": "default",
"filename": str(path / "uvicorn-error.log"),
"maxBytes": LOG_MAX_BYTES,
"backupCount": LOG_BACKUP_COUNT,
"encoding": "utf-8",
},
"access_file": {
"class": "logging.handlers.RotatingFileHandler",
"formatter": "access",
"filename": str(path / "uvicorn-access.log"),
"maxBytes": LOG_MAX_BYTES,
"backupCount": LOG_BACKUP_COUNT,
"encoding": "utf-8",
},
},
"loggers": {
"uvicorn": {
"handlers": ["default_console", "error_file"],
"level": "INFO",
"propagate": False,
},
"uvicorn.error": {
"handlers": [],
"level": "INFO",
"propagate": True,
},
"uvicorn.access": {
"handlers": ["access_console", "access_file"],
"level": "INFO",
"propagate": False,
},
},
}
def run_web_server(app: FastAPI, *, log_directory: str | Path) -> None:
selected = environment_settings()
host = str(getattr(selected, "web_host", "127.0.0.1"))
port = int(getattr(selected, "web_port", 8888))
LOGI(f"Starting web application at http://{host}:{port}")
uvicorn.run(
app,
host=host,
port=port,
log_level="info",
log_config=build_uvicorn_log_config(log_directory),
access_log=True,
)