This repository was archived by the owner on Aug 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathlog.py
More file actions
75 lines (64 loc) · 2.29 KB
/
log.py
File metadata and controls
75 lines (64 loc) · 2.29 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
# Copyright (C) Fabulously Optimized 2023
# Licensed under the MIT License. The full license text can be found at https://github.com/Fabulously-Optimized/vanilla-installer/blob/main/LICENSE.md.
"""
Starts logging for Vanilla Installer.
"""
import logging
import logging.handlers # pylance moment
import sys
from pathlib import Path
class LoggerWriter:
def __init__(self, logfct):
self.logfct = logfct
self.buf = []
def write(self, msg):
if msg.endswith("\n"):
self.buf.append(msg.removesuffix("\n"))
self.logfct("".join(self.buf))
self.buf = []
else:
self.buf.append(msg)
def flush(self):
pass
logger = logging.getLogger(__name__)
try:
if log_setup is not True: # noqa: F821
log_setup = False
logger.setLevel(logging.DEBUG)
logfile_path = Path("./logs").resolve() / "vanilla_installer.log"
if logfile_path.exists() is False:
Path("./logs").resolve().mkdir(exist_ok=True)
with logfile_path as file:
open(file, "x", encoding="utf-8").write("")
handler = logging.handlers.RotatingFileHandler(
filename=logfile_path,
encoding="utf-8",
maxBytes=32 * 1024 * 1024, # 32 MiB
backupCount=5, # Rotate through 5 files
)
except UnboundLocalError:
log_setup = False
logger.setLevel(logging.DEBUG)
logfile_path = Path("./logs").resolve() / "vanilla_installer.log"
if logfile_path.exists() is False:
Path("./logs").resolve().mkdir(exist_ok=True)
with logfile_path as file:
open(file, "x", encoding="utf-8").write("")
handler = logging.handlers.RotatingFileHandler(
filename=logfile_path,
encoding="utf-8",
maxBytes=32 * 1024 * 1024, # 32 MiB
backupCount=5, # Rotate through 5 files
)
dt_fmt = "%Y-%m-%d %H:%M:%S"
formatter = logging.Formatter(
"[{asctime}] [{levelname:<8}] {name}: {message}", dt_fmt, style="{"
)
handler.setFormatter(formatter)
logger.addHandler(handler)
# To access the original stdout/stderr, use sys.__stdout__/sys.__stderr__
sys.stdout = LoggerWriter(logger.info)
sys.stderr = LoggerWriter(logger.error)
log_setup = True
def setup_logging() -> logging.Logger:
return logger