blob: 2d185e1ca60e9920d3a7a4bd0f7ba80e42ba3d8e [file] [log] [blame]
maruelea586f32016-04-05 11:11:33 -07001# Copyright 2015 The LUCI Authors. All rights reserved.
maruelf1f5e2a2016-05-25 17:10:39 -07002# Use of this source code is governed under the Apache License, Version 2.0
3# that can be found in the LICENSE file.
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -04004
5"""Utility relating to logging."""
6
Marc-Antoine Ruelf899c482019-10-10 23:32:06 +00007from __future__ import print_function
8
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -04009import argparse
10import codecs
maruel625c1ea2015-09-09 11:41:13 -070011import ctypes
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -040012import logging
13import logging.handlers
14import optparse
15import os
16import sys
17import tempfile
18import time
19
Takuto Ikuta39b612a2019-10-18 08:51:22 +000020import six
21
nodir9130f072016-05-27 13:59:08 -070022from utils import file_path
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -040023
24# This works around file locking issue on Windows specifically in the case of
25# long lived child processes.
26#
27# Python opens files with inheritable handle and without file sharing by
28# default. This causes the RotatingFileHandler file handle to be duplicated in
29# the subprocesses even if the log file is not used in it. Because of this
30# handle in the child process, when the RotatingFileHandler tries to os.rename()
31# the file in the parent process, it fails with:
32# WindowsError: [Error 32] The process cannot access the file because
33# it is being used by another process
34if sys.platform == 'win32':
maruel625c1ea2015-09-09 11:41:13 -070035 import ctypes
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -040036 import msvcrt # pylint: disable=F0401
37 import _subprocess # pylint: disable=F0401
38
Marc-Antoine Ruel0eb2eb22019-01-29 21:00:16 +000039 FILE_ATTRIBUTE_NORMAL = 0x80
maruel625c1ea2015-09-09 11:41:13 -070040 FILE_SHARE_READ = 1
41 FILE_SHARE_WRITE = 2
42 FILE_SHARE_DELETE = 4
43 GENERIC_READ = 0x80000000
44 GENERIC_WRITE = 0x40000000
45 OPEN_ALWAYS = 4
46
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -040047 # TODO(maruel): Make it work in cygwin too if necessary. This would have to
48 # use ctypes.cdll.kernel32 instead of _subprocess and msvcrt.
49
maruel625c1ea2015-09-09 11:41:13 -070050
51 def shared_open(path):
52 """Opens a file with full sharing mode and without inheritance.
53
54 The file is open for both read and write.
55
56 See https://bugs.python.org/issue15244 for inspiration.
57 """
Takuto Ikuta39b612a2019-10-18 08:51:22 +000058 path = six.text_type(path)
maruel625c1ea2015-09-09 11:41:13 -070059 handle = ctypes.windll.kernel32.CreateFileW(
60 path,
61 GENERIC_READ|GENERIC_WRITE,
62 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
63 None,
64 OPEN_ALWAYS,
65 FILE_ATTRIBUTE_NORMAL,
66 None)
67 ctr_handle = msvcrt.open_osfhandle(handle, os.O_BINARY | os.O_NOINHERIT)
68 return os.fdopen(ctr_handle, 'r+b')
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -040069
70
71 class NoInheritRotatingFileHandler(logging.handlers.RotatingFileHandler):
72 def _open(self):
maruel625c1ea2015-09-09 11:41:13 -070073 """Opens the log file without handle inheritance but with file sharing.
74
75 Ignores self.mode.
76 """
77 f = shared_open(self.baseFilename)
78 if self.encoding:
79 # Do the equivalent of
80 # codecs.open(self.baseFilename, self.mode, self.encoding)
81 info = codecs.lookup(self.encoding)
82 f = codecs.StreamReaderWriter(
83 f, info.streamreader, info.streamwriter, 'replace')
84 f.encoding = self.encoding
85 return f
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -040086
87
88else: # Not Windows.
89
90
91 NoInheritRotatingFileHandler = logging.handlers.RotatingFileHandler
92
93
94# Levels used for logging.
95LEVELS = [logging.ERROR, logging.INFO, logging.DEBUG]
96
97
98class CaptureLogs(object):
99 """Captures all the logs in a context."""
100 def __init__(self, prefix, root=None):
101 handle, self._path = tempfile.mkstemp(prefix=prefix, suffix='.log')
102 os.close(handle)
103 self._handler = logging.FileHandler(self._path, 'w')
104 self._handler.setLevel(logging.DEBUG)
105 formatter = UTCFormatter(
106 '%(process)d %(asctime)s: %(levelname)-5s %(message)s')
107 self._handler.setFormatter(formatter)
108 self._root = root or logging.getLogger()
109 self._root.addHandler(self._handler)
110 assert self._root.isEnabledFor(logging.DEBUG)
111
112 def read(self):
113 """Returns the current content of the logs.
114
115 This also closes the log capture so future logs will not be captured.
116 """
117 self._disconnect()
118 assert self._path
119 try:
120 with open(self._path, 'rb') as f:
121 return f.read()
122 except IOError as e:
123 return 'Failed to read %s: %s' % (self._path, e)
124
125 def close(self):
126 """Closes and delete the log."""
127 self._disconnect()
128 if self._path:
129 try:
130 os.remove(self._path)
131 except OSError as e:
132 logging.error('Failed to delete log file %s: %s', self._path, e)
133 self._path = None
134
135 def __enter__(self):
136 return self
137
138 def __exit__(self, _exc_type, _exc_value, _traceback):
139 self.close()
140
141 def _disconnect(self):
142 if self._handler:
143 self._root.removeHandler(self._handler)
144 self._handler.close()
145 self._handler = None
146
147
148class UTCFormatter(logging.Formatter):
149 converter = time.gmtime
150
151 def formatTime(self, record, datefmt=None):
152 """Change is ',' to '.'."""
153 ct = self.converter(record.created)
154 if datefmt:
155 return time.strftime(datefmt, ct)
156 else:
157 t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
158 return "%s.%03d" % (t, record.msecs)
159
160
maruel9fd83362015-10-01 10:51:27 -0700161class Filter(object):
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -0400162 """Adds fields used by the infra-specific formatter.
163
164 Fields added:
165 - 'severity': one-letter indicator of log level (first letter of levelname).
166 """
167
168 def filter(self, record):
169 record.severity = record.levelname[0]
170 return True
171
172
173def find_stderr(root=None):
174 """Returns the logging.handler streaming to stderr, if any."""
175 for log in (root or logging.getLogger()).handlers:
176 if getattr(log, 'stream', None) is sys.stderr:
177 return log
178
179
180def prepare_logging(filename, root=None):
181 """Prepare logging for scripts.
182
183 Makes it log in UTC all the time. Prepare a rotating file based log.
184 """
185 assert not find_stderr(root)
Takuto Ikutaeedccf72020-03-30 20:09:44 +0000186 formatter = UTCFormatter(
187 '%(process)d %(asctime)s %(severity)s %(pathname)s %(lineno)d:'
188 ' %(message)s')
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -0400189
190 # It is a requirement that the root logger is set to DEBUG, so the messages
191 # are not lost. It defaults to WARNING otherwise.
192 logger = root or logging.getLogger()
maruel26cfc602015-09-04 19:12:55 -0700193 if not logger:
194 # Better print insanity than crash.
Marc-Antoine Ruelf899c482019-10-10 23:32:06 +0000195 print('OMG NO ROOT', file=sys.stderr)
maruel26cfc602015-09-04 19:12:55 -0700196 return
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -0400197 logger.setLevel(logging.DEBUG)
198
199 stderr = logging.StreamHandler()
200 stderr.setFormatter(formatter)
201 stderr.addFilter(Filter())
202 # Default to ERROR.
203 stderr.setLevel(logging.ERROR)
204 logger.addHandler(stderr)
205
206 # Setup up logging to a constant file so we can debug issues where
207 # the results aren't properly sent to the result URL.
208 if filename:
Takuto Ikuta39b612a2019-10-18 08:51:22 +0000209 file_path.ensure_tree(
210 os.path.dirname(os.path.abspath(six.text_type(filename))))
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -0400211 try:
212 rotating_file = NoInheritRotatingFileHandler(
213 filename, maxBytes=10 * 1024 * 1024, backupCount=5,
214 encoding='utf-8')
215 rotating_file.setLevel(logging.DEBUG)
216 rotating_file.setFormatter(formatter)
217 rotating_file.addFilter(Filter())
218 logger.addHandler(rotating_file)
219 except Exception:
220 # May happen on cygwin. Do not crash.
221 logging.exception('Failed to open %s', filename)
222
223
224def set_console_level(level, root=None):
225 """Reset the console (stderr) logging level."""
226 handler = find_stderr(root)
maruel26cfc602015-09-04 19:12:55 -0700227 if not handler:
228 # Better print insanity than crash.
Marc-Antoine Ruelf899c482019-10-10 23:32:06 +0000229 print('OMG NO STDERR', file=sys.stderr)
maruel26cfc602015-09-04 19:12:55 -0700230 return
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -0400231 handler.setLevel(level)
232
233
234class OptionParserWithLogging(optparse.OptionParser):
235 """Adds --verbose option."""
236
237 # Set to True to enable --log-file options.
238 enable_log_file = True
239
240 # Set in unit tests.
241 logger_root = None
242
243 def __init__(self, verbose=0, log_file=None, **kwargs):
244 kwargs.setdefault('description', sys.modules['__main__'].__doc__)
245 optparse.OptionParser.__init__(self, **kwargs)
246 self.group_logging = optparse.OptionGroup(self, 'Logging')
247 self.group_logging.add_option(
248 '-v', '--verbose',
249 action='count',
250 default=verbose,
251 help='Use multiple times to increase verbosity')
252 if self.enable_log_file:
253 self.group_logging.add_option(
254 '-l', '--log-file',
255 default=log_file,
256 help='The name of the file to store rotating log details')
257 self.group_logging.add_option(
258 '--no-log', action='store_const', const='', dest='log_file',
259 help='Disable log file')
260
261 def parse_args(self, *args, **kwargs):
262 # Make sure this group is always the last one.
263 self.add_option_group(self.group_logging)
264
265 options, args = optparse.OptionParser.parse_args(self, *args, **kwargs)
266 prepare_logging(self.enable_log_file and options.log_file, self.logger_root)
267 set_console_level(
268 LEVELS[min(len(LEVELS) - 1, options.verbose)], self.logger_root)
269 return options, args
270
271
272class ArgumentParserWithLogging(argparse.ArgumentParser):
273 """Adds --verbose option."""
274
275 # Set to True to enable --log-file options.
276 enable_log_file = True
277
278 def __init__(self, verbose=0, log_file=None, **kwargs):
279 kwargs.setdefault('description', sys.modules['__main__'].__doc__)
280 kwargs.setdefault('conflict_handler', 'resolve')
281 self.__verbose = verbose
282 self.__log_file = log_file
283 super(ArgumentParserWithLogging, self).__init__(**kwargs)
284
285 def _add_logging_group(self):
286 group = self.add_argument_group('Logging')
287 group.add_argument(
288 '-v', '--verbose',
289 action='count',
290 default=self.__verbose,
291 help='Use multiple times to increase verbosity')
292 if self.enable_log_file:
293 group.add_argument(
294 '-l', '--log-file',
295 default=self.__log_file,
296 help='The name of the file to store rotating log details')
297 group.add_argument(
298 '--no-log', action='store_const', const='', dest='log_file',
299 help='Disable log file')
300
301 def parse_args(self, *args, **kwargs):
302 # Make sure this group is always the last one.
303 self._add_logging_group()
304
305 args = super(ArgumentParserWithLogging, self).parse_args(*args, **kwargs)
306 prepare_logging(self.enable_log_file and args.log_file, self.logger_root)
307 set_console_level(
308 LEVELS[min(len(LEVELS) - 1, args.verbose)], self.logger_root)
309 return args