blob: 74772beee6f5b258d9ce003fa71e9f76b948f776 (
plain)
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
|
from __future__ import annotations
import contextlib
import logging
from collections.abc import Generator
from pre_commit import color
from pre_commit import output
logger = logging.getLogger('pre_commit')
LOG_LEVEL_COLORS = {
'DEBUG': '',
'INFO': '',
'WARNING': color.YELLOW,
'ERROR': color.RED,
}
class LoggingHandler(logging.Handler):
def __init__(self, use_color: bool) -> None:
super().__init__()
self.use_color = use_color
def emit(self, record: logging.LogRecord) -> None:
level_msg = color.format_color(
f'[{record.levelname}]',
LOG_LEVEL_COLORS[record.levelname],
self.use_color,
)
output.write_line(f'{level_msg} {record.getMessage()}')
@contextlib.contextmanager
def logging_handler(use_color: bool) -> Generator[None]:
handler = LoggingHandler(use_color)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
try:
yield
finally:
logger.removeHandler(handler)
|