#305: during startup :class:`LogHandler` may be installed before it is
        possible to route messages, therefore messages are buffered until
        :meth:`uncork` is called by :class:`ExternalContext`.
970941
def uncork(self):
        
        self._send = self.context.send
        for msg in self._buffer:
            self._send(msg)
        self._buffer = None
54669
def _unregisterHandler(self, handler, shutdown=True):
        
        if handler in self._handlers:
            self._handlers.remove(handler)
            self._logger.removeHandler(handler)
            if shutdown:
                try:
                    handler.close()
                except KeyError:
                    # Depending on the Python version, it's possible for this call
                    # to fail most likely because some logging module objects get
                    # garbage collected before the VSGLogger object is.
                    pass
306080
def setup_extended_logging(opts):
    '''
    
    '''
    if is_extended_logging_configured() is True:
        # Don't re-configure external loggers
        return

    # Explicit late import of salt's loader
    import salt.loader

    # Let's keep a reference to the current logging handlers
    initial_handlers = logging.root.handlers[:]

    # Load any additional logging handlers
    providers = salt.loader.log_handlers(opts)

    # Let's keep track of the new logging handlers so we can sync the stored
    # log records with them
    additional_handlers = []

    for name, get_handlers_func in six.iteritems(providers):
        logging.getLogger(__name__).info('Processing `log_handlers.%s`', name)
        # Keep a reference to the logging handlers count before getting the
        # possible additional ones.
        initial_handlers_count = len(logging.root.handlers)

        handlers = get_handlers_func()
        if isinstance(handlers, types.GeneratorType):
            handlers = list(handlers)
        elif handlers is False or handlers == [False]:
            # A false return value means not configuring any logging handler on
            # purpose
            logging.getLogger(__name__).info(
                'The `log_handlers.%s.setup_handlers()` function returned '
                '`False` which means no logging handler was configured on '
                'purpose. Continuing...', name
            )
            continue
        else:
            # Make sure we have an iterable
            handlers = [handlers]

        for handler in handlers:
            if not handler and \
                    len(logging.root.handlers) == initial_handlers_count:
                logging.getLogger(__name__).info(
                    'The `log_handlers.%s`, did not return any handlers '
                    'and the global handlers count did not increase. This '
                    'could be a sign of `log_handlers.%s` not working as '
                    'supposed', name, name
                )
                continue

            logging.getLogger(__name__).debug(
                'Adding the \'%s\' provided logging handler: \'%s\'',
                name, handler
            )
            additional_handlers.append(handler)
            logging.root.addHandler(handler)

    for handler in logging.root.handlers:
        if handler in initial_handlers:
            continue
        additional_handlers.append(handler)

    # Sync the null logging handler messages with the temporary handler
    if LOGGING_STORE_HANDLER is not None:
        LOGGING_STORE_HANDLER.sync_with_handlers(additional_handlers)
    else:
        logging.getLogger(__name__).debug(
            'LOGGING_STORE_HANDLER is already None, can\'t sync messages '
            'with it'
        )

    # Remove the temporary queue logging handler
    __remove_queue_logging_handler()

    # Remove the temporary null logging handler (if it exists)
    __remove_null_logging_handler()

    global __EXTERNAL_LOGGERS_CONFIGURED
    __EXTERNAL_LOGGERS_CONFIGURED = True
1174356
def init_logger(root_dir, name="train.log"):
    
    os.makedirs(root_dir, exist_ok=True)
    log_formatter = logging.Formatter("%(message)s")
    logger = logging.getLogger(name)
    file_handler = logging.FileHandler("{0}/{1}".format(root_dir, name), mode='w')
    file_handler.setFormatter(log_formatter)
    logger.addHandler(file_handler)
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(log_formatter)
    logger.addHandler(console_handler)
    logger.setLevel(logging.INFO)
    return logger
424239
def on_receive(self, message):
        
        if self.log_file is not None and message['should_log']:
            message_copy = Message(message['text'],
                                   Metadata(None).__dict__,
                                   message['should_log']).__dict__
            with open(self.log_file, mode='w') as f:
                f.write(json.dumps(message_copy))
            logger.info(message['metadata']['source'])
        if self.listening_for(message):
            self_thread = self.HandlerThread(self.handle, message)
            self_thread.start()
        self.cleanup()
        for child in self.children:
            child.tell(message)
281489
def exit(self, status=0, message=None):
        
        if status:
            self.logger.error(message)
        if self.__parser__:  # pylint: disable-msg=E1101
            self.__parser__.exit(status, message)  # pylint: disable-msg=E1101
        else:
            sys.exit(status)
974334
def add_logging_handler(handler, format_='file'):
    
    global __UTOOL_ROOT_LOGGER__
    if __UTOOL_ROOT_LOGGER__ is None:
        builtins.print('[WARNING] logger not started, cannot add handler')
        return
    # create formatter and add it to the handlers
    #logformat = '%Y-%m-%d %H:%M:%S'
    #logformat = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    timeformat = '%H:%M:%S'
    if format_ == 'file':
        logformat = '[%(asctime)s]%(message)s'
    elif format_ == 'stdout':
        logformat = '%(message)s'
    else:
        raise AssertionError('unknown logging format_: %r' % format_)
    # Create formatter for handlers
    formatter = logging.Formatter(logformat, timeformat)
    handler.setLevel(logging.DEBUG)
    handler.setFormatter(formatter)
    __UTOOL_ROOT_LOGGER__.addHandler(handler)
677375
def main():
    
    # Setup an initial logging handler that buffers log messages before
    # applying the final logging configuration.
    initial_handler = logging.handlers.MemoryHandler(100)
    root_logger = logging.getLogger()
    root_logger.addHandler(initial_handler)

    # Parse configuration and setup logging.
    conf = config.Config(get_config_options())
    conf.parse_args()
    setup_logging(conf)

    # Flush the buffered log messages to the final logging handler.
    initial_handler.setTarget(root_logger.handlers[-1])
    initial_handler.flush()
    root_logger.removeHandler(initial_handler)

    log_startup_info()

    connector = Connector.from_config(conf)

    # Catch SIGTERM and SIGINT to cleanup the connector gracefully
    def signame_handler(signal_name):
        def sig_handler(signum, frame):
            # Save the signal so it can be printed later
            connector.signal = (signal_name, signum)
            connector.can_run = False

        return sig_handler

    signal.signal(signal.SIGTERM, signame_handler("SIGTERM"))
    signal.signal(signal.SIGINT, signame_handler("SIGINT"))

    connector.start()

    while True:
        if not connector.is_alive():
            break
        time.sleep(3)
1304982
def setup_logging():
    
    fmt = 'DBG<0>%(pathname)s:%(lineno)d  %(funcName)s: %(message)s'

    handler_stderr = logging.StreamHandler(sys.stderr)
    handler_stderr.setFormatter(logging.Formatter(fmt))

    root_logger = logging.getLogger()
    root_logger.setLevel(logging.DEBUG)
    root_logger.addHandler(handler_stderr)
188536
def logging_on(level=logging.WARNING):
    
    global _is_logging_on

    if not _is_logging_on:
        console = logging.StreamHandler()
        console.setFormatter(logging.Formatter("[%(levelname)s: %(asctime)s :"
                                               " %(name)s] %(message)s",
                                               '%Y-%m-%d %H:%M:%S'))
        console.setLevel(level)
        logging.getLogger('').addHandler(console)
        _is_logging_on = True

    log = logging.getLogger('')
    log.setLevel(level)
    for h in log.handlers:
        h.setLevel(level)
870868
async def on_raw(self, message):
        
        self.logger.debug('<< %s', message._raw)
        if not message._valid:
            self.logger.warning('Encountered strictly invalid IRC message from server: %s',
                                message._raw)

        if isinstance(message.command, int):
            cmd = str(message.command).zfill(3)
        else:
            cmd = message.command

        # Invoke dispatcher, if we have one.
        method = 'on_raw_' + cmd.lower()
        try:
            # Set _top_level so __getattr__() can decide whether to return on_unknown or _ignored for unknown handlers.
            # The reason for this is that features can always call super().on_raw_* safely and thus don't need to care for other features,
            # while unknown messages for which no handlers exist at all are still logged.
            self._handler_top_level = True
            handler = getattr(self, method)
            self._handler_top_level = False

            await handler(message)
        except:
            self.logger.exception('Failed to execute %s handler.', method)
1238209
def init_logging(verbose=False, format='%(asctime)s %(message)s'):
    
    def sig_handler(signum, frame):
        logger = logging.getLogger()
        log_level = logger.level
        if log_level == logging.DEBUG:
            log_level = logging.WARN
        else:
            log_level = logging.DEBUG
        logging.warn('Got signal %d, setting log level to %d',
                     signum, log_level)
        logger.setLevel(log_level)

    signal.signal(signal.SIGUSR1, sig_handler)

    if verbose:
        initial_level = logging.DEBUG
    else:
        initial_level = logging.WARN
    logging.getLogger().setLevel(initial_level)
    logging.basicConfig(format=format, level=initial_level)
1101321
def _log_unhandled_exception_and_exit(cls, exc_class=None, exc=None, tb=None, add_newline=False):
    """"""
    exc_class = exc_class or sys.exc_info()[0]
    exc = exc or sys.exc_info()[1]
    tb = tb or sys.exc_info()[2]

    # This exception was raised by a signal handler with the intent to exit the program.
    if exc_class == SignalHandler.SignalHandledNonLocalExit:
      return cls._handle_signal_gracefully(exc.signum, exc.signame, exc.traceback_lines)

    extra_err_msg = None
    try:
      # Always output the unhandled exception details into a log file, including the traceback.
      exception_log_entry = cls._format_unhandled_exception_log(exc, tb, add_newline,
                                                                should_print_backtrace=True)
      cls.log_exception(exception_log_entry)
    except Exception as e:
      extra_err_msg = 'Additional error logging unhandled exception {}: {}'.format(exc, e)
      logger.error(extra_err_msg)

    # Generate an unhandled exception report fit to be printed to the terminal (respecting the
    # Exiter's should_print_backtrace field).
    stderr_printed_error = cls._format_unhandled_exception_log(
      exc, tb, add_newline,
      should_print_backtrace=cls._should_print_backtrace_to_terminal)
    if extra_err_msg:
      stderr_printed_error = '{}\n{}'.format(stderr_printed_error, extra_err_msg)
    cls._exit_with_failure(stderr_printed_error)
780861
def _initialize():
  """"""
  global _absl_logger, _absl_handler

  if _absl_logger:
    return

  original_logger_class = logging.getLoggerClass()
  logging.setLoggerClass(ABSLLogger)
  _absl_logger = logging.getLogger('absl')
  logging.setLoggerClass(original_logger_class)

  python_logging_formatter = PythonFormatter()
  _absl_handler = ABSLHandler(python_logging_formatter)

  # The absl handler logs to stderr by default. To prevent double logging to
  # stderr, the following code tries its best to remove other handlers that emit
  # to stderr. Those handlers are most commonly added when logging.info/debug is
  # called before importing this module.
  handlers = [
      h for h in logging.root.handlers
      if isinstance(h, logging.StreamHandler) and h.stream == sys.stderr]
  for h in handlers:
    logging.root.removeHandler(h)

  # The absl handler will always be attached to root, not the absl logger.
  if not logging.root.handlers:
    # Attach the absl handler at import time when there are no other handlers.
    # Otherwise it means users have explicitly configured logging, and the absl
    # handler will only be attached later in app.run(). For App Engine apps,
    # the absl handler is not used.
    logging.root.addHandler(_absl_handler)
528227
def initLogger():
    '''
    
    '''
    global logger
    logger = logging.getLogger('root')
    logger.setLevel(logging.DEBUG)
    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(logging.INFO)
    formatter = logging.Formatter("[%(asctime)s] %(levelname)s: %(message)s", "%Y-%m-%d %H:%M:%S")
    ch.setFormatter(formatter)
    logger.addHandler(ch)
583622
def initialize_logging(self):
        """"""
        # Reset logging to pass logrecords into the queue to the frontend only.
        # Existing handlers may be broken as they were copied into a new process,
        # so should be discarded.
        for loggername in [None] + list(logging.Logger.manager.loggerDict.keys()):
            logger = logging.getLogger(loggername)
            while logger.handlers:
                logger.removeHandler(logger.handlers[0])

        # Re-enable logging to console
        root_logger = logging.getLogger()

        # By default pass all warning (and higher) level messages to the frontend
        root_logger.setLevel(logging.WARN)
        root_logger.addHandler(workflows.logging.CallbackHandler(self._log_send))

        # Set up the service logger and pass all info (and higher) level messages
        # (or other level if set differently)
        self.log = logging.getLogger(self._logger_name)

        if self.start_kwargs.get("verbose_log"):
            self.log_verbosity = logging.DEBUG
        self.log.setLevel(self.log_verbosity)

        # Additionally, write all critical messages directly to console
        console = logging.StreamHandler()
        console.setLevel(logging.CRITICAL)
        root_logger.addHandler(console)
498777
function beforeUnloadHook() {
    // Synchronously check to see if any route hooks want
    // to prevent the current window/tab from closing.
    if (state.routes) {
      var hooks = getRouteHooksForRoutes(state.routes);

      var message = void 0;
      for (var i = 0, len = hooks.length; typeof message !== 'string' && i < len; ++i) {
        // Passing no args indicates to the user that this is a
        // beforeunload hook. We don't know the next location.
        message = hooks[i]();
      }

      return message;
    }
  }