Skip to content
This repository was archived by the owner on Aug 22, 2023. It is now read-only.

Commit 29a683d

Browse files
committed
refactor(logging): 🔊 improve logging
Add a class to redirect stdout/stderr to the logfile, allowing errors to be printed to the logfile even if stdout is not shown (e.g. on GUI builds)
1 parent 0527986 commit 29a683d

1 file changed

Lines changed: 30 additions & 14 deletions

File tree

vanilla_installer/log.py

Lines changed: 30 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,35 +3,51 @@
33
"""Starts logging for Vanilla Installer."""
44
import logging
55
import logging.handlers # pylance moment
6-
import pathlib
6+
from pathlib import Path
7+
import sys
8+
9+
10+
class LoggerWriter:
11+
def __init__(self, logfct):
12+
self.logfct = logfct
13+
self.buf = []
14+
15+
def write(self, msg):
16+
if msg.endswith('\n'):
17+
self.buf.append(msg.removesuffix('\n'))
18+
self.logfct(''.join(self.buf))
19+
self.buf = []
20+
else:
21+
self.buf.append(msg)
22+
23+
def flush(self):
24+
pass
25+
726

827
logger = logging.getLogger()
928
logger.setLevel(logging.DEBUG)
10-
logfile_path = str(pathlib.Path("./logs").resolve() / "vanilla_installer.log")
11-
try:
12-
handler = logging.handlers.RotatingFileHandler(
13-
filename=logfile_path,
14-
encoding="utf-8",
15-
maxBytes=32 * 1024 * 1024, # 32 MiB
16-
backupCount=5, # Rotate through 5 files
17-
)
18-
except FileNotFoundError:
19-
print("WARNING | Log file not found, creating...")
20-
pathlib.Path("./logs").mkdir(exist_ok=True)
21-
with pathlib.Path("./logs").resolve() / "vanilla_installer.log" as file:
29+
logfile_path = Path("./logs").resolve() / "vanilla_installer.log"
30+
if logfile_path.exists() is False:
31+
Path("./logs").resolve().mkdir(exist_ok=True)
32+
with logfile_path as file:
2233
open(file, "x", encoding="utf-8").write("")
23-
handler = logging.handlers.RotatingFileHandler(
34+
handler = logging.handlers.RotatingFileHandler(
2435
filename=logfile_path,
2536
encoding="utf-8",
2637
maxBytes=32 * 1024 * 1024, # 32 MiB
2738
backupCount=5, # Rotate through 5 files
2839
)
40+
2941
dt_fmt = "%Y-%m-%d %H:%M:%S"
3042
formatter = logging.Formatter(
3143
"[{asctime}] [{levelname:<8}] {name}: {message}", dt_fmt, style="{"
3244
)
3345
handler.setFormatter(formatter)
3446
logger.addHandler(handler)
3547

48+
# To access the original stdout/stderr, use sys.__stdout__/sys.__stderr__
49+
sys.stdout = LoggerWriter(logger.info)
50+
sys.stderr = LoggerWriter(logger.error)
51+
3652
logging.info("Starting Vanilla Installer")
3753
logger = logging.getLogger("Vanilla Installer")

0 commit comments

Comments
 (0)