-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathargparse_logging.py
87 lines (67 loc) · 2.46 KB
/
argparse_logging.py
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
import logging
from argparse import Action, ArgumentParser, Namespace
from typing import Any, Optional, Sequence, Union
from enum import Enum
class LogLevel(Enum):
DEBUG = logging.DEBUG
INFO = logging.INFO
WARNING = logging.WARNING
ERROR = logging.ERROR
CRITICAL = logging.CRITICAL
FATAL = logging.FATAL
def __str__(self):
return self.name
class LoggingAction(Action):
"""Abstraction for the different log parsers."""
def __init__(self: "LoggingAction", *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
logging.basicConfig()
self.configure(self.default)
def __call__(
self: "LoggingAction",
parser: ArgumentParser,
namespace: Namespace,
values: Union[str, Sequence[Any], None],
option_string: Optional[str] = None,
) -> None:
self.configure(values)
setattr(namespace, self.dest, values)
def configure(self: "LoggingAction", level: Any) -> None:
raise NotImplementedError
class LogLevelAction(LoggingAction):
"""Simple argparse action to manage logging level."""
def configure(self: "LogLevelAction", level: int) -> None:
assert isinstance(level, LogLevel)
logging.getLogger().setLevel(level.value)
def add_log_level_argument(
parser: ArgumentParser, option_string: str = "--log-level"
) -> Action:
"""Add argument and action to configure the log level."""
return parser.add_argument(
option_string,
choices=list(LogLevel),
type=lambda x: getattr(LogLevel, x),
default=LogLevel.INFO,
action=LogLevelAction,
help="Logging level.",
)
class LogFormatAction(LoggingAction):
"""Configure the logging format."""
def configure(self: "LogFormatAction", fmt: str) -> None:
formatter = logging.Formatter(fmt)
for handler in logging.getLogger().handlers:
handler.setFormatter(formatter)
def add_log_format_argument(
parser: ArgumentParser, option_string: str = "--log-format"
) -> Action:
"""Add argument and action to configure the log format."""
return parser.add_argument(
option_string,
default="%(asctime)s:%(levelname)s:%(name)s:%(message)s",
action=LogFormatAction,
help="Logging format."
"See https://docs.python.org/3/library/logging.html#logrecord-attributes",
)
def add_logging_arguments(parser):
add_log_format_argument(parser)
add_log_level_argument(parser)