Skip to content

Commit 17f03e3

Browse files
committed
logging: use log config
1 parent 87ecacc commit 17f03e3

File tree

3 files changed

+81
-22
lines changed

3 files changed

+81
-22
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: 14 additions & 22 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,7 +61,6 @@ 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()
@@ -101,29 +101,20 @@ def healthy(self):
101101
return "warnet is healthy"
102102

103103
def setup_logging(self):
104-
# Ensure the directory exists
105104
os.makedirs(os.path.dirname(self.log_file_path), exist_ok=True)
106105

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)
106+
with open(LOGGING_CONFIG_PATH) as f:
107+
logging_config = json.load(f)
108+
109+
# Update log file path
110+
logging_config["handlers"]["file"]["filename"] = str(self.log_file_path)
111+
112+
# Apply the config
113+
logging.config.dictConfig(logging_config)
114+
120115
self.logger = logging.getLogger("warnet")
121116
self.logger.info("Logging started")
122117

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-
127118
def log_request():
128119
if not request.path.startswith("/api/"):
129120
self.logger.debug(request.path)
@@ -439,7 +430,7 @@ def thread_start(wn):
439430
wn.apply_network_conditions()
440431
wn.wait_for_health()
441432
self.logger.info(
442-
f"Resumed warnet named '{network}' from config dir {wn.config_dir}"
433+
f"Successfully resumed warnet named '{network}' from config dir {wn.config_dir}"
443434
)
444435
except Exception as e:
445436
trace = traceback.format_exc()
@@ -472,6 +463,7 @@ def thread_start(wn, lock: threading.Lock):
472463
wn.warnet_up()
473464
wn.wait_for_health()
474465
wn.apply_network_conditions()
466+
self.logger.info("Warnet started successfully")
475467
except Exception as e:
476468
trace = traceback.format_exc()
477469
self.logger.error(f"Unhandled exception starting warnet: {e}\n{trace}")

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)