Skip to content

Commit 2be8aa6

Browse files
authored
Merge pull request #299 from willcl-ark/tidy-up-logging
2 parents c602118 + 3f12e2a commit 2be8aa6

File tree

4 files changed

+87
-25
lines changed

4 files changed

+87
-25
lines changed

src/logging_config/config.json

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
{
2+
"version": 1,
3+
"disable_existing_loggers": false,
4+
"formatters": {
5+
"simple": {
6+
"format": " %(asctime)s - %(levelname)s - %(message)s",
7+
"datefmt": "%Y-%m-%dT%H:%M:%S%z"
8+
},
9+
"detailed": {
10+
"format": " %(asctime)s - %(levelname)s - [%(module)s|L%(lineno)d] - %(message)s",
11+
"datefmt": "%Y-%m-%dT%H:%M:%S%z"
12+
}
13+
},
14+
"filters": {
15+
"no_errors": {
16+
"()": "warnet.utils.NonErrorFilter"
17+
}
18+
},
19+
"handlers": {
20+
"stdout": {
21+
"class": "logging.StreamHandler",
22+
"level": "DEBUG",
23+
"formatter": "simple",
24+
"filters": ["no_errors"],
25+
"stream": "ext://sys.stdout"
26+
},
27+
"stderr": {
28+
"class": "logging.StreamHandler",
29+
"level": "WARNING",
30+
"formatter": "simple",
31+
"stream": "ext://sys.stderr"
32+
},
33+
"file": {
34+
"class": "logging.handlers.RotatingFileHandler",
35+
"level": "DEBUG",
36+
"formatter": "detailed",
37+
"filename": "warnet.log",
38+
"maxBytes": 16000000,
39+
"backupCount": 3
40+
}
41+
},
42+
"loggers": {
43+
"root": {
44+
"level": "DEBUG",
45+
"handlers": [
46+
"stdout",
47+
"stderr",
48+
"file"
49+
]
50+
},
51+
"urllib3.connectionpool": {
52+
"level": "WARNING",
53+
"propagate": 1
54+
},
55+
56+
"kubernetes.client.rest": {
57+
"level": "WARNING",
58+
"propagate": 1
59+
}
60+
}
61+
}

src/warnet/server.py

Lines changed: 16 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import argparse
22
import base64
3+
import json
34
import logging
5+
import logging.config
46
import os
57
import pkgutil
68
import platform
@@ -14,8 +16,6 @@
1416
import traceback
1517
from datetime import datetime
1618
from io import BytesIO
17-
from logging import StreamHandler
18-
from logging.handlers import RotatingFileHandler
1919
from pathlib import Path
2020

2121
import jsonschema
@@ -35,6 +35,7 @@
3535

3636
WARNET_SERVER_PORT = 9276
3737
CONFIG_DIR_ALREADY_EXISTS = 32001
38+
LOGGING_CONFIG_PATH = Path("src/logging_config/config.json")
3839

3940

4041
class Server:
@@ -60,12 +61,10 @@ def __init__(self, backend):
6061
self.jsonrpc = JSONRPC(self.app, "/api")
6162

6263
self.log_file_path = os.path.join(self.basedir, "warnet.log")
63-
self.logger: logging.Logger
6464
self.setup_global_exception_handler()
6565
self.setup_logging()
6666
self.setup_rpc()
6767
self.logger.info("Started server")
68-
self.app.add_url_rule("/-/healthy", view_func=self.healthy)
6968

7069
# register a well known /-/healthy endpoint for liveness tests
7170
# we regard warnet as healthy if the http server is up
@@ -101,30 +100,23 @@ def healthy(self):
101100
return "warnet is healthy"
102101

103102
def setup_logging(self):
104-
# Ensure the directory exists
105103
os.makedirs(os.path.dirname(self.log_file_path), exist_ok=True)
106104

107-
# Configure root logger
108-
logging.basicConfig(
109-
level=logging.DEBUG,
110-
handlers=[
111-
RotatingFileHandler(
112-
self.log_file_path, maxBytes=16_000_000, backupCount=3, delay=True
113-
),
114-
StreamHandler(sys.stdout),
115-
],
116-
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
117-
)
118-
# Disable urllib3.connectionpool logging
119-
logging.getLogger("urllib3.connectionpool").setLevel(logging.CRITICAL)
105+
with open(LOGGING_CONFIG_PATH) as f:
106+
logging_config = json.load(f)
107+
108+
# Update log file path
109+
logging_config["handlers"]["file"]["filename"] = str(self.log_file_path)
110+
111+
# Apply the config
112+
logging.config.dictConfig(logging_config)
113+
120114
self.logger = logging.getLogger("warnet")
121115
self.logger.info("Logging started")
122116

123-
if self.backend == "k8s":
124-
# if using k8s as a backend, tone the logging down
125-
logging.getLogger("kubernetes.client.rest").setLevel(logging.WARNING)
126-
127117
def log_request():
118+
if "healthy" in request.path:
119+
return # No need to log all these
128120
if not request.path.startswith("/api/"):
129121
self.logger.debug(request.path)
130122
else:
@@ -439,7 +431,7 @@ def thread_start(wn):
439431
wn.apply_network_conditions()
440432
wn.wait_for_health()
441433
self.logger.info(
442-
f"Resumed warnet named '{network}' from config dir {wn.config_dir}"
434+
f"Successfully resumed warnet named '{network}' from config dir {wn.config_dir}"
443435
)
444436
except Exception as e:
445437
trace = traceback.format_exc()
@@ -472,6 +464,7 @@ def thread_start(wn, lock: threading.Lock):
472464
wn.warnet_up()
473465
wn.wait_for_health()
474466
wn.apply_network_conditions()
467+
self.logger.info("Warnet started successfully")
475468
except Exception as e:
476469
trace = traceback.format_exc()
477470
self.logger.error(f"Unhandled exception starting warnet: {e}\n{trace}")

src/warnet/tank.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,12 +62,13 @@ def _parse_version(self):
6262

6363
def parse_graph_node(self, node):
6464
# Dynamically parse properties based on the schema
65+
graph_properties = {}
6566
for property, specs in self.warnet.node_schema["properties"].items():
6667
value = node.get(property, specs.get("default"))
6768
if property == "version":
6869
self._parse_version()
6970
setattr(self, property, value)
70-
logger.debug(f"{property}={value}")
71+
graph_properties[property] = value
7172

7273
if self.version and self.image:
7374
raise Exception(
@@ -83,7 +84,8 @@ def parse_graph_node(self, node):
8384

8485
self.config_dir = self.warnet.config_dir / str(self.suffix)
8586
self.config_dir.mkdir(parents=True, exist_ok=True)
86-
logger.debug(f"{self=:}")
87+
88+
logger.debug(f"Parsed graph node: {self.index} with attributes: {[f'{key}={value}' for key, value in graph_properties.items()]}")
8789

8890
@classmethod
8991
def from_graph_node(cls, index, warnet, tank=None):

src/warnet/utils.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,12 @@
3636
NODE_SCHEMA_PATH = SCHEMA / "node_schema.json"
3737

3838

39+
class NonErrorFilter(logging.Filter):
40+
41+
def filter(self, record: logging.LogRecord) -> bool | logging.LogRecord:
42+
return record.levelno <= logging.INFO
43+
44+
3945
def exponential_backoff(max_retries=5, base_delay=1, max_delay=32):
4046
"""
4147
A decorator for exponential backoff.

0 commit comments

Comments
 (0)