-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.py
58 lines (47 loc) · 1.66 KB
/
logger.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
# coding: utf-8
import io
import sys
from contextlib import contextmanager, redirect_stdout
from dataclasses import dataclass
from typing import List, Literal, Optional
LOG_LEVEL = Literal['debug', 'notice', 'warning', 'error']
@dataclass
class Message:
level: Literal['', LOG_LEVEL]
text: str
filename: Optional[str] = None
line: Optional[int] = None
end_line: Optional[int] = None
title: Optional[str] = None
def __str__(self) -> str:
if False:
return f'{self.level.upper()}: {self.text}' if self.level else self.text
# https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-a-notice-message
params: List[str] = []
if self.filename:
params.append(f'file={self.filename}')
if self.line:
params.append(f'line={self.line}')
if self.end_line:
params.append(f'endLine={self.end_line}')
if self.title:
params.append(f'title={self.title}')
params_str = f"' {','.join(params)}" if params else ''
return f'::{self.level or "notice"}{params_str}::{self.text}'
@contextmanager
def report_errors(ci: bool):
stdout = sys.stdout
with redirect_stdout(io.StringIO()) as buffer:
yield
if not (output := buffer.getvalue()):
return
if not ci:
print(output, file=stdout)
return
for line in output.splitlines():
level = 'notice'
if 'WARNING:' in line:
level = 'warning'
if 'ERROR' in line:
level = 'error'
print(Message(level, line), file=stdout)