Repository navigation
Expand file tree
/
Copy pathscript.py
More file actions
150 lines (117 loc) · 5.21 KB
/
Copy pathscript.py
File metadata and controls
150 lines (117 loc) · 5.21 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
"""
{Script Name}
{Summary of what the script does}
{How to use the script}
"""
from datetime import datetime, timedelta
from pathlib import Path
import logging
import sys
__version__ = "0.0.0"
logger = logging.getLogger(__name__)
def main() -> None:
logger.info("Code goes here")
def setup_logging(
log_folder: Path = Path("Logs"),
console_level: int = logging.INFO,
file_level: int = logging.DEBUG,
enable_file_logging: bool = True,
max_log_files: int | None = 30,
max_log_age: timedelta | None = None,
date_format: str = "%Y-%m-%dT%H:%M:%S",
console_message_format: str = "%(message)s",
file_message_format: str = "%(asctime)s.%(msecs)03d [%(levelname)s] %(message)s",
) -> Path | None:
"""
Configure console and optional file logging for this script.
Existing handlers on the root logger are closed and replaced. When
file logging is enabled, logs are written to ``log_folder`` and old logs
for this script are pruned according to ``max_log_files`` and
``max_log_age``.
To put logs in a script-specific folder under the user's AppData Temp
directory, pass ``Path(f"~/AppData/Local/Temp/{Path(__file__).stem}")``.
Args:
log_folder: Directory for log files. Relative paths are resolved from
the current working directory.
console_level: Minimum severity level written to the console.
file_level: Minimum severity level written to the log file.
enable_file_logging: Whether to create a log file. Console logging
remains enabled when this is ``False``.
max_log_files: Maximum number of this script's log files to keep, or
``None`` to disable count-based pruning.
max_log_age: Remove this script's logs older than this duration, or
``None`` to disable age-based pruning.
date_format: Date format used in file log timestamps.
console_message_format: Logging format string for console messages.
file_message_format: Logging format string for file messages.
Returns:
The created log file path, or ``None`` when file logging is disabled.
Raises:
ValueError: If ``max_log_files`` is less than 1 or ``max_log_age`` is
negative.
"""
if max_log_files is not None and max_log_files < 1:
raise ValueError("max_log_files must be at least 1 or None.")
if max_log_age is not None and max_log_age < timedelta(0):
raise ValueError("max_log_age must be non-negative or None.")
root_logger = logging.getLogger()
for handler in root_logger.handlers[:]:
handler.close()
root_logger.removeHandler(handler)
root_logger.setLevel(logging.DEBUG)
# Console Handler (always active)
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(console_level)
console_handler.setFormatter(logging.Formatter(console_message_format))
root_logger.addHandler(console_handler)
log_path: Path | None = None
# Optional File Handler
if enable_file_logging:
script_stem = Path(__file__).stem
timestamp = datetime.now().strftime("%Y%m%dT%H%M%S")
log_dir = Path(log_folder).expanduser().resolve()
log_dir.mkdir(parents=True, exist_ok=True)
log_path = log_dir / f"{timestamp}_{script_stem}.log"
file_handler = logging.FileHandler(log_path, mode="w", encoding="utf-8")
file_handler.setLevel(file_level)
file_handler.setFormatter(logging.Formatter(file_message_format, datefmt=date_format))
root_logger.addHandler(file_handler)
# Prune old logs specific to this script
if max_log_files is not None or max_log_age is not None:
script_logs = sorted(p for p in log_dir.glob("*.log") if p.stem.partition("_")[2] == script_stem)
if max_log_age is not None:
expiration_time = datetime.now().timestamp() - max_log_age.total_seconds()
for old_log in script_logs[:]:
if old_log == log_path:
continue
try:
if old_log.stat().st_mtime < expiration_time:
old_log.unlink()
script_logs.remove(old_log)
except OSError:
root_logger.warning("Failed to remove old log file: %s", old_log)
if max_log_files is not None:
while len(script_logs) > max_log_files:
oldest = script_logs.pop(0)
try:
oldest.unlink()
except OSError:
root_logger.warning("Failed to remove old log file: %s", oldest)
return log_path
if __name__ == "__main__":
exit_code = 0
try:
setup_logging(max_log_files=10)
# logging.getLogger("urllib3").setLevel(logging.WARNING)
# logging.getLogger("requests").setLevel(logging.WARNING)
main()
except KeyboardInterrupt:
print()
logger.warning("Operation interrupted by user.")
exit_code = 130
except Exception as e:
print()
logger.exception("A fatal error has occurred: %s", e)
exit_code = 1
# input("Press Enter to exit...")
sys.exit(exit_code)