Repository navigation
Expand file tree
/
Copy pathlogging_setup.py
More file actions
81 lines (62 loc) · 2.45 KB
/
Copy pathlogging_setup.py
File metadata and controls
81 lines (62 loc) · 2.45 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
"""Logging configuration.
The packaged application has no console (``--windows-console-mode=disable``),
so the log file is the only way a user can hand over something useful for
diagnosis. Nothing that goes through this logger may contain a token, an
authorization code or a stream key.
"""
from __future__ import annotations
import logging
import sys
from logging.handlers import RotatingFileHandler
from pathlib import Path
from platformdirs import user_log_dir
from config_store import APP_AUTHOR, APP_NAME
LOG_FILENAME = "app.log"
MAX_BYTES = 512 * 1024
BACKUP_COUNT = 3
LOG_FORMAT = "%(asctime)s %(levelname)s %(name)s: %(message)s"
def log_directory() -> Path:
"""Return the directory where the application writes its log file."""
return Path(user_log_dir(APP_NAME, APP_AUTHOR))
def log_file_path() -> Path:
"""Return the full path of the application log file."""
return log_directory() / LOG_FILENAME
def configure_logging(level: str = "WARNING") -> Path | None:
"""Configure logging and return the log file path, if it is writable.
Returns ``None`` when the log file cannot be created, in which case only the
console handler (if there is any console) remains active.
"""
handlers: list[logging.Handler] = []
file_path: Path | None = None
console_level = getattr(logging, str(level).upper(), logging.WARNING)
try:
directory = log_directory()
directory.mkdir(parents=True, exist_ok=True)
candidate = log_file_path()
file_handler = RotatingFileHandler(
candidate,
maxBytes=MAX_BYTES,
backupCount=BACKUP_COUNT,
encoding="utf-8",
)
# The file always keeps at least INFO: it is the artefact a user sends
# when asking for help, and an empty file helps nobody.
file_handler.setLevel(min(console_level, logging.INFO))
handlers.append(file_handler)
file_path = candidate
except OSError:
file_path = None
if sys.stderr is not None:
console_handler = logging.StreamHandler(sys.stderr)
console_handler.setLevel(console_level)
handlers.append(console_handler)
if not handlers:
# A windowed build may have neither a writable log file nor a console.
handlers.append(logging.NullHandler())
logging.basicConfig(
level=min(console_level, logging.INFO),
format=LOG_FORMAT,
handlers=handlers,
force=True,
)
return file_path