-
Notifications
You must be signed in to change notification settings - Fork 201
/
Copy pathtoolong_formatter.py
326 lines (258 loc) · 11.8 KB
/
toolong_formatter.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
from __future__ import annotations
import re
from datetime import datetime
from typing import Optional
from rich.text import Text
from toolong.format_parser import FormatParser
from toolong.highlighter import LogHighlighter
from typing_extensions import TypeAlias
ParseResult: TypeAlias = "tuple[Optional[datetime], str, Text]"
MOVE_LOG_LEVEL_COL = True
LOG_LEVELS = {
"DEBUG": ["dim white on black", "dim"],
"INFO": ["bold black on green", ""],
"WARN": ["bold black on yellow", "yellow"],
"ERROR": ["bold black on red", "red"],
}
class LogFormat:
def parse(self, line: str) -> ParseResult | None:
raise NotImplementedError()
class NextflowLogFormat(LogFormat):
"""
Formatter for regular Nextflow log files.
Examples:
Mar-24 00:11:47.302 [main] DEBUG nextflow.util.CustomThreadPool - Creating default thread pool > poolSize: 11; maxThreads: 1000
Mar-24 00:12:04.942 [Task monitor] INFO nextflow.Session - Execution cancelled -- Finishing pending tasks before exit
"""
REGEX = re.compile(
r"(?P<date>\w+-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}) (?P<thread>\[.*\]?) (?P<log_level>\w+)\s+(?P<logger_name>[\w\.]+) - (?P<message>.*?)$"
)
highlighter = LogHighlighter()
def parse(self, line: str) -> ParseResult | None:
match = self.REGEX.fullmatch(line)
if match is None:
return None
text = Text.from_ansi(line)
groups = match.groupdict()
if date := groups.get("date", None):
timestamp = datetime.strptime(groups["date"], "%b-%d %H:%M:%S.%f")
text.highlight_words([date], "not bold magenta")
if thread := groups.get("thread", None):
text.highlight_words([thread], "blue")
if log_level := groups.get("log_level", None):
text.highlight_words([f" {log_level} "], LOG_LEVELS[log_level][0])
if logger_name := groups.get("logger_name", None):
text.highlight_words([logger_name], "cyan")
if process_name := groups.get("process_name", None):
text.highlight_words([process_name], "bold cyan")
if message := groups.get("message", None):
text.highlight_words([message], "dim" if log_level == "DEBUG" else "")
return timestamp, line, text
class NextflowLogAbortedProcessNames(LogFormat):
"""
Formatter for process names when a pipeline is aborted.
Example:
The following lines:
[process] NFCORE_RNASEQ:RNASEQ:ALIGN_STAR:STAR_ALIGN
[process] NFCORE_RNASEQ:RNASEQ:ALIGN_STAR:BAM_SORT_STATS_SAMTOOLS:SAMTOOLS_SORT
In blocks that look like this:
Mar-12 23:56:10.538 [SIGINT handler] DEBUG nextflow.Session - Session aborted -- Cause: SIGINT
Mar-12 23:56:10.572 [SIGINT handler] DEBUG nextflow.Session - The following nodes are still active:
[process] NFCORE_RNASEQ:RNASEQ:ALIGN_STAR:STAR_ALIGN
status=ACTIVE
port 0: (queue) OPEN ; channel: -
port 1: (value) bound ; channel: -
port 2: (value) bound ; channel: -
port 3: (value) bound ; channel: star_ignore_sjdbgtf
port 4: (value) bound ; channel: seq_platform
port 5: (value) bound ; channel: seq_center
port 6: (cntrl) - ; channel: $
[process] NFCORE_RNASEQ:RNASEQ:ALIGN_STAR:BAM_SORT_STATS_SAMTOOLS:SAMTOOLS_SORT
status=ACTIVE
port 0: (queue) OPEN ; channel: -
port 1: (cntrl) - ; channel: $
"""
REGEX = re.compile(r"^(?P<marker>\[process\]) (?P<process>.*?)(?P<process_name>[^:]+?)?$")
highlighter = LogHighlighter()
def parse(self, line: str) -> ParseResult | None:
match = self.REGEX.fullmatch(line)
if match is None:
return None
text = Text.from_ansi(line)
text.stylize_before("dim")
groups = match.groupdict()
if process := groups.get("process", None):
text.highlight_words([process], "blue not dim")
if process_name := groups.get("process_name", None):
text.highlight_words([process_name], "bold cyan not dim")
return None, line, text
class NextflowLogAbortedProcessPorts(LogFormat):
"""
Formatter for process names when a pipeline is aborted.
Example:
The following lines:
port 0: (queue) OPEN ; channel: -
port 1: (value) bound ; channel: -
port 2: (value) bound ; channel: -
port 3: (value) bound ; channel: star_ignore_sjdbgtf
In blocks that look like this:
Mar-12 23:56:10.538 [SIGINT handler] DEBUG nextflow.Session - Session aborted -- Cause: SIGINT
Mar-12 23:56:10.572 [SIGINT handler] DEBUG nextflow.Session - The following nodes are still active:
[process] NFCORE_RNASEQ:RNASEQ:ALIGN_STAR:STAR_ALIGN
status=ACTIVE
port 0: (queue) OPEN ; channel: -
port 1: (value) bound ; channel: -
port 2: (value) bound ; channel: -
port 3: (value) bound ; channel: star_ignore_sjdbgtf
port 4: (value) bound ; channel: seq_platform
port 5: (value) bound ; channel: seq_center
port 6: (cntrl) - ; channel: $
[process] NFCORE_RNASEQ:RNASEQ:ALIGN_STAR:BAM_SORT_STATS_SAMTOOLS:SAMTOOLS_SORT
status=ACTIVE
port 0: (queue) OPEN ; channel: -
port 1: (cntrl) - ; channel: $
"""
REGEX = re.compile(
r" (?P<port>port \d+): (?P<channel_type>\((value|queue|cntrl)\)) (?P<channel_state>\S+)\s+; channel: (?P<channel_name>.*?)$"
)
CHANNEL_TYPES = {
"(value)": "green",
"(cntrl)": "yellow",
"(queue)": "magenta",
}
highlighter = LogHighlighter()
def parse(self, line: str) -> ParseResult | None:
match = self.REGEX.fullmatch(line)
if match is None:
return None
text = Text.from_ansi(line)
groups = match.groupdict()
if port := groups.get("port", None):
text.highlight_words([port], "blue")
if channel_type := groups.get("channel_type", None):
text.highlight_words([channel_type], self.CHANNEL_TYPES[channel_type])
if channel_state := groups.get("channel_state", None):
text.highlight_words([channel_state], "cyan" if channel_state == "OPEN" else "yellow")
text.highlight_words(["; channel:"], "dim")
if channel_name := groups.get("channel_name", None):
text.highlight_words([channel_name], "cyan")
return None, line, text
class NextflowLogAbortedProcessStatus(LogFormat):
"""
Formatter for process names when a pipeline is aborted.
Example:
The following lines:
status=ACTIVE
In blocks that look like this:
Mar-12 23:56:10.538 [SIGINT handler] DEBUG nextflow.Session - Session aborted -- Cause: SIGINT
Mar-12 23:56:10.572 [SIGINT handler] DEBUG nextflow.Session - The following nodes are still active:
[process] NFCORE_RNASEQ:RNASEQ:ALIGN_STAR:STAR_ALIGN
status=ACTIVE
port 0: (queue) OPEN ; channel: -
port 1: (value) bound ; channel: -
port 2: (value) bound ; channel: -
port 3: (value) bound ; channel: star_ignore_sjdbgtf
port 4: (value) bound ; channel: seq_platform
port 5: (value) bound ; channel: seq_center
port 6: (cntrl) - ; channel: $
[process] NFCORE_RNASEQ:RNASEQ:ALIGN_STAR:BAM_SORT_STATS_SAMTOOLS:SAMTOOLS_SORT
status=ACTIVE
port 0: (queue) OPEN ; channel: -
port 1: (cntrl) - ; channel: $
"""
REGEX = re.compile(r"^ status=(?P<status>.*?)?$")
highlighter = LogHighlighter()
def parse(self, line: str) -> ParseResult | None:
match = self.REGEX.fullmatch(line)
if match is None:
return None
text = Text.from_ansi(line)
text.stylize_before("dim")
groups = match.groupdict()
text.highlight_words(["status="], "dim")
if status := groups.get("status", None):
text.highlight_words([status], "cyan not dim")
return None, line, text
class NextflowLogParsedScripts(LogFormat):
"""
Formatter for parsed scriptp names.
For example:
Mar-24 00:12:03.547 [main] DEBUG nextflow.script.ScriptRunner - Parsed script files:
Script_e2630658c898fe40: /Users/ewels/GitHub/nf-core/rnaseq/./workflows/rnaseq/../../modules/local/deseq2_qc/main.nf
Script_56c7c9e8363ee20a: /Users/ewels/GitHub/nf-core/rnaseq/./workflows/rnaseq/../../subworkflows/local/quantify_pseudo_alignment/../../../modules/nf-core/custom/tx2gene/main.nf
"""
REGEX = re.compile(r"^ (?P<script_id>Script_\w+:) (?P<script_path>.*?)$")
highlighter = LogHighlighter()
def parse(self, line: str) -> ParseResult | None:
match = self.REGEX.fullmatch(line)
if match is None:
return None
text = Text.from_ansi(line)
groups = match.groupdict()
if script_id := groups.get("script_id", None):
text.highlight_words([script_id], "blue")
if script_path := groups.get("script_path", None):
text.highlight_words([script_path], "magenta")
return None, line, text
def nextflow_format_parser(logfile_obj):
is_nextflow = logfile_obj.name.startswith(".nextflow.log")
class NextflowFormatParser(FormatParser):
"""Parses a log line."""
def __init__(self) -> None:
super().__init__()
if is_nextflow:
self._formats = [
NextflowLogFormat(),
NextflowLogAbortedProcessNames(),
NextflowLogAbortedProcessPorts(),
NextflowLogAbortedProcessStatus(),
NextflowLogParsedScripts(),
]
self._log_status = ""
def parse(self, line: str) -> ParseResult:
"""Use the toolong parser with custom formatters."""
# Return if not a netflow log file
if not is_nextflow:
return super().parse(line)
# Copied from toolong source, but without the default log parser
if len(line) > 10_000:
line = line[:10_000]
parse_result = None
if line.strip():
for index, format in enumerate(self._formats):
parse_result = format.parse(line)
if parse_result is not None:
if index:
self._formats = [*self._formats[index:], *self._formats[:index]]
timestamp, line, text = parse_result
break
if parse_result is None:
timestamp = None
line = line
text = Text(line)
# Custom formatting with log levels
for logtype in LOG_LEVELS.keys():
if logtype in line:
# Set log status for next lines, if multi-line
self._log_status = logtype
# Set the base stlying for this line
text.stylize_before(LOG_LEVELS[logtype][1])
# Move the "INFO" log level to the start of the line
if MOVE_LOG_LEVEL_COL:
line = "{} {}".format(
logtype,
line.replace(f" {logtype} ", ""),
)
logtype_str = f"[{LOG_LEVELS[logtype][0]}] {logtype: <5} [/] "
text = Text.from_markup(
logtype_str + text.markup.replace(f" {logtype} ", "[reset] [/]"),
)
# Return - on to next line
return timestamp, line, text
# Multi-line log message - add colour character at start of line
for logtype in LOG_LEVELS.keys():
if self._log_status == logtype:
text = Text.from_markup(f"[{LOG_LEVELS[logtype][0]}] [/] " + text.markup)
text.stylize_before(LOG_LEVELS[logtype][1])
return timestamp, line, text
return NextflowFormatParser()