我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用logging._acquireLock()。
def _config(props, category=None, disable_existing_loggers=1): logging.shutdown() # critical section # patterned after from logging.config... logging._acquireLock() try: logging._handlers.clear() del logging._handlerList[:] # Handlers add themselves to logging._handlers handlers = _install_handlers(props) _install_loggers(props, handlers, category, disable_existing_loggers) except Exception as e: traceback.print_exc() raise e finally: logging._releaseLock()
def _logging_config(config_parser, disable_existing_loggers=False): """ Helper that allows us to use an existing ConfigParser object to load logging configurations instead of a filename. Note: this code is essentially copy pasta from `logging.config.fileConfig` except we skip loading the file. """ formatters = logging.config._create_formatters(config_parser) # critical section logging._acquireLock() try: logging._handlers.clear() del logging._handlerList[:] # Handlers add themselves to logging._handlers handlers = logging.config._install_handlers(config_parser, formatters) logging.config._install_loggers(config_parser, handlers, disable_existing_loggers) finally: logging._releaseLock()
def tearDown(self): """Remove our logging stream, and restore the original logging level.""" self.stream.close() self.root_logger.removeHandler(self.root_hdlr) while self.root_logger.handlers: h = self.root_logger.handlers[0] self.root_logger.removeHandler(h) h.close() self.root_logger.setLevel(self.original_logging_level) logging._acquireLock() try: logging._levelNames.clear() logging._levelNames.update(self.saved_level_names) logging._handlers.clear() logging._handlers.update(self.saved_handlers) logging._handlerList[:] = self.saved_handler_list loggerDict = logging.getLogger().manager.loggerDict loggerDict.clear() loggerDict.update(self.saved_loggers) finally: logging._releaseLock()
def tearDown(self): """Remove our logging stream, and restore the original logging level.""" self.stream.close() self.root_logger.removeHandler(self.root_hdlr) while self.root_logger.handlers: h = self.root_logger.handlers[0] self.root_logger.removeHandler(h) h.close() self.root_logger.setLevel(self.original_logging_level) logging._acquireLock() try: logging._levelToName.clear() logging._levelToName.update(self.saved_level_to_name) logging._nameToLevel.clear() logging._nameToLevel.update(self.saved_name_to_level) logging._handlers.clear() logging._handlers.update(self.saved_handlers) logging._handlerList[:] = self.saved_handler_list loggerDict = logging.getLogger().manager.loggerDict loggerDict.clear() loggerDict.update(self.saved_loggers) finally: logging._releaseLock()
def get_logger(): ''' Returns logger used by multiprocessing ''' global _logger import logging, atexit logging._acquireLock() try: if not _logger: _logger = logging.getLogger(LOGGER_NAME) _logger.propagate = 0 logging.addLevelName(SUBDEBUG, 'SUBDEBUG') logging.addLevelName(SUBWARNING, 'SUBWARNING') # XXX multiprocessing should cleanup before logging if hasattr(atexit, 'unregister'): atexit.unregister(_exit_function) atexit.register(_exit_function) else: atexit._exithandlers.remove((_exit_function, (), {})) atexit._exithandlers.append((_exit_function, (), {})) finally: logging._releaseLock() return _logger
def fileConfig(fname, defaults=None, disable_existing_loggers=True): """ Read the logging configuration from a ConfigParser-format file. This can be called several times from an application, allowing an end user the ability to select from various pre-canned configurations (if the developer provides a mechanism to present the choices and load the chosen configuration). """ import ConfigParser cp = ConfigParser.ConfigParser(defaults) if hasattr(fname, 'readline'): cp.readfp(fname) else: cp.read(fname) formatters = _create_formatters(cp) # critical section logging._acquireLock() try: logging._handlers.clear() del logging._handlerList[:] # Handlers add themselves to logging._handlers handlers = _install_handlers(cp, formatters) _install_loggers(cp, handlers, disable_existing_loggers) finally: logging._releaseLock()
def stopListening(): """ Stop the listening server which was created with a call to listen(). """ global _listener logging._acquireLock() try: if _listener: _listener.abort = 1 _listener = None finally: logging._releaseLock()
def setUp(self): """Setup the default logging stream to an internal StringIO instance, so that we can examine log output as we want.""" logger_dict = logging.getLogger().manager.loggerDict logging._acquireLock() try: self.saved_handlers = logging._handlers.copy() self.saved_handler_list = logging._handlerList[:] self.saved_loggers = saved_loggers = logger_dict.copy() self.saved_name_to_level = logging._nameToLevel.copy() self.saved_level_to_name = logging._levelToName.copy() self.logger_states = logger_states = {} for name in saved_loggers: logger_states[name] = getattr(saved_loggers[name], 'disabled', None) finally: logging._releaseLock() # Set two unused loggers: one non-ASCII and one Unicode. # This is to test correct operation when sorting existing # loggers in the configuration code. See issue 8201. self.logger1 = logging.getLogger("\xab\xd7\xbb") self.logger2 = logging.getLogger("\u013f\u00d6\u0047") self.root_logger = logging.getLogger("") self.original_logging_level = self.root_logger.getEffectiveLevel() self.stream = io.StringIO() self.root_logger.setLevel(logging.DEBUG) self.root_hdlr = logging.StreamHandler(self.stream) self.root_formatter = logging.Formatter(self.log_format) self.root_hdlr.setFormatter(self.root_formatter) if self.logger1.hasHandlers(): hlist = self.logger1.handlers + self.root_logger.handlers raise AssertionError('Unexpected handlers: %s' % hlist) if self.logger2.hasHandlers(): hlist = self.logger2.handlers + self.root_logger.handlers raise AssertionError('Unexpected handlers: %s' % hlist) self.root_logger.addHandler(self.root_hdlr) self.assertTrue(self.logger1.hasHandlers()) self.assertTrue(self.logger2.hasHandlers())
def tearDown(self): """Remove our logging stream, and restore the original logging level.""" self.stream.close() self.root_logger.removeHandler(self.root_hdlr) while self.root_logger.handlers: h = self.root_logger.handlers[0] self.root_logger.removeHandler(h) h.close() self.root_logger.setLevel(self.original_logging_level) logging._acquireLock() try: logging._levelToName.clear() logging._levelToName.update(self.saved_level_to_name) logging._nameToLevel.clear() logging._nameToLevel.update(self.saved_name_to_level) logging._handlers.clear() logging._handlers.update(self.saved_handlers) logging._handlerList[:] = self.saved_handler_list loggerDict = logging.getLogger().manager.loggerDict loggerDict.clear() loggerDict.update(self.saved_loggers) logger_states = self.logger_states for name in self.logger_states: if logger_states[name] is not None: self.saved_loggers[name].disabled = logger_states[name] finally: logging._releaseLock()
def fileConfig(fname, defaults=None, disable_existing_loggers=True): """ Read the logging configuration from a ConfigParser-format file. This can be called several times from an application, allowing an end user the ability to select from various pre-canned configurations (if the developer provides a mechanism to present the choices and load the chosen configuration). """ import configparser cp = configparser.ConfigParser(defaults) if hasattr(fname, 'readline'): cp.read_file(fname) else: cp.read(fname) formatters = _create_formatters(cp) # critical section logging._acquireLock() try: logging._handlers.clear() del logging._handlerList[:] # Handlers add themselves to logging._handlers handlers = _install_handlers(cp, formatters) _install_loggers(cp, handlers, disable_existing_loggers) finally: logging._releaseLock()
def setUp(self): """Setup the default logging stream to an internal StringIO instance, so that we can examine log output as we want.""" logger_dict = logging.getLogger().manager.loggerDict logging._acquireLock() try: self.saved_handlers = logging._handlers.copy() self.saved_handler_list = logging._handlerList[:] self.saved_loggers = logger_dict.copy() self.saved_level_names = logging._levelNames.copy() finally: logging._releaseLock() # Set two unused loggers: one non-ASCII and one Unicode. # This is to test correct operation when sorting existing # loggers in the configuration code. See issue 8201. logging.getLogger("\xab\xd7\xbb") logging.getLogger(u"\u013f\u00d6\u0047") self.root_logger = logging.getLogger("") self.original_logging_level = self.root_logger.getEffectiveLevel() self.stream = cStringIO.StringIO() self.root_logger.setLevel(logging.DEBUG) self.root_hdlr = logging.StreamHandler(self.stream) self.root_formatter = logging.Formatter(self.log_format) self.root_hdlr.setFormatter(self.root_formatter) self.root_logger.addHandler(self.root_hdlr)
def dataToStdout(data, forceOutput=False, bold=False, content_type=None, status=CONTENT_STATUS.IN_PROGRESS): """ Writes text to the stdout (console) stream """ message = "" if not kb.get("threadException"): if forceOutput or not getCurrentThreadData().disableStdOut: if kb.get("multiThreadMode"): logging._acquireLock() if isinstance(data, unicode): message = stdoutencode(data) else: message = data try: if conf.get("api"): sys.stdout.write(message, status, content_type) else: sys.stdout.write(setColor(message, bold)) sys.stdout.flush() except IOError: pass if kb.get("multiThreadMode"): logging._releaseLock() kb.prependFlag = isinstance(data, basestring) and (len(data) == 1 and data not in ('\n', '\r') or len(data) > 2 and data[0] == '\r' and data[-1] != '\n')
def get_logger(): ''' Returns logger used by multiprocessing ''' global _logger import logging logging._acquireLock() try: if not _logger: _logger = logging.getLogger(LOGGER_NAME) _logger.propagate = 0 logging.addLevelName(SUBDEBUG, 'SUBDEBUG') logging.addLevelName(SUBWARNING, 'SUBWARNING') # XXX multiprocessing should cleanup before logging if hasattr(atexit, 'unregister'): atexit.unregister(_exit_function) atexit.register(_exit_function) else: atexit._exithandlers.remove((_exit_function, (), {})) atexit._exithandlers.append((_exit_function, (), {})) finally: logging._releaseLock() return _logger
def setUp(self): """Setup the default logging stream to an internal StringIO instance, so that we can examine log output as we want.""" logger_dict = logging.getLogger().manager.loggerDict logging._acquireLock() try: self.saved_handlers = logging._handlers.copy() self.saved_handler_list = logging._handlerList[:] self.saved_loggers = saved_loggers = logger_dict.copy() self.saved_level_names = logging._levelNames.copy() self.logger_states = logger_states = {} for name in saved_loggers: logger_states[name] = getattr(saved_loggers[name], 'disabled', None) finally: logging._releaseLock() # Set two unused loggers self.logger1 = logging.getLogger("\xab\xd7\xbb") self.logger2 = logging.getLogger("\u013f\u00d6\u0047") self.root_logger = logging.getLogger("") self.original_logging_level = self.root_logger.getEffectiveLevel() self.stream = io.StringIO() self.root_logger.setLevel(logging.DEBUG) self.root_hdlr = logging.StreamHandler(self.stream) self.root_formatter = logging.Formatter(self.log_format) self.root_hdlr.setFormatter(self.root_formatter) if self.logger1.hasHandlers(): hlist = self.logger1.handlers + self.root_logger.handlers raise AssertionError('Unexpected handlers: %s' % hlist) if self.logger2.hasHandlers(): hlist = self.logger2.handlers + self.root_logger.handlers raise AssertionError('Unexpected handlers: %s' % hlist) self.root_logger.addHandler(self.root_hdlr) self.assertTrue(self.logger1.hasHandlers()) self.assertTrue(self.logger2.hasHandlers())
def tearDown(self): """Remove our logging stream, and restore the original logging level.""" self.stream.close() self.root_logger.removeHandler(self.root_hdlr) while self.root_logger.handlers: h = self.root_logger.handlers[0] self.root_logger.removeHandler(h) h.close() self.root_logger.setLevel(self.original_logging_level) logging._acquireLock() try: logging._levelNames.clear() logging._levelNames.update(self.saved_level_names) logging._handlers.clear() logging._handlers.update(self.saved_handlers) logging._handlerList[:] = self.saved_handler_list loggerDict = logging.getLogger().manager.loggerDict loggerDict.clear() loggerDict.update(self.saved_loggers) logger_states = self.logger_states for name in self.logger_states: if logger_states[name] is not None: self.saved_loggers[name].disabled = logger_states[name] finally: logging._releaseLock()
def basicConfig(**kwargs): """Call ``logging.basicConfig`` and override the formatter it creates.""" logging.basicConfig(**kwargs) logging._acquireLock() try: stream = logging.root.handlers[0] stream.setFormatter( ColoredFormatter( fmt=kwargs.get('format', BASIC_FORMAT), datefmt=kwargs.get('datefmt', None))) finally: logging._releaseLock()
def log_level(self, level): logger.debug("Setting config.log_level to %r", level) logging.getLogger().setLevel(level) logging._acquireLock() for name, _logger in iteritems(logging.Logger.manager.loggerDict): if isinstance(_logger, logging.PlaceHolder): continue _logger.setLevel(level) logging._releaseLock()
def disable(self): self.setLevel(sys.maxsize) # Just in case. _logger.removeHandler(self) logging._acquireLock() try: del logging._handlers[self] finally: logging._releaseLock()
def dataToStdout(data, forceOutput=False, bold=False, content_type=None, status=CONTENT_STATUS.IN_PROGRESS): """ Writes text to the stdout (console) stream """ message = "" if not kb.get("threadException"): if forceOutput or not getCurrentThreadData().disableStdOut: if kb.get("multiThreadMode"): logging._acquireLock() if isinstance(data, unicode): message = stdoutencode(data) else: message = data if hasattr(conf, "api"): sys.stdout.write(message, status, content_type) else: sys.stdout.write(setColor(message, bold)) try: sys.stdout.flush() except IOError: pass if kb.get("multiThreadMode"): logging._releaseLock() kb.prependFlag = isinstance(data, basestring) and (len(data) == 1 and data not in ('\n', '\r') or len(data) > 2 and data[0] == '\r' and data[-1] != '\n')
def setUp(self): """Setup the default logging stream to an internal StringIO instance, so that we can examine log output as we want.""" logger_dict = logging.getLogger().manager.loggerDict logging._acquireLock() try: self.saved_handlers = logging._handlers.copy() self.saved_handler_list = logging._handlerList[:] self.saved_loggers = logger_dict.copy() self.saved_name_to_level = logging._nameToLevel.copy() self.saved_level_to_name = logging._levelToName.copy() finally: logging._releaseLock() # Set two unused loggers: one non-ASCII and one Unicode. # This is to test correct operation when sorting existing # loggers in the configuration code. See issue 8201. logging.getLogger("\xab\xd7\xbb") logging.getLogger(u"\u013f\u00d6\u0047") self.root_logger = logging.getLogger("") self.original_logging_level = self.root_logger.getEffectiveLevel() self.stream = cStringIO.StringIO() self.root_logger.setLevel(logging.DEBUG) self.root_hdlr = logging.StreamHandler(self.stream) self.root_formatter = logging.Formatter(self.log_format) self.root_hdlr.setFormatter(self.root_formatter) self.root_logger.addHandler(self.root_hdlr)
def get_logger(): ''' Returns logger used by multiprocessing ''' global _logger import logging logging._acquireLock() try: if not _logger: _logger = logging.getLogger(LOGGER_NAME) _logger.propagate = 0 # XXX multiprocessing should cleanup before logging if hasattr(atexit, 'unregister'): atexit.unregister(_exit_function) atexit.register(_exit_function) else: atexit._exithandlers.remove((_exit_function, (), {})) atexit._exithandlers.append((_exit_function, (), {})) finally: logging._releaseLock() return _logger
def setUp(self): """Setup the default logging stream to an internal StringIO instance, so that we can examine log output as we want.""" logger_dict = logging.getLogger().manager.loggerDict logging._acquireLock() try: self.saved_handlers = logging._handlers.copy() self.saved_handler_list = logging._handlerList[:] self.saved_loggers = saved_loggers = logger_dict.copy() self.saved_name_to_level = logging._nameToLevel.copy() self.saved_level_to_name = logging._levelToName.copy() self.logger_states = logger_states = {} for name in saved_loggers: logger_states[name] = getattr(saved_loggers[name], 'disabled', None) finally: logging._releaseLock() # Set two unused loggers self.logger1 = logging.getLogger("\xab\xd7\xbb") self.logger2 = logging.getLogger("\u013f\u00d6\u0047") self.root_logger = logging.getLogger("") self.original_logging_level = self.root_logger.getEffectiveLevel() self.stream = io.StringIO() self.root_logger.setLevel(logging.DEBUG) self.root_hdlr = logging.StreamHandler(self.stream) self.root_formatter = logging.Formatter(self.log_format) self.root_hdlr.setFormatter(self.root_formatter) if self.logger1.hasHandlers(): hlist = self.logger1.handlers + self.root_logger.handlers raise AssertionError('Unexpected handlers: %s' % hlist) if self.logger2.hasHandlers(): hlist = self.logger2.handlers + self.root_logger.handlers raise AssertionError('Unexpected handlers: %s' % hlist) self.root_logger.addHandler(self.root_hdlr) self.assertTrue(self.logger1.hasHandlers()) self.assertTrue(self.logger2.hasHandlers())
def fileConfig(fname, defaults=None, disable_existing_loggers=True): """ Read the logging configuration from a ConfigParser-format file. This can be called several times from an application, allowing an end user the ability to select from various pre-canned configurations (if the developer provides a mechanism to present the choices and load the chosen configuration). """ import configparser if isinstance(fname, configparser.RawConfigParser): cp = fname else: cp = configparser.ConfigParser(defaults) if hasattr(fname, 'readline'): cp.read_file(fname) else: cp.read(fname) formatters = _create_formatters(cp) # critical section logging._acquireLock() try: logging._handlers.clear() del logging._handlerList[:] # Handlers add themselves to logging._handlers handlers = _install_handlers(cp, formatters) _install_loggers(cp, handlers, disable_existing_loggers) finally: logging._releaseLock()