-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathlogger.py
More file actions
86 lines (67 loc) · 2.3 KB
/
logger.py
File metadata and controls
86 lines (67 loc) · 2.3 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
"""Simple logging to stdout the same way Proton does"""
import os
import sys
from enum import Enum
from pathlib import Path
# Enums
class LogLevel(Enum):
"""Enum and mapping (level -> color) for log levels"""
RESET = '\u001b[0m'
INFO = '\u001b[34m'
WARN = '\u001b[33m'
CRIT = '\u001b[31m'
DEBUG = '\u001b[35m'
class Log:
"""Log to stderr for steam dumps"""
pfx = f'ProtonFixes[{os.getpid()}]'
is_tty = os.isatty(sys.stderr.fileno())
_cache_root = Path(os.getenv('XDG_CACHE_HOME', '~/.cache')).expanduser()
_log_dir = _cache_root / 'protonfixes'
try:
_log_dir.mkdir(parents=True, exist_ok=True)
logfile = _log_dir / 'protonfixes.log'
except Exception:
# Fallback if the cache dir can't be created for any reason
logfile = Path('/tmp/protonfixes.log')
@classmethod
def __colorize(cls, msg: str, level: LogLevel) -> str:
if not cls.is_tty:
return msg
color = level.value
reset = LogLevel.RESET.value
return f'{color}{msg}{reset}'
@classmethod
def __call__(cls, msg: str) -> None:
"""Allows the Log instance to be called directly"""
cls.log(msg)
@classmethod
def log(cls, msg: str = '', level: LogLevel = LogLevel.INFO) -> None:
"""Prints the log message to stdout the same way as Proton"""
# To terminal
print(
cls.__colorize(f'{cls.pfx} {level.name}: {msg}', level),
file=sys.stderr,
flush=True,
)
# To log file
with open(cls.logfile, 'a', buffering=1, encoding='utf-8') as testfile:
print(f'{cls.pfx} {level.name}: {msg}', file=testfile)
@classmethod
def info(cls, msg: str) -> None:
"""Wrapper for printing info messages"""
cls.log(msg, LogLevel.INFO)
@classmethod
def warn(cls, msg: str) -> None:
"""Wrapper for printing warning messages"""
cls.log(msg, LogLevel.WARN)
@classmethod
def crit(cls, msg: str) -> None:
"""Wrapper for printing critical messages"""
cls.log(msg, LogLevel.CRIT)
@classmethod
def debug(cls, msg: str) -> None:
"""Wrapper for printing debug messages"""
if 'DEBUG' not in os.environ:
return
cls.log(msg, LogLevel.DEBUG)
log = Log()