|
1 | 1 | from datetime import datetime |
| 2 | +import logging |
| 3 | +from os import path, makedirs |
| 4 | +from typing import Any |
| 5 | +from electionguard.logs import ( |
| 6 | + get_file_handler, |
| 7 | + log_critical, |
| 8 | + log_debug, |
| 9 | + log_error, |
| 10 | + log_info, |
| 11 | + log_warning, |
| 12 | + LOG, |
| 13 | +) |
| 14 | +from electionguard_gui.services.directory_service import get_data_dir |
2 | 15 | from electionguard_gui.services.service_base import ServiceBase |
3 | 16 |
|
4 | 17 |
|
5 | 18 | class EelLogService(ServiceBase): |
6 | 19 | """A facade for logging. Currently this simply writes to the console without using log levels, but |
7 | 20 | this may eventually be used to log to a file or database.""" |
8 | 21 |
|
9 | | - # pylint: disable=no-self-use |
10 | | - def _log(self, level: str, message: str) -> None: |
11 | | - print(f"{datetime.now()} {level} {message}") |
| 22 | + def __init__(self) -> None: |
| 23 | + LOG.set_stream_log_level(logging.DEBUG) |
| 24 | + file_dir = path.join(get_data_dir(), "logs") |
| 25 | + makedirs(file_dir, exist_ok=True) |
| 26 | + now = datetime.now().strftime("%Y-%m-%d-%H-%M-%S-%f") |
| 27 | + file_name = path.join(file_dir, f"electionguard-{now}.log") |
| 28 | + LOG.add_handler(get_file_handler(logging.DEBUG, file_name)) |
12 | 29 |
|
13 | | - def trace(self, message: str) -> None: |
| 30 | + def trace(self, message: str, *args: Any, **kwargs: Any) -> None: |
14 | 31 | pass |
15 | 32 |
|
16 | | - def debug(self, message: str) -> None: |
17 | | - self._log("DEBUG", message) |
| 33 | + # pylint: disable=no-self-use |
| 34 | + def debug(self, message: str, *args: Any, **kwargs: Any) -> None: |
| 35 | + log_debug(message, *args, **kwargs) |
18 | 36 |
|
19 | | - def info(self, message: str) -> None: |
20 | | - self._log("INFO ", message) |
| 37 | + # pylint: disable=no-self-use |
| 38 | + def info(self, message: str, *args: Any, **kwargs: Any) -> None: |
| 39 | + log_info(message, *args, **kwargs) |
21 | 40 |
|
22 | | - def warn(self, message: str) -> None: |
23 | | - self._log("WARN ", message) |
| 41 | + # pylint: disable=no-self-use |
| 42 | + def warn(self, message: str, *args: Any, **kwargs: Any) -> None: |
| 43 | + log_warning(message, *args, **kwargs) |
24 | 44 |
|
25 | | - def error(self, e: Exception) -> None: |
26 | | - self._log("ERROR", str(e)) |
| 45 | + # pylint: disable=no-self-use |
| 46 | + def error(self, message: str, exception: Exception) -> None: |
| 47 | + log_error( |
| 48 | + f"{message} '{exception}'", |
| 49 | + exc_info=1, |
| 50 | + extra={"exception": exception}, |
| 51 | + ) |
27 | 52 |
|
28 | | - def fatal(self, message: str) -> None: |
29 | | - self._log("FATAL", message) |
| 53 | + # pylint: disable=no-self-use |
| 54 | + def fatal(self, message: str, exception: Exception) -> None: |
| 55 | + log_critical( |
| 56 | + f"{message} '{str(exception)}'", |
| 57 | + exc_info=1, |
| 58 | + extra={"exception": exception}, |
| 59 | + ) |
0 commit comments