Python twisted.python.log.startLogging() Examples

The following are 30 code examples of twisted.python.log.startLogging(). 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 also want to check out all available functions/classes of the module twisted.python.log , or try the search function .
Example #1
Source File: test_log.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_startLogging(self):
        """
        startLogging() installs FileLogObserver and overrides sys.stdout and
        sys.stderr.
        """
        origStdout, origStderr = sys.stdout, sys.stderr
        self._startLoggingCleanup()
        # When done with test, reset stdout and stderr to current values:
        fakeFile = StringIO()
        observer = log.startLogging(fakeFile)
        self.addCleanup(observer.stop)
        log.msg("Hello!")
        self.assertIn("Hello!", fakeFile.getvalue())
        self.assertIsInstance(sys.stdout, LoggingFile)
        self.assertEqual(sys.stdout.level, NewLogLevel.info)
        encoding = getattr(origStdout, "encoding", None)
        if not encoding:
            encoding = sys.getdefaultencoding()
        self.assertEqual(sys.stdout.encoding.upper(), encoding.upper())
        self.assertIsInstance(sys.stderr, LoggingFile)
        self.assertEqual(sys.stderr.level, NewLogLevel.error)
        encoding = getattr(origStderr, "encoding", None)
        if not encoding:
            encoding = sys.getdefaultencoding()
        self.assertEqual(sys.stderr.encoding.upper(), encoding.upper()) 
Example #2
Source File: cftp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def run():
#    import hotshot
#    prof = hotshot.Profile('cftp.prof')
#    prof.start()
    args = sys.argv[1:]
    if '-l' in args: # cvs is an idiot
        i = args.index('-l')
        args = args[i:i+2]+args
        del args[i+2:i+4]
    options = ClientOptions()
    try:
        options.parseOptions(args)
    except usage.UsageError as u:
        print('ERROR: %s' % u)
        sys.exit(1)
    if options['log']:
        realout = sys.stdout
        log.startLogging(sys.stderr)
        sys.stdout = realout
    else:
        log.discardLogs()
    doConnect(options)
    reactor.run()
#    prof.stop()
#    prof.close() 
Example #3
Source File: test_log.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_startLoggingTwice(self):
        """
        There are some obscure error conditions that can occur when logging is
        started twice. See http://twistedmatrix.com/trac/ticket/3289 for more
        information.
        """
        # The bug is particular to the way that the t.p.log 'global' function
        # handle stdout. If we use our own stream, the error doesn't occur. If
        # we use our own LogPublisher, the error doesn't occur.
        sys.stdout = StringIO()
        self.addCleanup(setattr, sys, 'stdout', sys.__stdout__)

        def showError(eventDict):
            if eventDict['isError']:
                sys.__stdout__.write(eventDict['failure'].getTraceback())

        log.addObserver(showError)
        self.addCleanup(log.removeObserver, showError)
        observer = log.startLogging(sys.stdout)
        self.addCleanup(observer.stop)
        # At this point, we expect that sys.stdout is a StdioOnnaStick object.
        self.assertIsInstance(sys.stdout, log.StdioOnnaStick)
        fakeStdout = sys.stdout
        observer = log.startLogging(sys.stdout)
        self.assertIdentical(sys.stdout, fakeStdout) 
Example #4
Source File: test_log.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_startLoggingTwice(self):
        """
        There are some obscure error conditions that can occur when logging is
        started twice. See http://twistedmatrix.com/trac/ticket/3289 for more
        information.
        """
        self._startLoggingCleanup()
        # The bug is particular to the way that the t.p.log 'global' function
        # handle stdout. If we use our own stream, the error doesn't occur. If
        # we use our own LogPublisher, the error doesn't occur.
        sys.stdout = StringIO()

        def showError(eventDict):
            if eventDict['isError']:
                sys.__stdout__.write(eventDict['failure'].getTraceback())

        log.addObserver(showError)
        self.addCleanup(log.removeObserver, showError)
        observer = log.startLogging(sys.stdout)
        self.addCleanup(observer.stop)
        # At this point, we expect that sys.stdout is a StdioOnnaStick object.
        self.assertIsInstance(sys.stdout, LoggingFile)
        fakeStdout = sys.stdout
        observer = log.startLogging(sys.stdout)
        self.assertIs(sys.stdout, fakeStdout) 
Example #5
Source File: test_log.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_startLogging(self):
        """
        startLogging() installs FileLogObserver and overrides sys.stdout and
        sys.stderr.
        """
        origStdout, origStderr = sys.stdout, sys.stderr
        self._startLoggingCleanup()
        # When done with test, reset stdout and stderr to current values:
        fakeFile = StringIO()
        observer = log.startLogging(fakeFile)
        self.addCleanup(observer.stop)
        log.msg("Hello!")
        self.assertIn("Hello!", fakeFile.getvalue())
        self.assertIsInstance(sys.stdout, LoggingFile)
        self.assertEqual(sys.stdout.level, NewLogLevel.info)
        encoding = getattr(origStdout, "encoding", None)
        if not encoding:
            encoding = sys.getdefaultencoding()
        self.assertEqual(sys.stdout.encoding.upper(), encoding.upper())
        self.assertIsInstance(sys.stderr, LoggingFile)
        self.assertEqual(sys.stderr.level, NewLogLevel.error)
        encoding = getattr(origStderr, "encoding", None)
        if not encoding:
            encoding = sys.getdefaultencoding()
        self.assertEqual(sys.stderr.encoding.upper(), encoding.upper()) 
Example #6
Source File: test_log.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_printToStderrSetsIsError(self):
        """
        startLogging()'s overridden sys.stderr should consider everything
        written to it an error.
        """
        self._startLoggingCleanup()
        fakeFile = StringIO()
        log.startLogging(fakeFile)

        def observe(event):
            observed.append(event)
        observed = []
        log.addObserver(observe)

        print("Hello, world.", file=sys.stderr)
        self.assertEqual(observed[0]["isError"], 1) 
Example #7
Source File: test_log.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_printToStderrSetsIsError(self):
        """
        startLogging()'s overridden sys.stderr should consider everything
        written to it an error.
        """
        self._startLoggingCleanup()
        fakeFile = StringIO()
        log.startLogging(fakeFile)

        def observe(event):
            observed.append(event)
        observed = []
        log.addObserver(observe)

        print("Hello, world.", file=sys.stderr)
        self.assertEqual(observed[0]["isError"], 1) 
Example #8
Source File: cftp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def run():
#    import hotshot
#    prof = hotshot.Profile('cftp.prof')
#    prof.start()
    args = sys.argv[1:]
    if '-l' in args: # cvs is an idiot
        i = args.index('-l')
        args = args[i:i+2]+args
        del args[i+2:i+4]
    options = ClientOptions()
    try:
        options.parseOptions(args)
    except usage.UsageError as u:
        print('ERROR: %s' % u)
        sys.exit(1)
    if options['log']:
        realout = sys.stdout
        log.startLogging(sys.stderr)
        sys.stdout = realout
    else:
        log.discardLogs()
    doConnect(options)
    reactor.run()
#    prof.stop()
#    prof.close() 
Example #9
Source File: _twistw.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def runApp(config):
    passphrase = app.getPassphrase(config['encrypted'])
    app.installReactor(config['reactor'])
    application = app.getApplication(config, passphrase)
    oldstdout = sys.stdout
    oldstderr = sys.stderr
    startLogging(config['logfile'])
    app.initialLog()
    os.chdir(config['rundir'])
    service.IService(application).privilegedStartService()
    app.startApplication(application, not config['no_save'])
    app.startApplication(internet.TimerService(0.1, lambda:None), 0)
    app.runReactorWithLogging(config, oldstdout, oldstderr)
    app.reportProfile(config['report-profile'],
                      service.IProcess(application).processName)
    log.msg("Server Shut Down.") 
Example #10
Source File: twistd.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def startLogging(logfilename, sysLog, prefix, nodaemon):
    if logfilename == '-':
        if not nodaemon:
            print 'daemons cannot log to stdout'
            os._exit(1)
        logFile = sys.stdout
    elif sysLog:
        syslog.startLogging(prefix)
    elif nodaemon and not logfilename:
        logFile = sys.stdout
    else:
        logFile = app.getLogFile(logfilename or 'twistd.log')
        try:
            import signal
        except ImportError:
            pass
        else:
            def rotateLog(signal, frame):
                from twisted.internet import reactor
                reactor.callFromThread(logFile.rotate)
            signal.signal(signal.SIGUSR1, rotateLog)
        
    if not sysLog:
        log.startLogging(logFile)
    sys.stdout.flush() 
Example #11
Source File: twistd.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def runApp(config):
    checkPID(config['pidfile'])
    passphrase = app.getPassphrase(config['encrypted'])
    app.installReactor(config['reactor'])
    config['nodaemon'] = config['nodaemon'] or config['debug']
    oldstdout = sys.stdout
    oldstderr = sys.stderr
    startLogging(config['logfile'], config['syslog'], config['prefix'],
                 config['nodaemon'])
    app.initialLog()
    application = app.getApplication(config, passphrase)
    startApplication(config, application)
    app.runReactorWithLogging(config, oldstdout, oldstderr)
    removePID(config['pidfile'])
    app.reportProfile(config['report-profile'],
                      service.IProcess(application).processName)
    log.msg("Server Shut Down.") 
Example #12
Source File: test_log.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_startLoggingTwice(self):
        """
        There are some obscure error conditions that can occur when logging is
        started twice. See http://twistedmatrix.com/trac/ticket/3289 for more
        information.
        """
        self._startLoggingCleanup()
        # The bug is particular to the way that the t.p.log 'global' function
        # handle stdout. If we use our own stream, the error doesn't occur. If
        # we use our own LogPublisher, the error doesn't occur.
        sys.stdout = StringIO()

        def showError(eventDict):
            if eventDict['isError']:
                sys.__stdout__.write(eventDict['failure'].getTraceback())

        log.addObserver(showError)
        self.addCleanup(log.removeObserver, showError)
        observer = log.startLogging(sys.stdout)
        self.addCleanup(observer.stop)
        # At this point, we expect that sys.stdout is a StdioOnnaStick object.
        self.assertIsInstance(sys.stdout, LoggingFile)
        fakeStdout = sys.stdout
        observer = log.startLogging(sys.stdout)
        self.assertIs(sys.stdout, fakeStdout) 
Example #13
Source File: nodeservice.py    From kotori with GNU Affero General Public License v3.0 6 votes vote down vote up
def run():
    log.startLogging(sys.stdout)

    if len(sys.argv) > 1 and sys.argv[1] == 'debug':
        debug = True
    else:
        debug = False

    # startup greeting
    #tts_say('Herzlich Willkommen')

    WEBSOCKET_URI = 'ws://localhost:9000'
    #WEBSOCKET_URI = 'ws://master.example.com:9000'
    boot_node(WEBSOCKET_URI, debug)

    reactor.run() 
Example #14
Source File: storm32_controller.py    From wifibroadcast with GNU General Public License v3.0 5 votes vote down vote up
def main():
    log.startLogging(sys.stdout)
    reactor.connectTCP('127.0.0.1', 5760, MAVLinkClientFactory())
    reactor.run()

    rc = exit_status()
    log.msg('Exiting with code %d' % rc)
    sys.exit(rc) 
Example #15
Source File: stdio.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def main(argv=None):
    log.startLogging(file('child.log', 'w'))

    if argv is None:
        argv = sys.argv[1:]
    if argv:
        klass = reflect.namedClass(argv[0])
    else:
        klass = ConsoleManhole
    runWithProtocol(klass) 
Example #16
Source File: gtk2manhole.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _captureLocalLog(self):
        return log.startLogging(_Notafile(self, "log"), setStdout=False) 
Example #17
Source File: stdio_test_consumer.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def failed(err):
    log.startLogging(sys.stderr)
    log.err(err) 
Example #18
Source File: stdio_test_producer.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def dataReceived(self, bytes):
        self.buf += bytes
        if self._paused:
            log.startLogging(sys.stderr)
            log.msg("dataReceived while transport paused!")
            self.transport.loseConnection()
        else:
            self.transport.write(bytes)
            if self.buf.endswith('\n0\n'):
                self.transport.loseConnection()
            else:
                self.pause() 
Example #19
Source File: cli.py    From wifibroadcast with GNU General Public License v3.0 5 votes vote down vote up
def main():
    stderr = sys.stderr

    if len(sys.argv) != 2:
        print("Usage: %s <profile>" % (sys.argv[0],), file=stderr)
        sys.exit(1)

    fd = tempfile.TemporaryFile()
    log.startLogging(fd)

    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()
    curses.curs_set(0)
    stdscr.keypad(1)

    reactor.callWhenRunning(lambda: defer.maybeDeferred(init, stdscr, sys.argv[1])\
                            .addErrback(abort_on_crash))
    reactor.run()
    curses.endwin()
    rc = exit_status()

    if rc:
        log.msg('Exiting with code %d' % rc)
        fd.seek(0)
        for l in fd:
            stderr.write(l)

    sys.exit(rc) 
Example #20
Source File: test_calvin.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def testRemoteOneActor(self):
        """Testing remote port"""
        from twisted.python import log
        from twisted.internet import defer
        import sys
        defer.setDebugging(True)
        log.startLogging(sys.stdout)

        rt = self.rt1
        peer = self.rt2

        snk = request_handler.new_actor_wargs(rt, 'test.Sink', 'snk', store_tokens=1, quiet=1)
        csum = request_handler.new_actor(peer, 'std.Sum', 'sum')
        src = request_handler.new_actor(rt, 'std.CountTimer', 'src')

        request_handler.connect(rt, snk, 'token', peer.id, csum, 'integer')
        request_handler.connect(peer, csum, 'integer', rt.id, src, 'integer')

        # Wait for some tokens
        actual = wait_for_tokens(rt, snk, 10)

        request_handler.disconnect(rt, src)

        # Fetch sent
        expected = expected_tokens(rt, src, 'sum')

        self.assert_lists_equal(expected, actual)

        request_handler.delete_actor(rt, snk)
        request_handler.delete_actor(peer, csum)
        request_handler.delete_actor(rt, src) 
Example #21
Source File: gtk2manhole.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def _captureLocalLog(self):
        return log.startLogging(_Notafile(self, "log"), setStdout=False) 
Example #22
Source File: stdio.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def main(argv=None):
    log.startLogging(file('child.log', 'w'))

    if argv is None:
        argv = sys.argv[1:]
    if argv:
        klass = reflect.namedClass(argv[0])
    else:
        klass = ConsoleManhole
    runWithProtocol(klass) 
Example #23
Source File: stdio_test_consumer.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def failed(err):
    log.startLogging(sys.stderr)
    log.err(err) 
Example #24
Source File: stdio_test_producer.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def dataReceived(self, bytes):
        self.buf += bytes
        if self._paused:
            log.startLogging(sys.stderr)
            log.msg("dataReceived while transport paused!")
            self.transport.loseConnection()
        else:
            self.transport.write(bytes)
            if self.buf.endswith('\n0\n'):
                self.transport.loseConnection()
            else:
                self.pause() 
Example #25
Source File: tkunzip.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def run(argv=sys.argv):
    log.startLogging(file('tkunzip.log', 'w'))
    opt=TkunzipOptions()
    try:
        opt.parseOptions(argv[1:])
    except usage.UsageError, e:
        print str(opt)
        print str(e)
        sys.exit(1) 
Example #26
Source File: proxy.py    From root-2015-tasks with GNU General Public License v3.0 5 votes vote down vote up
def start_proxy(reactor):
    log.startLogging(sys.stderr)
    reactor.run() 
Example #27
Source File: test_dht_server.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def atest_dht_single(self, monkeypatch):
        from twisted.python import log

        log.startLogging(sys.stdout)
        iface = "0.0.0.0"
        a = None
        b = None
        q = Queue.Queue()

        defer.setDebugging(True)

        def server_started(a, *args):
            for b in args:
                if isinstance(b, twisted.python.failure.Failure):
                    b.printTraceback()
                else:
                    _log.debug("** %s" % b)
            q.put([a, args])

        try:
            a = AutoDHTServer()
            a.start(iface, cb=CalvinCB(server_started, "1"))

            # Wait for start
            assert q.get(timeout=2) == ["1", self._sucess_start]

            assert a.set(key="APA", value="banan").wait() == True
            assert a.get(key="APA").wait() == "banan"

        except Exception as e:
            _log.exception("Failed")
            pytest.fail(traceback.format_exc())
        finally:
            if a:
                yield threads.defer_to_thread(a.stop) 
Example #28
Source File: test_secdht_server.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def atest_dht_single(self, monkeypatch):
        from twisted.python import log

        log.startLogging(sys.stdout)
        iface = "0.0.0.0"
        a = None
        b = None
        q = Queue.Queue()

        defer.setDebugging(True)

        def server_started(a, *args):
            for b in args:
                if isinstance(b, twisted.python.failure.Failure):
                    b.printTraceback()
                else:
                    _log.debug("** %s" % b)
            q.put([a, args])

        try:
            a = AutoDHTServer()
            a.start(iface, cb=CalvinCB(server_started, "1"))

            # Wait for start
            assert q.get(timeout=2) == ["1", self._sucess_start]

            assert a.set(key="APA", value="banan").wait() == True
            assert a.get(key="APA").wait() == "banan"

        except Exception as e:
            _log.exception("Failed")
            pytest.fail(traceback.format_exc())
        finally:
            if a:
                yield threads.defer_to_thread(a.stop) 
Example #29
Source File: test_calvin.py    From calvin-base with Apache License 2.0 5 votes vote down vote up
def testStartNode(self):
        """Testing starting node"""
        #import sys
        #from twisted.python import log
        #from twisted.internet import defer
        #log.startLogging(sys.stdout)
        #defer.setDebugging(True)

        assert request_handler.get_node(self.rt1, self.rt1.id)['uris'] == self.rt1.uris 
Example #30
Source File: latency_test.py    From wifibroadcast with GNU General Public License v3.0 5 votes vote down vote up
def main():
    log.startLogging(sys.stdout)
    port_in, port_out, size, max_packet_rate = sys.argv[1:]
    reactor.callWhenRunning(lambda: defer.maybeDeferred(eval_max_rate, int(port_in), int(port_out), int(size), int(max_packet_rate))\
                            .addCallbacks(lambda _: reactor.stop(), abort_on_crash))
    reactor.run()

    rc = exit_status()
    log.msg('Exiting with code %d' % rc)
    sys.exit(rc)