Debian Codegraph @

cylc/flow/loggingutil.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 """Logging utilities.
18
19 This module provides:
20 - A custom rolling file handler for workflow logs with date-time names.
21 - A formatter with ISO date time and indented multi-line messages.
22 Note: The ISO date time bit is redundant in Python 3,
23 because "time.strftime" will handle time zone from "localtime" properly.
24 """
25
26 from contextlib import contextmanager, suppress
27 from glob import glob
28 import logging
29 import os
30 from pathlib import Path
31 import re
32 import sys
33 import textwrap
34 from time import time
35 from typing import List, Optional, Union
36
37 from ansimarkup import parse as cparse, strip as cstrip
38
39 from cylc.flow.cfgspec.glbl_cfg import glbl_cfg
40 from cylc.flow.wallclock import get_time_string_from_unix_time
41
42
43 LOG_FILE_EXTENSION = '.log'
44 START_LOAD_TYPE = 'start'
45 RESTART_LOAD_TYPE = 'restart'
46
47
48 class CylcLogFormatter(logging.Formatter):
49 """Format log record in standard Cylc way.
50
51 Message in '%(asctime)s %(levelname)-2s - %(message)s' format.
52 Indent continuation in multi-line messages.
53 Date time in ISO date time with correct time zone.
54 """
55
56 COLORS = {
57 'CRITICAL': '<red><bold>{0}</bold></red>',
58 'ERROR': '<red>{0}</red>',
59 'WARNING': '<yellow>{0}</yellow>',
60 'DEBUG': '<fg #888888>{0}</fg #888888>'
61 }
62
63 # default hard-coded max width for log entries
64 # NOTE: this should be sufficiently long that log entries read by the
65 # daemonise script (url, pid) are not wrapped
66 MAX_WIDTH = 999
67
68 def __init__(
69 self,
70 timestamp: bool = True,
71 color: bool = False,
72 max_width: Optional[int] = None,
73 dev_info: bool = False
74 ) -> None:
75 self.timestamp = None
76 self.color = None
77 self.max_width = self.MAX_WIDTH
78 self.configure(timestamp, color, max_width)
79 prefix = '%(asctime)s %(levelname)-2s - '
80 if dev_info is True:
81 prefix += '[%(module)s:%(lineno)d] - '
82
83 logging.Formatter.__init__(
84 self,
85 prefix + '%(message)s',
86 '%Y-%m-%dT%H:%M:%S%Z')
87
88 def configure(self, timestamp=None, color=None, max_width=None):
89 """Reconfigure the format settings."""
90 if timestamp is not None:
91 self.timestamp = timestamp
92 if color is not None:
93 self.color = color
94 if max_width is not None:
95 self.max_width = max_width
96
97 def format(self, record): # noqa: A003 (method name not local)
98 """Indent continuation lines in multi-line messages."""
99 text = logging.Formatter.format(self, record)
100 if not self.timestamp:
101 _, text = text.split(' ', 1) # ISO8601 time points have no spaces
102 if self.color and record.levelname in self.COLORS:
103 text = cparse(self.COLORS[record.levelname].format(text))
104 elif not self.color:
105 text = cstrip(text)
106 if self.max_width:
107 return '\n'.join(
108 line
109 for part_num, part in enumerate(text.splitlines())
110 for line in textwrap.wrap(
111 part,
112 width=self.max_width,
113 initial_indent='' if part_num == 0 else ' ',
114 subsequent_indent=' ',
115 )
116 )
117 else:
118 return '\n '.join(text.splitlines())
119
120 def formatTime(self, record, datefmt=None):
121 """Formats the record time as an ISO date time with correct time zone.
122
123 Note: This should become redundant in Python 3, because
124 "time.strftime" will handle time zone from "localtime" properly.
125 """
126 return get_time_string_from_unix_time(record.created)
127
128
129 class RotatingLogFileHandler(logging.FileHandler):
130 """Rotating workflow logs using cumulative log number and (re)start number
131 for names.
132
133 Argument:
134 log_file_path: path to the log file (symlink to latest log file)
135 no_detach: non-detach mode?
136 restart_num: restart number for the run
137 timestamp: Add timestamp to log formatting?
138 """
139
140 FILE_HEADER_FLAG = 'cylc_log_file_header'
141 ROLLOVER_NUM = 'cylc_log_num'
142
143 header_extra = {FILE_HEADER_FLAG: True}
144 """Use to indicate the log msg is a header that should be logged on
145 every rollover"""
146
147 def __init__(
148 self,
149 log_file_path: Union[Path, str],
150 no_detach: bool = False,
151 restart_num: int = 0,
152 timestamp: bool = True,
153 ):
154 logging.FileHandler.__init__(self, log_file_path)
155 self.no_detach = no_detach
156 self.formatter = CylcLogFormatter(timestamp=timestamp)
157 # Header records get appended to when calling
158 # `LOG.info(extra=RotatingLogFileHandler.[rollover_]header_extra)`:
159 self.header_records: List[logging.LogRecord] = []
160 self.restart_num = restart_num
161 self.log_num: Optional[int] = None # null value until log file created
162 # Get & cache properties from global config (note: we should not access
163 # the global config object when emitting log messages as as doing so
164 # can have the side effect of expanding the global config):
165 self.max_bytes: int = max(
166 glbl_cfg().get(['scheduler', 'logging', 'maximum size in bytes']),
167 1024 # Max size must be >= 1KB
168 )
169 self.arch_len: Optional[int] = glbl_cfg().get([
170 'scheduler', 'logging', 'rolling archive length'
171 ])
172
173 def emit(self, record):
174 """Emit a record, rollover log if necessary."""
175 try:
176 if self.should_rollover(record):
177 self.do_rollover()
178 if record.__dict__.get(self.FILE_HEADER_FLAG):
179 self.header_records.append(record)
180 logging.FileHandler.emit(self, record)
181 except (KeyboardInterrupt, SystemExit):
182 raise
183 except Exception:
184 self.handleError(record)
185
186 def load_type_change(self) -> bool:
187 """Has there been a load-type change, e.g. restart?"""
188 existing_load_type = self.existing_log_load_type()
189 if existing_load_type and self.load_type != existing_load_type:
190 return True
191 return False
192
193 def existing_log_load_type(self) -> Optional[str]:
194 """Return a log load type, if one currently exists"""
195 try:
196 existing_log_name = os.readlink(self.baseFilename)
197 except OSError:
198 return None
199 # find load type, check restart first
200 for load_type in [RESTART_LOAD_TYPE, START_LOAD_TYPE]:
201 if existing_log_name.find(load_type) > 0:
202 return load_type
203 return None
204
205 def should_rollover(self, record: logging.LogRecord) -> bool:
206 """Should rollover?"""
207 if self.log_num is None or self.stream is None:
208 return True
209 msg = "%s\n" % self.format(record)
210 try:
211 # due to non-posix-compliant Windows feature
212 self.stream.seek(0, 2)
213 except ValueError as exc:
214 # intended to catch - ValueError: I/O operation on closed file
215 raise SystemExit(exc) from None
216 return self.stream.tell() + len(msg.encode('utf8')) >= self.max_bytes
217
218 @property
219 def load_type(self) -> str:
220 """Establish current load type, as perceived by scheduler."""
221 if self.restart_num > 0:
222 return RESTART_LOAD_TYPE
223 return START_LOAD_TYPE
224
225 def do_rollover(self) -> None:
226 """Create and rollover log file if necessary."""
227 # Create new log file
228 self.new_log_file()
229 # Housekeep old log files
230 if self.arch_len:
231 self.update_log_archive(self.arch_len)
232 # Reopen stream, redirect STDOUT and STDERR to log
233 if self.stream:
234 self.stream.close()
235 self.stream = self._open()
236 # Dup STDOUT and STDERR in detach mode
237 if not self.no_detach:
238 os.dup2(self.stream.fileno(), sys.stdout.fileno())
239 os.dup2(self.stream.fileno(), sys.stderr.fileno())
240 # Emit header records (should only do this for subsequent log files)
241 for header_record in self.header_records:
242 now = time()
243 if self.ROLLOVER_NUM in header_record.__dict__:
244 # A hack to increment the rollover number that gets logged in
245 # the log file. (Rollover number only applies to a particular
246 # workflow run; note this is different from the log count
247 # number in the log filename.)
248
249 header_record.__dict__[self.ROLLOVER_NUM] += 1
250 header_record.args = (
251 header_record.__dict__[self.ROLLOVER_NUM],
252 )
253
254 # patch the record time (otherwise this will be logged with the
255 # original timestamp)
256 header_record.created = now
257
258 logging.FileHandler.emit(self, header_record)
259
260 def update_log_archive(self, arch_len: int) -> None:
261 """Maintain configured log file archive.
262 - Sort logs by file modification time
263 - Delete old log files in line with archive length configured in
264 Global Config.
265 """
266 log_files = get_sorted_logs_by_time(
267 Path(self.baseFilename).parent, f"*{LOG_FILE_EXTENSION}")
268 while len(log_files) > arch_len:
269 os.unlink(log_files.pop(0))
270
271 def new_log_file(self) -> Path:
272 """Set self.log_num and create new log file."""
273 try:
274 log_file = os.readlink(self.baseFilename)
275 except OSError:
276 # "log" symlink not yet created, this is the first log
277 self.log_num = 1
278 else:
279 self.log_num = get_next_log_number(log_file)
280 log_dir = Path(self.baseFilename).parent
281 # User-facing restart num is 1 higher than backend value
282 restart_num = self.restart_num + 1
283 filename = log_dir.joinpath(
284 f'{self.log_num:02d}-{self.load_type}-{restart_num:02d}'
285 f'{LOG_FILE_EXTENSION}'
286 )
287 os.makedirs(filename.parent, exist_ok=True)
288 # Touch file
289 with open(filename, 'w+'):
290 os.utime(filename, None)
291 # Update symlink
292 if os.path.lexists(self.baseFilename):
293 os.unlink(self.baseFilename)
294 os.symlink(os.path.basename(filename), self.baseFilename)
295 return filename
296
297
298 class ReferenceLogFileHandler(logging.FileHandler):
299 """A handler class which writes filtered reference logging records
300 to disk files.
301 """
302
303 REF_LOG_TEXTS = (
304 'triggered off',
305 'Initial point',
306 'Start point',
307 'Final point',
308 'Start task'
309 )
310 """List of texts used for filtering messages."""
311
312 def __init__(self, filename):
313 """Create the reference log file handler, specifying the file to
314 write the reference log lines."""
315 with suppress(OSError):
316 os.unlink(filename)
317 super().__init__(filename)
318 self.formatter = logging.Formatter('%(message)s')
319 self.addFilter(self._filter)
320
321 def _filter(self, record):
322 """Filter a logging record. From the base class Filterer (parent of
323 logging.Handler).
324
325 Args:
326 record (logging.LogRecord): a log record.
327 Returns:
328 bool: True for message to be logged, False otherwise.
329 """
330 return any(text in record.getMessage() for text in self.REF_LOG_TEXTS)
331
332
333 LOG_LEVEL_REGEXES = [
334 (
335 re.compile(r'(^.*%s.*\n((^\t.*\n)+)?)' % level, re.M),
336 replacement.format(r'\1')
337 )
338 for level, replacement in CylcLogFormatter.COLORS.items()
339 ]
340
341
342 def re_formatter(log_string):
343 """Read in an uncoloured log_string file and apply colour formatting."""
344 for sub, repl in LOG_LEVEL_REGEXES:
345 log_string = cparse(sub.sub(repl, log_string))
346 return log_string
347
348
349 def set_timestamps(logger: logging.Logger, enable: bool) -> None:
350 """Enable or disable logging timestamps."""
351 for handler in logger.handlers:
352 if isinstance(handler.formatter, CylcLogFormatter):
353 handler.formatter.configure(timestamp=enable)
354
355
356 def setup_segregated_log_streams(
357 logger: logging.Logger, stderr_handler: logging.StreamHandler
358 ) -> None:
359 """Set up a logger so that info and debug messages get printed to stdout,
360 while warnings and above get printed to stderr.
361
362 Args:
363 logger: The logger to modify.
364 stderr_handler: The existing stderr stream handler.
365 """
366 stdout_handler = logging.StreamHandler(sys.stdout)
367 stdout_handler.setLevel(logging.DEBUG)
368 # Filter out >= warnings from stdout
369 stdout_handler.addFilter(lambda rec: rec.levelno < logging.WARNING)
370 if stderr_handler.formatter:
371 stdout_handler.setFormatter(stderr_handler.formatter)
372 logger.addHandler(stdout_handler)
373
374 stderr_handler.setLevel(logging.WARNING)
375
376
377 def close_log(logger: logging.Logger) -> None:
378 """Close log handlers for the specified logger."""
379 for handler in logger.handlers:
380 with suppress(IOError):
381 # suppress traceback which `logging` might try to write to the
382 # log we are trying to close
383 handler.close()
384
385
386 def get_next_log_number(log_filepath: Union[str, Path]) -> int:
387 """Returns the next log number for the given log file path/name.
388
389 Log name formats are of the form :
390 <log number>-<load type>-<start number>
391 When given the latest log it returns the next log number.
392
393 Examples:
394 >>> get_next_log_number('03-restart-02.log')
395 4
396 >>> get_next_log_number('/some/path/to/19-start-01.cylc')
397 20
398 >>> get_next_log_number('199-start-08.log')
399 200
400 >>> get_next_log_number('blah')
401 1
402 """
403 try:
404 stripped_log = os.path.basename(log_filepath)
405 return int(stripped_log.partition("-")[0]) + 1
406 except ValueError:
407 return 1
408
409
410 def get_sorted_logs_by_time(
411 log_dir: Union[Path, str], pattern: str
412 ) -> List[str]:
413 """Returns time sorted logs from directory provided, filtered by pattern"""
414 log_files = glob(os.path.join(log_dir, pattern))
415 # Sort log files by modification time
416 return sorted(log_files, key=os.path.getmtime)
417
418
419 def get_reload_start_number(config_logs: List[str]) -> str:
420 """Find the start number, for reload config filename.
421 """
422 if not config_logs:
423 return '01'
424 else:
425 try:
426 latest_log = config_logs.pop(-1)
427 start_num = int(
428 latest_log.rpartition("-")[2].replace('.cylc', ''))
429 except Exception:
430 return '01'
431 return f'{start_num:02d}'
432
433
434 @contextmanager
435 def patch_log_level(logger: logging.Logger, level: int = logging.INFO):
436 """Temporarily patch the logging level of a logger if the specified level
437 is less severe than the current level.
438
439 Defaults to INFO.
440 """
441 orig_level = logger.level
442 if level < orig_level:
443 logger.setLevel(level)
444 yield
445 logger.setLevel(orig_level)
446 else: # No need to patch
447 yield