def SetControlHandler(self, stream): """Set console handler for logging. Args: stream: The input stream, could be stdout/stderr. """ handler = logging.StreamHandler(stream) handler.setLevel(self.CONSOLE_LEVEL) file_formatter = logging.Formatter(fmt=self.LOGGING_FORMAT, datefmt='%Y/%m/%d %H:%M:%S') handler.setFormatter(file_formatter) self.logger.addHandler(handler) return handler
def SetFileHandler(self, file_name): """Set file handler for logging. Args: file_name: The file to save logs into. """ handler = logging.FileHandler(file_name) handler.setLevel(self.FILE_LEVEL) # file format is set as same as console format. file_formatter = logging.Formatter(fmt=self.LOGGING_FORMAT, datefmt='%Y/%m/%d %H:%M:%S') handler.setFormatter(file_formatter) self.logger.addHandler(handler)
def ScriptWrapperMain(find_target_func, argv=None, log_level=logging.DEBUG, log_format=constants.LOGGER_FMT): """Function usable for chromite.script.* style wrapping. Note that this function invokes sys.exit on the way out by default. Args: find_target_func: a function, which, when given the absolute pathway the script was invoked via (for example, /home/ferringb/cros/trunk/chromite/bin/cros_sdk; note that any trailing .py from the path name will be removed), will return the main function to invoke (that functor will take a single arg- a list of arguments, and shall return either None or an integer, to indicate the exit code). argv: sys.argv, or an equivalent tuple for testing. If nothing is given, sys.argv is defaulted to. log_level: Default logging level to start at. log_format: Default logging format to use. """ if argv is None: argv = sys.argv[:] target = os.path.abspath(argv[0]) name = os.path.basename(target) if target.endswith('.py'): target = os.path.splitext(target)[0] target = find_target_func(target) if target is None: print('Internal error detected- no main functor found in module %r.' % (name, ), file=sys.stderr) sys.exit(100) # Set up basic logging information for all modules that use logging. # Note a script target may setup default logging in its module namespace # which will take precedence over this. logger = logging.getLogger() logger.setLevel(log_level) logger_handler = ChromiteStreamHandler() logger_handler.setFormatter( logging.Formatter(fmt=log_format, datefmt=constants.LOGGER_DATE_FMT)) logger.addHandler(logger_handler) logging.captureWarnings(True) signal.signal(signal.SIGTERM, _DefaultHandler) ret = 1 try: ret = target(argv[1:]) except _ShutDownException as e: sys.stdout.flush() print('%s: Signaled to shutdown: caught %i signal.' % (name, e.signal), file=sys.stderr) sys.stderr.flush() except SystemExit as e: # Right now, let this crash through- longer term, we'll update the scripts # in question to not use sys.exit, and make this into a flagged error. raise except ChrootRequiredError as e: ret = _RestartInChroot(e.cmd, e.chroot_args, e.extra_env) except ExecRequiredError as e: logging.shutdown() # This does not return. os.execv(e.cmd[0], e.cmd) except Exception as e: sys.stdout.flush() print('%s: Unhandled exception:' % (name, ), file=sys.stderr) sys.stderr.flush() raise finally: logging.shutdown() if ret is None: ret = 0 sys.exit(ret)
# -*- coding: utf-8 -*- # Copyright 2017 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Handler for copying Chrome OS payloads to DUTs.""" from __future__ import print_function from chromite.lib import cros_logging as logging from chromite.lib import remote_access _LOGGING_FORMAT = '%(asctime)s %(levelname)-10s - %(message)s' _LOGGING_DATE_FORMAT = '%Y-%m-%d %H:%M:%S' LOG_FORMATTER = logging.Formatter(_LOGGING_FORMAT, _LOGGING_DATE_FORMAT) def CopyPayload(request_data): """Copy a payload file to a target DUT. This constructs a `RemoteDevice`, and calls its `CopyToDevice()` method to copy a payload file to the target device. A payload file is either the `stateful.tgz` tarball, or a Chrome OS AU payload (typically a full payload). The `request_data` argument has the following fields: * hostname: Name of the target DUT where the payload will be copied. * localpath: Path on this system to the payload file. * remotepath: Path on the DUT where the payload will be copied. * kwargs: Keyword arguments dictionanry to be passed