Python logging.shutdown() Examples

The following are 30 code examples for showing how to use logging.shutdown(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module logging , or try the search function .

Example 1
Project: simnibs   Author: simnibs   File: run_simnibs.py    License: GNU General Public License v3.0 6 votes vote down vote up
def run_simnibs(simnibs_struct, cpus=1):
    """Runs a simnnibs problem.

    Parameters:
    --------------
    simnibs_struct: sim_struct.mat.SESSION of str
        SESSION of name of '.mat' file defining the simulation
    cpus: int
        Number of processes to run in parallel (if avaliable)
    """
    np.set_printoptions(precision=4)

    if isinstance(simnibs_struct, str):
        p = read_mat(simnibs_struct)
    else:
        p = simnibs_struct

    out = p.run(cpus=cpus)
    logging.shutdown()
    return out 
Example 2
Project: python-netsurv   Author: sofia-netsurv   File: logging.py    License: MIT License 6 votes vote down vote up
def pytest_sessionfinish(self):
        with self.live_logs_context():
            if self.log_cli_handler:
                self.log_cli_handler.set_when("sessionfinish")
            if self.log_file_handler is not None:
                try:
                    with catching_logs(
                        self.log_file_handler, level=self.log_file_level
                    ):
                        yield
                finally:
                    # Close the FileHandler explicitly.
                    # (logging.shutdown might have lost the weakref?!)
                    self.log_file_handler.close()
            else:
                yield 
Example 3
Project: python-netsurv   Author: sofia-netsurv   File: logging.py    License: MIT License 6 votes vote down vote up
def pytest_sessionfinish(self):
        with self.live_logs_context():
            if self.log_cli_handler:
                self.log_cli_handler.set_when("sessionfinish")
            if self.log_file_handler is not None:
                try:
                    with catching_logs(
                        self.log_file_handler, level=self.log_file_level
                    ):
                        yield
                finally:
                    # Close the FileHandler explicitly.
                    # (logging.shutdown might have lost the weakref?!)
                    self.log_file_handler.close()
            else:
                yield 
Example 4
Project: airflow   Author: apache   File: test_logging_config.py    License: Apache License 2.0 6 votes vote down vote up
def reset_logging():
    """Reset Logging"""
    manager = logging.root.manager
    manager.disabled = logging.NOTSET
    airflow_loggers = [
        logger for logger_name, logger in manager.loggerDict.items() if logger_name.startswith('airflow')
    ]
    for logger in airflow_loggers:  # pylint: disable=too-many-nested-blocks
        if isinstance(logger, logging.Logger):
            logger.setLevel(logging.NOTSET)
            logger.propagate = True
            logger.disabled = False
            logger.filters.clear()
            handlers = logger.handlers.copy()
            for handler in handlers:
                # Copied from `logging.shutdown`.
                try:
                    handler.acquire()
                    handler.flush()
                    handler.close()
                except (OSError, ValueError):
                    pass
                finally:
                    handler.release()
                logger.removeHandler(handler) 
Example 5
Project: n6   Author: CERT-Polska   File: log_helpers.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def close(self):
        # typically, this method is called at interpreter exit
        # (by logging.shutdown() which is always registered with
        # atexit.register() machinery)
        try:
            try:
                super(AMQPHandler, self).close()
                self._closing = True
                self._pusher.shutdown()
            except:
                dump_condensed_debug_msg(
                    'EXCEPTION DURING EXECUTION OF close() OF THE AMQP LOGGING HANDLER!')
                raise
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            exc = sys.exc_info()[1]
            self._error_fifo.put(exc) 
Example 6
Project: RAFCON   Author: DLR-RM   File: start.py    License: Eclipse Public License 1.0 6 votes vote down vote up
def signal_handler(signal, frame=None):
    state_machine_execution_engine = core_singletons.state_machine_execution_engine
    core_singletons.shut_down_signal = signal

    # in this case the print is on purpose to see more easily if the interrupt signal reached the thread
    print(_("Signal '{}' received.\nExecution engine will be stopped and program will be shutdown!").format(
        SIGNALS_TO_NAMES_DICT.get(signal, "[unknown]")))

    # close gui properly
    gui_singletons.main_window_controller.get_controller('menu_bar_controller').on_quit_activate(None)

    post_gui_destruction()

    logging.shutdown()

    # Do not use sys.exit() in signal handler:
    # http://thushw.blogspot.de/2010/12/python-dont-use-sysexit-inside-signal.html
    # noinspection PyProtectedMember
    os._exit(0) 
Example 7
Project: RAFCON   Author: DLR-RM   File: start.py    License: Eclipse Public License 1.0 6 votes vote down vote up
def register_signal_handlers(callback):
    # When using plain signal.signal to install a signal handler, the GUI will not shutdown until it receives the
    # focus again. The following logic (inspired from https://stackoverflow.com/a/26457317) fixes this
    def install_glib_handler(sig):
        unix_signal_add = None

        if hasattr(GLib, "unix_signal_add"):
            unix_signal_add = GLib.unix_signal_add
        elif hasattr(GLib, "unix_signal_add_full"):
            unix_signal_add = GLib.unix_signal_add_full

        if unix_signal_add:
            unix_signal_add(GLib.PRIORITY_HIGH, sig, callback, sig)

    def idle_handler(*args):
        GLib.idle_add(callback, *args, priority=GLib.PRIORITY_HIGH)

    for signal_code in [signal.SIGHUP, signal.SIGINT, signal.SIGTERM]:
        signal.signal(signal_code, idle_handler)
        GLib.idle_add(install_glib_handler, signal_code, priority=GLib.PRIORITY_HIGH) 
Example 8
Project: RAFCON   Author: DLR-RM   File: start.py    License: Eclipse Public License 1.0 6 votes vote down vote up
def signal_handler(signal, frame):
    global _user_abort

    state_machine_execution_engine = core_singletons.state_machine_execution_engine
    core_singletons.shut_down_signal = signal

    logger.info("Shutting down ...")

    try:
        if not state_machine_execution_engine.finished_or_stopped():
            state_machine_execution_engine.stop()
            state_machine_execution_engine.join(3)  # Wait max 3 sec for the execution to stop
    except Exception:
        logger.exception("Could not stop state machine")

    _user_abort = True

    # shutdown twisted correctly
    if reactor_required():
        from twisted.internet import reactor
        if reactor.running:
            plugins.run_hook("pre_destruction")
            reactor.callFromThread(reactor.stop)

    logging.shutdown() 
Example 9
Project: Fluid-Designer   Author: Microvellum   File: test_logging.py    License: GNU General Public License v3.0 6 votes vote down vote up
def setUp(self):
        super(LoggerAdapterTest, self).setUp()
        old_handler_list = logging._handlerList[:]

        self.recording = RecordingHandler()
        self.logger = logging.root
        self.logger.addHandler(self.recording)
        self.addCleanup(self.logger.removeHandler, self.recording)
        self.addCleanup(self.recording.close)

        def cleanup():
            logging._handlerList[:] = old_handler_list

        self.addCleanup(cleanup)
        self.addCleanup(logging.shutdown)
        self.adapter = logging.LoggerAdapter(logger=self.logger, extra=None) 
Example 10
Project: ironpython3   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 6 votes vote down vote up
def setUp(self):
        super(LoggerAdapterTest, self).setUp()
        old_handler_list = logging._handlerList[:]

        self.recording = RecordingHandler()
        self.logger = logging.root
        self.logger.addHandler(self.recording)
        self.addCleanup(self.logger.removeHandler, self.recording)
        self.addCleanup(self.recording.close)

        def cleanup():
            logging._handlerList[:] = old_handler_list

        self.addCleanup(cleanup)
        self.addCleanup(logging.shutdown)
        self.adapter = logging.LoggerAdapter(logger=self.logger, extra=None) 
Example 11
Project: security-utilities   Author: sevro   File: main.py    License: GNU General Public License v3.0 6 votes vote down vote up
def main(args):
    """ Main

    """
    setup_logs()
    _logger.debug("Starting main()")

    args = parse_args(args)
    print("[*] Initiating attack on IP address {}:{}".format(args.ip, args.port))
    if args.test:
        pwn(args.ip, args.port, 'test')
    elif args.unique:
        pwn(args.ip, args.port, 'unique')
    elif args.chars:
        pwn(args.ip, args.port, 'chars')
    elif args.breakpoint:
        pwn(args.ip, args.port, 'break')
    else:
        pwn(args.ip, args.port, args.payload)

    _logger.debug("All done, shutting down.")
    logging.shutdown() 
Example 12
Project: security-utilities   Author: sevro   File: main.py    License: GNU General Public License v3.0 6 votes vote down vote up
def main(args):
    """ Main

    TODO: validate ip address input
    
    """
    setup_logs()
    _logger.debug("Starting main()")

    ips = []
    args = parse_args(args)
    print("[*] Fuzzing port {} on IP address {}".format(args.port, args.ip))
    fuzz(args.ip, args.port, args.size, args.increment)

    _logger.debug("All done, shutting down.")
    logging.shutdown() 
Example 13
Project: iSDX   Author: sdn-ixp   File: faucet_util.py    License: Apache License 2.0 5 votes vote down vote up
def kill_on_exception(logname):
    """decorator to ensure functions will kill ryu when an unhandled exception
    occurs"""
    def _koe(func):
        @wraps(func)
        def __koe(*args, **kwargs):
            try:
                func(*args, **kwargs)
            except:
                logging.getLogger(logname).exception(
                    "Unhandled exception, killing RYU")
                logging.shutdown()
                os.kill(os.getpid(), signal.SIGKILL)
        return __koe
    return _koe 
Example 14
Project: sanic   Author: huge-success   File: test_logging.py    License: MIT License 5 votes vote down vote up
def reset_logging():
    logging.shutdown()
    reload(logging) 
Example 15
Project: tornado-zh   Author: tao12345666333   File: process_test.py    License: MIT License 5 votes vote down vote up
def tearDown(self):
        if task_id() is not None:
            # We're in a child process, and probably got to this point
            # via an uncaught exception.  If we return now, both
            # processes will continue with the rest of the test suite.
            # Exit now so the parent process will restart the child
            # (since we don't have a clean way to signal failure to
            # the parent that won't restart)
            logging.error("aborting child process from tearDown")
            logging.shutdown()
            os._exit(1)
        # In the surviving process, clear the alarm we set earlier
        signal.alarm(0)
        super(ProcessTest, self).tearDown() 
Example 16
Project: tornado-zh   Author: tao12345666333   File: process_test.py    License: MIT License 5 votes vote down vote up
def tearDown(self):
        if task_id() is not None:
            # We're in a child process, and probably got to this point
            # via an uncaught exception.  If we return now, both
            # processes will continue with the rest of the test suite.
            # Exit now so the parent process will restart the child
            # (since we don't have a clean way to signal failure to
            # the parent that won't restart)
            logging.error("aborting child process from tearDown")
            logging.shutdown()
            os._exit(1)
        # In the surviving process, clear the alarm we set earlier
        signal.alarm(0)
        super(ProcessTest, self).tearDown() 
Example 17
Project: knack   Author: microsoft   File: test_command_with_configured_defaults.py    License: MIT License 5 votes vote down vote up
def tearDownClass(cls):
        logging.shutdown() 
Example 18
Project: LagouJob   Author: lucasxlu   File: log.py    License: Apache License 2.0 5 votes vote down vote up
def init_logger():
    """Reload the global logger."""
    global g_logger

    if g_logger is None:
        g_logger = logging.getLogger()
    else:
        logging.shutdown()
        g_logger.handlers = []

    g_logger.setLevel(logging.DEBUG) 
Example 19
Project: king-phisher   Author: rsmusllp   File: __main__.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sig_handler(server, name, number, frame):
	signal.signal(signal.SIGINT, signal.SIG_IGN)
	signal.signal(signal.SIGTERM, signal.SIG_IGN)
	logger.info("received signal {0}, shutting down the server".format(name))
	threading.Thread(target=server.shutdown).start() 
Example 20
def main():
    irc_log()
    logging.shutdown() 
Example 21
def main():
    irc_log()
    logging.shutdown() 
Example 22
def main():
    irc_log()
    logging.shutdown() 
Example 23
Project: opendevops   Author: opendevops-cn   File: process_test.py    License: GNU General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        if task_id() is not None:
            # We're in a child process, and probably got to this point
            # via an uncaught exception.  If we return now, both
            # processes will continue with the rest of the test suite.
            # Exit now so the parent process will restart the child
            # (since we don't have a clean way to signal failure to
            # the parent that won't restart)
            logging.error("aborting child process from tearDown")
            logging.shutdown()
            os._exit(1)
        # In the surviving process, clear the alarm we set earlier
        signal.alarm(0)
        super(ProcessTest, self).tearDown() 
Example 24
Project: visual_foresight   Author: SudeepDasari   File: robot_controller_interface.py    License: MIT License 5 votes vote down vote up
def clean_shutdown(self):
        pid = os.getpid()
        logging.getLogger('robot_logger').info('Exiting example w/ pid: {}'.format(pid))
        logging.shutdown()

        if self._is_email_setup and self._log_file:
            self._send_email("Collection on {} has exited!".format(self._robot_name), attachment=self._log_file)
        elif self._is_email_setup:
            self._send_email("Collection on {} has exited!".format(self._robot_name))
        
        os.kill(-pid, 9) 
Example 25
Project: Controllers   Author: ipop-project   File: Logger.py    License: MIT License 5 votes vote down vote up
def terminate(self):
        logging.shutdown() 
Example 26
Project: viewfinder   Author: viewfinderco   File: process_test.py    License: Apache License 2.0 5 votes vote down vote up
def tearDown(self):
        if task_id() is not None:
            # We're in a child process, and probably got to this point
            # via an uncaught exception.  If we return now, both
            # processes will continue with the rest of the test suite.
            # Exit now so the parent process will restart the child
            # (since we don't have a clean way to signal failure to
            # the parent that won't restart)
            logging.error("aborting child process from tearDown")
            logging.shutdown()
            os._exit(1)
        # In the surviving process, clear the alarm we set earlier
        signal.alarm(0)
        super(ProcessTest, self).tearDown() 
Example 27
Project: viewfinder   Author: viewfinderco   File: process_test.py    License: Apache License 2.0 5 votes vote down vote up
def tearDown(self):
        if task_id() is not None:
            # We're in a child process, and probably got to this point
            # via an uncaught exception.  If we return now, both
            # processes will continue with the rest of the test suite.
            # Exit now so the parent process will restart the child
            # (since we don't have a clean way to signal failure to
            # the parent that won't restart)
            logging.error("aborting child process from tearDown")
            logging.shutdown()
            os._exit(1)
        # In the surviving process, clear the alarm we set earlier
        signal.alarm(0)
        super(ProcessTest, self).tearDown() 
Example 28
Project: pex   Author: pantsbuild   File: base_command.py    License: Apache License 2.0 5 votes vote down vote up
def main(self, args):
        # type: (List[str]) -> int
        try:
            with self.main_context():
                return self._main(args)
        finally:
            logging.shutdown() 
Example 29
Project: teleport   Author: tp4a   File: process_test.py    License: Apache License 2.0 5 votes vote down vote up
def tearDown(self):
        if task_id() is not None:
            # We're in a child process, and probably got to this point
            # via an uncaught exception.  If we return now, both
            # processes will continue with the rest of the test suite.
            # Exit now so the parent process will restart the child
            # (since we don't have a clean way to signal failure to
            # the parent that won't restart)
            logging.error("aborting child process from tearDown")
            logging.shutdown()
            os._exit(1)
        # In the surviving process, clear the alarm we set earlier
        signal.alarm(0)
        super(ProcessTest, self).tearDown() 
Example 30
Project: airflow   Author: apache   File: es_task_handler.py    License: Apache License 2.0 5 votes vote down vote up
def close(self):
        # When application exit, system shuts down all handlers by
        # calling close method. Here we check if logger is already
        # closed to prevent uploading the log to remote storage multiple
        # times when `logging.shutdown` is called.
        if self.closed:
            return

        if not self.mark_end_on_close:
            self.closed = True
            return

        # Case which context of the handler was not set.
        if self.handler is None:
            self.closed = True
            return

        # Reopen the file stream, because FileHandler.close() would be called
        # first in logging.shutdown() and the stream in it would be set to None.
        if self.handler.stream is None or self.handler.stream.closed:
            self.handler.stream = self.handler._open()  # pylint: disable=protected-access

        # Mark the end of file using end of log mark,
        # so we know where to stop while auto-tailing.
        self.handler.stream.write(self.end_of_log_mark)

        if self.write_stdout:
            self.handler.close()
            sys.stdout = sys.__stdout__

        super().close()

        self.closed = True