我们从Python开源项目中,提取了以下9个代码示例,用于说明如何使用twisted.python.log.PythonLoggingObserver()。
def threaded_reactor(): """ Start the Twisted reactor in a separate thread, if not already done. Returns the reactor. """ global _twisted_thread if not _twisted_thread: from threading import Thread _twisted_thread = Thread(target=lambda: reactor.run(installSignalHandlers=False), name="Twisted") _twisted_thread.setDaemon(True) _twisted_thread.start() def hook_observer(): observer = log.PythonLoggingObserver() observer.start() import logging log.msg("PythonLoggingObserver hooked up", logLevel=logging.DEBUG) reactor.callFromThread(hook_observer) return reactor, _twisted_thread
def setup_logger(name): """Enable debug logging.""" if DEBUGLOG: logging.basicConfig( level=logging.DEBUG, format=name + ' %(asctime)-15s %(levelname)-8s %(message)s', ) disabled_loggers = [] if not PIKALOG: disabled_loggers.append('pika') for logger in disabled_loggers: logging.getLogger(logger).setLevel(logging.WARNING) new_defaults = list(Server.__init__.__defaults__) # NOTE: Patch `action_logger` argument default value. new_defaults[6] = AccessLogGenerator(sys.stdout) Server.__init__.__defaults__ = tuple(new_defaults) observer = PythonLoggingObserver(loggerName='twisted') observer.start()
def setUp(self): rootLogger = logging.getLogger("") originalLevel = rootLogger.getEffectiveLevel() rootLogger.setLevel(logging.DEBUG) @self.addCleanup def restoreLevel(): rootLogger.setLevel(originalLevel) self.hdlr, self.out = handlerAndBytesIO() rootLogger.addHandler(self.hdlr) @self.addCleanup def removeLogger(): rootLogger.removeHandler(self.hdlr) self.hdlr.close() self.lp = log.LogPublisher() self.obs = log.PythonLoggingObserver() self.lp.addObserver(self.obs.emit)
def test_startStopObserver(self): """ Test that start and stop methods of the observer actually register and unregister to the log system. """ oldAddObserver = log.addObserver oldRemoveObserver = log.removeObserver l = [] try: log.addObserver = l.append log.removeObserver = l.remove obs = log.PythonLoggingObserver() obs.start() self.assertEqual(l[0], obs.emit) obs.stop() self.assertEqual(len(l), 0) finally: log.addObserver = oldAddObserver log.removeObserver = oldRemoveObserver
def test_inheritance(self): """ Test that we can inherit L{log.PythonLoggingObserver} and use super: that's basically a validation that L{log.PythonLoggingObserver} is new-style class. """ class MyObserver(log.PythonLoggingObserver): def emit(self, eventDict): super(MyObserver, self).emit(eventDict) obs = MyObserver() l = [] oldEmit = log.PythonLoggingObserver.emit try: log.PythonLoggingObserver.emit = l.append obs.emit('foo') self.assertEqual(len(l), 1) finally: log.PythonLoggingObserver.emit = oldEmit
def emit(self, eventDict): if 'logLevel' in eventDict: level = eventDict['logLevel'] elif eventDict['isError']: level = logging.ERROR else: level = logging.DEBUG eventDict['logLevel'] = level twistedlog.PythonLoggingObserver.emit(self, eventDict)
def setup(level=logging.DEBUG): ''' Setup logging bridge from twisted to python ''' observer = log.PythonLoggingObserver() observer.start() level = config.get('loglevel', 'info') try: l = getattr(logging, level.upper()) except: l = logging.INFO logging.basicConfig(level=l)
def setupTwistedLogging(application): """Setup a L{LogFile} for the given application. @param application: A C{twisted.application.service.Application} instance. """ application.setComponent(ILogObserver, PythonLoggingObserver(None).emit)
def startWebServer(options, config): # import pdb; pdb.set_trace() # Extract properties from config log_dir = str(config["configuration"]["log_dir"]) content = str(config["configuration"]["content"]) # twisted expects byte for uris. endpoint = str(config["configuration"]["endpoint"]).encode('utf-8') host = str(config["configuration"]["host"]) port = int(config["configuration"]["port"]) # Setup logging logFileName = log_dir + os.sep + "launcherLog.log" formatting = '%(asctime)s:%(levelname)s:%(name)s:%(message)s' logging.basicConfig(level=logging.DEBUG, filename=logFileName, filemode='w', format=formatting) observer = log.PythonLoggingObserver() observer.start() if options.debug: console = logging.StreamHandler(sys.stdout) console.setLevel(logging.INFO) formatter = logging.Formatter(formatting) console.setFormatter(formatter) logging.getLogger('').addHandler(console) # Initialize web resource web_resource = File(content) if (len(content) > 0) else resource.Resource() # Attach launcher web_resource.putChild(endpoint, LauncherResource(options, config)) # Check if launcher should act as a file upload server as well if "upload_dir" in config["configuration"]: from upload import UploadPage updir = replaceVariables(config['configuration']['upload_dir'], [config['properties']]) uploadResource = UploadPage(updir) web_resource.putChild("upload", uploadResource) site = server.Site(web_resource) reactor.listenTCP(port, site, interface=host) reactor.run() # ============================================================================= # Parse config file # =============================================================================