Debian Codegraph @

DisplayCAL/log.py

raw
1 """Logging utilities for file-based, rotating, and safe Unicode logging."""
2
3 from __future__ import annotations
4
5 import atexit
6 import contextlib
7 import logging
8 import logging.handlers
9 import os
10 import re
11 import sys
12 import warnings
13 from codecs import EncodedFile
14 from hashlib import md5
15 from io import BytesIO
16 from time import localtime, strftime, time
17 from typing import TYPE_CHECKING, Callable, TextIO
18
19 from DisplayCAL.meta import NAME as APPNAME
20 from DisplayCAL.meta import script2pywname
21 from DisplayCAL.multiprocess import mp
22 from DisplayCAL.options import DEBUG
23 from DisplayCAL.safe_print import SafePrinter
24 from DisplayCAL.safe_print import safe_print as _safe_print
25 from DisplayCAL.util_os import safe_glob
26
27 if TYPE_CHECKING:
28 import wx # noqa: TC004
29
30 logging.raiseExceptions = 0
31 logging._warnings_showwarning = warnings.showwarning
32
33
34 LOGLEVEL = logging.DEBUG if DEBUG else logging.INFO
35
36
37 LOGGER = None
38 _LOGDIR = None
39
40
41 def showwarning(
42 message: Warning,
43 category: Warning,
44 filename: str,
45 lineno: int,
46 file: None | TextIO = None,
47 line: str = "",
48 ) -> None:
49 # Adapted from _showwarning in Python2.7/lib/logging/__init__.py
50 """Implementation of `showwarnings` which redirects to logging.
51
52 It will first check to see if the file parameter is None. If a file is
53 specified, it will delegate to the original warnings implementation of
54 showwarning. Otherwise, it will call warnings.formatwarning and will log
55 the resulting string to a warnings logger named "py.warnings" with level
56 logging.WARNING.
57
58 Unlike the default implementation, the line is omitted from the warning,
59 and the warning does not end with a newline.
60
61 Args:
62 message (Warning): The warning message.
63 category (Warning): The warning category.
64 filename (str): The filename where the warning occurred.
65 lineno (int): The line number where the warning occurred.
66 file (None | TextIO, optional): The file to write the warning to.
67 line (str, optional): The line of code that caused the warning.
68 """
69 if file is not None:
70 if logging._warnings_showwarning is not None:
71 logging._warnings_showwarning(
72 message, category, filename, lineno, file, line
73 )
74 else:
75 s = warnings.formatwarning(message, category, filename, lineno, line)
76 logger = logging.getLogger("py.warnings")
77 if not logger.handlers:
78 if hasattr(sys.stderr, "isatty") and sys.stderr.isatty():
79 handler = logging.StreamHandler() # Logs to stderr by default
80 else:
81 handler = logging.NullHandler()
82 logger.addHandler(handler)
83 LOG(s.strip(), fn=logger.warning)
84
85
86 warnings.showwarning = showwarning
87
88 LOGBUFFER = EncodedFile(BytesIO(), "UTF-8", errors="replace")
89
90
91 def wx_log(logwindow: wx.Window, msg: str) -> None:
92 """Log a message to the wxPython log window.
93
94 Args:
95 logwindow (wx.Window): The wxPython log window to log to.
96 msg (str): The message to log.
97 """
98 if logwindow.IsShownOnScreen() and LOGBUFFER.tell():
99 # Check if log buffer has been emptied or not.
100 # If it has, our log message is already included.
101 logwindow.Log(msg)
102
103
104 class DummyLogger:
105 """Dummy logger class.
106
107 This is used when logging is disabled or not available.
108 """
109
110 def critical(self, msg: str, *args, **kwargs) -> None:
111 """Log a critical message.
112
113 Args:
114 msg (str): The message to log.
115 *args: Additional arguments to format the message.
116 **kwargs: Additional keyword arguments for logging.
117 """
118
119 def debug(self, msg: str, *args, **kwargs) -> None:
120 """Log a debug message.
121
122 Args:
123 msg (str): The message to log.
124 *args: Additional arguments to format the message.
125 **kwargs: Additional keyword arguments for logging.
126 """
127
128 def error(self, msg: str, *args, **kwargs) -> None:
129 """Log an error message.
130
131 Args:
132 msg (str): The message to log.
133 *args: Additional arguments to format the message.
134 **kwargs: Additional keyword arguments for logging.
135 """
136
137 def exception(self, msg: str, *args, **kwargs) -> None:
138 """Log an exception message.
139
140 Args:
141 msg (str): The message to log.
142 *args: Additional arguments to format the message.
143 **kwargs: Additional keyword arguments for logging.
144 """
145
146 def info(self, msg: str, *args, **kwargs) -> None:
147 """Log an info message.
148
149 Args:
150 msg (str): The message to log.
151 *args: Additional arguments to format the message.
152 **kwargs: Additional keyword arguments for logging.
153 """
154
155 def log(self, level: int, msg: str, *args, **kwargs) -> None:
156 """Log a message with the specified level.
157
158 Args:
159 level (int): The logging level (e.g., logging.INFO).
160 msg (str): The message to log.
161 *args: Additional arguments to format the message.
162 **kwargs: Additional keyword arguments for logging.
163 """
164
165 def warning(self, msg: str, *args, **kwargs) -> None:
166 """Log a warning message.
167
168 Args:
169 msg (str): The message to log.
170 *args: Additional arguments to format the message.
171 **kwargs: Additional keyword arguments for logging.
172 """
173
174
175 class Log:
176 """Log class.
177
178 This is a wrapper around the logging module.
179 """
180
181 def __call__(self, msg: str, fn: None | Callable = None) -> None:
182 """Log a message.
183
184 Optionally use function 'fn' instead of logging.info.
185
186 Args:
187 msg (str): The message to log.
188 fn (None | Callable, optional): Function to use for logging. If None,
189 it will use logging.info if available, otherwise it will
190 default to a dummy logger.
191 """
192 global LOGGER
193 if isinstance(msg, bytes):
194 msg = msg.decode("utf-8", "replace")
195
196 msg = msg.replace("\r\n", "\n").replace("\r", "")
197 if fn is None and LOGGER and LOGGER.handlers:
198 fn = LOGGER.info
199 if fn:
200 for line in msg.split("\n"):
201 fn(line)
202 # If wxPython itself calls warnings.warn on import, it is not yet fully
203 # imported at the point our showwarning() function calls log().
204 # Check for presence of our wx_fixes module and if it has an attribute
205 # "wx", in which case wxPython has finished importing.
206 wx_fixes = sys.modules.get(f"{APPNAME}.wx_fixes")
207 # wx_fixes = sys.modules.get("wx_fixes")
208 if (
209 wx_fixes
210 and hasattr(wx_fixes, "wx")
211 and mp.current_process().name == "MainProcess"
212 ):
213 wx = wx_fixes.wx
214 if (
215 wx.GetApp() is not None
216 and hasattr(wx.GetApp(), "frame")
217 and hasattr(wx.GetApp().frame, "infoframe")
218 ):
219 wx.CallAfter(wx_log, wx.GetApp().frame.infoframe, msg)
220
221 def flush(self) -> None:
222 """Flush the log."""
223
224 def write(self, msg: str) -> None:
225 """Write a message to the log.
226
227 Args:
228 msg (str): The message to write to the log.
229 """
230 self(msg.rstrip())
231
232
233 LOG = Log()
234
235
236 class LogFile:
237 """Logfile class. Default is to not rotate.
238
239 Args:
240 filename (str): The name of the log file.
241 logdir (str): The directory where the log file will be stored.
242 when (str, optional): When to rotate the log file. Defaults to "never".
243 backup_count (int, optional): Number of backup files to keep. Defaults
244 to 0
245 """
246
247 def __init__(
248 self,
249 filename: str,
250 logdir: str,
251 when: str = "never",
252 backup_count: int = 0,
253 ) -> None:
254 self.filename = filename
255 self._logger = get_file_logger(
256 md5(filename.encode()).hexdigest(), # noqa: S324
257 when=when,
258 backup_count=backup_count,
259 logdir=logdir,
260 filename=filename,
261 )
262
263 def close(self) -> None:
264 """Close the log file."""
265 for handler in reversed(self._logger.handlers):
266 handler.close()
267 self._logger.removeHandler(handler)
268
269 def flush(self) -> None:
270 """Flush the log file."""
271 for handler in self._logger.handlers:
272 handler.flush()
273
274 def write(self, msg: str) -> None:
275 """Write a message to the log file.
276
277 Args:
278 msg (str): The message to write to the log file.
279 """
280 for line in msg.rstrip().replace("\r\n", "\n").replace("\r", "").split("\n"):
281 self._logger.info(line)
282
283
284 class SafeLogger(SafePrinter):
285 """Safely print and log, avoiding Unicode errors.
286
287 Args:
288 log (bool, optional): Whether to log the messages. Defaults to True.
289 print_ (None | bool, optional): Whether to print the messages. If None,
290 it will check if sys.stdout is a TTY.
291 """
292
293 def __init__(self, log: bool = True, print_: None | bool = None) -> None:
294 SafePrinter.__init__(self)
295 self.log = log
296 if print_ is None:
297 print_ = (
298 sys.stdout and hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
299 )
300 self.print_ = print_
301
302 def write(self, *args, **kwargs) -> None:
303 """Write the given arguments to the stream, formatted and encoded."""
304 if kwargs.get("print_", self.print_):
305 _safe_print(*args, **kwargs)
306 if kwargs.get("log", self.log):
307 kwargs.update(fn=LOG, encoding=None)
308 _safe_print(*args, **kwargs)
309
310
311 safe_log = SafeLogger(print_=False)
312 safe_print = SafeLogger()
313
314
315 def get_file_logger(
316 name: str,
317 level: int = LOGLEVEL,
318 when: str = "midnight",
319 backup_count: int = 5,
320 logdir: None | str = None,
321 filename: None | str = None,
322 confighome: None | str = None,
323 ) -> logging.Logger:
324 """Return logger object.
325
326 A TimedRotatingFileHandler or FileHandler (if when == "never") will be used.
327
328 Args:
329 name (str): Name of the logger.
330 level (int, optional): Logging level. Defaults to LOGLEVEL.
331 when (str, optional): When to rotate the log file. Defaults to
332 "midnight".
333 backup_count (int, optional): Number of backup files to keep. Defaults
334 to 5
335 logdir (str, optional): Directory where log files will be stored.
336 filename (None | str, optional): Name of the log file. If None, it will
337 use the name parameter.
338 confighome (None | str, optional): Configuration home directory, used
339 for unique log file names. If None, it will not use a unique name.
340
341 Returns:
342 logging.Logger: The logger object.
343 """
344 global _LOGDIR
345 global LOGGER
346 if logdir is None:
347 logdir = _LOGDIR
348 LOGGER = logging.getLogger(name)
349 if not filename:
350 filename = name
351 mode = "a"
352 if confighome:
353 when, filename, mode = update_filename_for_confighome(
354 when,
355 logdir,
356 filename,
357 confighome,
358 mode,
359 )
360 logfile = os.path.join(logdir, filename + ".log")
361 for handler in LOGGER.handlers:
362 if isinstance(
363 handler, logging.FileHandler
364 ) and handler.baseFilename == os.path.abspath(logfile):
365 return LOGGER
366 LOGGER.propagate = 0
367 LOGGER.setLevel(level)
368 if not os.path.exists(logdir):
369 try:
370 os.makedirs(logdir)
371 except Exception as exception:
372 print(
373 f"Warning - log directory '{logdir}' could not be created: {exception}"
374 )
375 elif when != "never" and os.path.exists(logfile):
376 rotate_log_files(backup_count, logdir, logfile)
377 if os.path.exists(logdir):
378 try:
379 if when != "never":
380 filehandler = logging.handlers.TimedRotatingFileHandler(
381 logfile, when=when, backupCount=backup_count
382 )
383 else:
384 filehandler = logging.FileHandler(logfile, mode)
385 fileformatter = logging.Formatter("%(asctime)s %(message)s")
386 filehandler.setFormatter(fileformatter)
387 LOGGER.addHandler(filehandler)
388 except Exception as exception:
389 print(f"Warning - logging to file '{logfile}' not possible: {exception}")
390 return LOGGER
391
392
393 def update_filename_for_confighome(
394 when: str,
395 logdir: str,
396 filename: str,
397 confighome: str,
398 mode: str,
399 ) -> None:
400 """Update the filename for the log file based on the configuration home.
401
402 Args:
403 when (str): When to rotate the log file.
404 logdir (str): Directory where log files will be stored.
405 filename (str): Name of the log file.
406 confighome (str): Configuration home directory, used for unique log
407 file names.
408 mode (str): Mode for opening the log file.
409
410 Returns:
411 tuple[str, str, str]: A tuple containing the updated 'when',
412 'filename', and 'mode'.
413 """
414 # Use different logfile name (append number) for each additional instance
415 is_main_process = mp.current_process().name == "MainProcess"
416 if os.path.basename(confighome).lower() == "dispcalgui":
417 lockbasename = filename.replace(APPNAME, "dispcalGUI")
418 else:
419 lockbasename = filename
420 lockfilepath = os.path.join(confighome, f"{lockbasename}.lock")
421 if os.path.isfile(lockfilepath):
422 filename = update_filename_with_lockfile(logdir, filename, lockfilepath)
423 if is_main_process:
424 for lockfilepath in safe_glob(
425 os.path.join(confighome, f"{lockbasename}.mp-worker-*.lock")
426 ):
427 with contextlib.suppress(Exception):
428 os.remove(lockfilepath)
429 else:
430 # Running as child from multiprocessing under Windows
431 lockbasename = f"{lockbasename}.mp-worker-"
432 process_num = 1
433 while os.path.isfile(
434 os.path.join(confighome, f"{lockbasename}{process_num}.lock")
435 ):
436 process_num += 1
437 lockfilepath = os.path.join(confighome, f"{lockbasename}{process_num}.lock")
438 try:
439 with open(lockfilepath, "w"):
440 pass
441 except Exception:
442 pass
443 else:
444 atexit.register(os.remove, lockfilepath)
445 when = "never"
446 filename = f"{filename}.mp-worker-{process_num}"
447 mode = "w"
448
449 return when, filename, mode
450
451
452 def update_filename_with_lockfile(
453 logdir: str,
454 filename: str,
455 lockfilepath: str,
456 ) -> str:
457 """Update the filename based on the lock file.
458
459 Args:
460 logdir (str): Directory where log files will be stored.
461 filename (str): Name of the log file.
462 lockfilepath (str): Path to the lock file.
463 """
464 is_main_process = mp.current_process().name == "MainProcess"
465 try:
466 with open(lockfilepath) as lockfile:
467 instances = len(lockfile.read().splitlines())
468 except Exception:
469 return filename
470
471 if not is_main_process:
472 # Running as child from multiprocessing under Windows
473 instances -= 1
474 if not instances:
475 return filename
476
477 filenames = [filename]
478 filename = f"{filename}.{instances}"
479 filenames.append(filename)
480 if not filenames[0].endswith("-apply-profiles"):
481 return filename
482 # Running the profile loader always sends a close
483 # request to an already running instance, so there
484 # will be at most two logfiles, and we want to use
485 # the one not currently in use.
486 mtimes = {}
487 for filename in filenames:
488 logfile = os.path.join(logdir, f"{filename}.log")
489 if not os.path.isfile(logfile):
490 mtimes[0] = filename
491 continue
492 try:
493 logstat = os.stat(logfile)
494 except Exception as exception:
495 print(f"Warning - os.stat('{logfile}') failed: {exception}")
496 else:
497 mtimes[logstat.st_mtime] = filename
498 if mtimes:
499 filename = mtimes[sorted(mtimes.keys())[0]]
500 return filename
501
502
503 def rotate_log_files(backup_count: int, logdir: str, logfile: str) -> None:
504 """Rotate log files if needed.
505
506 Args:
507 backup_count (int): Number of backup files to keep.
508 logdir (str): Directory where log files are stored.
509 logfile (str): Path to the current log file.
510 """
511 try:
512 logstat = os.stat(logfile)
513 except Exception as exception:
514 print(f"Warning - os.stat('{logfile}') failed: {exception}")
515 return
516
517 # rollover needed?
518 now = localtime()
519 mtime = get_log_mtime(logstat, now)
520 if now[:3] <= mtime[:3]:
521 return
522
523 # do rollover
524 logbackup = logfile + strftime(".%Y-%m-%d", mtime)
525 validate_and_rename_logfile(logfile, logbackup)
526 ext_match = re.compile(r"^\d{4}-\d{2}-\d{2}$")
527 base_name = os.path.basename(logfile)
528 try:
529 file_names = os.listdir(logdir)
530 except Exception as exception:
531 print(
532 f"Warning - log directory '{logdir}' "
533 f"listing failed during rollover: {exception}"
534 )
535 return
536
537 result = []
538 prefix = base_name + "."
539 plen = len(prefix)
540 for file_name in file_names:
541 if file_name[:plen] != prefix:
542 continue
543 suffix = file_name[plen:]
544 if ext_match.match(suffix):
545 result.append(os.path.join(logdir, file_name))
546 result.sort()
547 if len(result) <= backup_count:
548 return
549 for logbackup in result[: len(result) - backup_count]:
550 try:
551 os.remove(logbackup)
552 except Exception as exception:
553 print(
554 f"Warning - logfile backup '{logbackup}' "
555 f"could not be removed during rollover: {exception}"
556 )
557
558
559 def get_log_mtime(
560 logstat: os.stat_result,
561 now: tuple[int, int, int, int, int, int],
562 ) -> tuple[int, int, int, int, int, int]:
563 """Get the modification time of the log file.
564
565 Args:
566 logstat (os.stat_result): The stat result of the log file.
567 now (tuple[int, int, int, int, int, int]): The current time as a tuple
568 of (year, month, day, hour, minute, second).
569
570 Returns:
571 tuple[int, int, int, int, int, int]: The modification time as a
572 tuple of (year, month, day, hour, minute, second).
573 """
574 t = logstat.st_mtime
575 try:
576 mtime = localtime(t)
577 except ValueError:
578 # This can happen on Windows because localtime() is buggy on
579 # that platform. See:
580 # http://stackoverflow.com/questions/4434629/zipfile-module-in-python-runtime-problems
581 # http://bugs.python.org/issue1760357
582 # To overcome this problem, we ignore the real modification
583 # date and force a rollover
584 t = time() - 60 * 60 * 24
585 mtime = localtime(t)
586 # Deal with DST
587
588 dst_now = now[-1]
589 dst_then = mtime[-1]
590 if dst_now != dst_then:
591 addend = 3600 if dst_now else -3600
592 mtime = localtime(t + addend)
593
594 return mtime
595
596
597 def validate_and_rename_logfile(logfile: str, logbackup: str) -> None:
598 """Validate and rename the log file to a backup.
599
600 Args:
601 logfile (str): Path to the current log file.
602 logbackup (str): Path to the backup log file.
603 """
604 if os.path.exists(logbackup):
605 try:
606 os.remove(logbackup)
607 except Exception as exception:
608 print(
609 f"Warning - logfile backup '{logbackup}' "
610 f"could not be removed during rollover: {exception}"
611 )
612
613 try:
614 os.rename(logfile, logbackup)
615 except Exception as exception:
616 print(
617 f"Warning - logfile '{logfile}' could not be renamed to "
618 f"'{os.path.basename(logbackup)}' during rollover: {exception}"
619 )
620 # Adapted from Python 2.6's
621 # logging.handlers.TimedRotatingFileHandler.getFilesToDelete
622
623
624 def setup_logging(
625 logdir: str,
626 name: str = APPNAME,
627 ext: str = ".py",
628 backup_count: int = 5,
629 confighome: None | str = None,
630 ) -> None:
631 """Setup the logging facility.
632
633 Args:
634 logdir (str): Directory where log files will be stored.
635 name (str, optional): Name of the application or script.
636 ext (str, optional): File extension for the log file.
637 backup_count (int, optional): Number of backup log files to keep.
638 confighome (None | str, optional): Configuration home directory, used
639 for unique log file names.
640 """
641 global _LOGDIR, LOGGER
642 _LOGDIR = logdir
643 name = script2pywname(name)
644 if name.startswith((APPNAME, "dispcalGUI")) or ext in (".app", ".exe", ".pyw"):
645 LOGGER = get_file_logger(
646 None,
647 LOGLEVEL,
648 "midnight",
649 backup_count,
650 filename=name,
651 confighome=confighome,
652 )
653 if name in (APPNAME, "dispcalGUI"):
654 streamhandler = logging.StreamHandler(LOGBUFFER)
655 streamformatter = logging.Formatter("%(asctime)s %(message)s")
656 streamhandler.setFormatter(streamformatter)
657 LOGGER.addHandler(streamhandler)