Python twisted.logger.textFileLogObserver() Examples

The following are 18 code examples of twisted.logger.textFileLogObserver(). 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.logger , or try the search function .
Example #1
Source File: test_twistd.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _patchTextFileLogObserver(patch):
    """
    Patch L{logger.textFileLogObserver} to record every call and keep a
    reference to the passed log file for tests.

    @param patch: a callback for patching (usually L{unittest.TestCase.patch}).

    @return: the list that keeps track of the log files.
    @rtype: C{list}
    """
    logFiles = []
    oldFileLogObserver = logger.textFileLogObserver

    def observer(logFile, *args, **kwargs):
        logFiles.append(logFile)
        return oldFileLogObserver(logFile, *args, **kwargs)

    patch(logger, 'textFileLogObserver', observer)
    return logFiles 
Example #2
Source File: test_options.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_selectDefaultLogObserverDefaultWithTTY(self):
        """
        L{TwistOptions.selectDefaultLogObserver} will not override an already
        selected observer.
        """
        class TTYFile(object):
            def isatty(self):
                return True

        # stdout may not be a tty, so let's make sure it thinks it is
        self.patch(_options, "stdout", TTYFile())

        options = TwistOptions()
        options.opt_log_file("-")  # stdout, a tty
        options.selectDefaultLogObserver()

        self.assertIdentical(
            options["fileLogObserverFactory"], textFileLogObserver
        )
        self.assertEqual(options["logFormat"], "text") 
Example #3
Source File: test_options.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_selectDefaultLogObserverNoOverride(self):
        """
        L{TwistOptions.selectDefaultLogObserver} will not override an already
        selected observer.
        """
        self.patchOpen()

        options = TwistOptions()
        options.opt_log_format("text")  # Ask for text
        options.opt_log_file("queso")   # File, not a tty
        options.selectDefaultLogObserver()

        # Because we didn't select a file that is a tty, the default is JSON,
        # but since we asked for text, we should get text.
        self.assertIdentical(
            options["fileLogObserverFactory"], textFileLogObserver
        )
        self.assertEqual(options["logFormat"], "text") 
Example #4
Source File: test_options.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_selectDefaultLogObserverDefaultWithTTY(self):
        """
        L{TwistOptions.selectDefaultLogObserver} will not override an already
        selected observer.
        """
        class TTYFile(object):
            def isatty(self):
                return True

        # stdout may not be a tty, so let's make sure it thinks it is
        self.patch(_options, "stdout", TTYFile())

        options = TwistOptions()
        options.opt_log_file("-")  # stdout, a tty
        options.selectDefaultLogObserver()

        self.assertIdentical(
            options["fileLogObserverFactory"], textFileLogObserver
        )
        self.assertEqual(options["logFormat"], "text") 
Example #5
Source File: test_options.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_selectDefaultLogObserverNoOverride(self):
        """
        L{TwistOptions.selectDefaultLogObserver} will not override an already
        selected observer.
        """
        self.patchOpen()

        options = TwistOptions()
        options.opt_log_format("text")  # Ask for text
        options.opt_log_file("queso")   # File, not a tty
        options.selectDefaultLogObserver()

        # Because we didn't select a file that is a tty, the default is JSON,
        # but since we asked for text, we should get text.
        self.assertIdentical(
            options["fileLogObserverFactory"], textFileLogObserver
        )
        self.assertEqual(options["logFormat"], "text") 
Example #6
Source File: test_log.py    From ccs-twistedextensions with Apache License 2.0 5 votes vote down vote up
def test_utf8(self):
        """
        L{Logger} handles utf8 log strings and format args.
        """
        observer = LogPublisher()

        observed = []
        observer.addObserver(observed.append)

        sio = StringIO()
        observer.addObserver(textFileLogObserver(sio))

        logger = Logger(observer=observer)

        index = 0
        logger.info("t\xc3\xa9st")
        self.assertEqual(observed[index]["log_level"], LogLevel.info)
        self.assertEqual(observed[index]["log_format"], u"{msg}")
        self.assertEqual(observed[index]["msg"], u"t\xe9st")
        self.assertEqual(sio.getvalue().splitlines()[index].split("#info] ")[1], "t\xc3\xa9st")

        index += 1
        logger.info("{str}", str="t\xc3\xa9st")
        self.assertEqual(observed[index]["log_level"], LogLevel.info)
        self.assertEqual(observed[index]["log_format"], u"{str}")
        self.assertEqual(observed[index]["str"], u"t\xe9st")
        self.assertEqual(sio.getvalue().splitlines()[index].split("#info] ")[1], "t\xc3\xa9st")

        index += 1
        logger.info("T\xc3\xa9st {str}", str="t\xc3\xa9st")
        self.assertEqual(observed[index]["log_level"], LogLevel.info)
        self.assertEqual(observed[index]["log_format"], u"T\xe9st {str}")
        self.assertEqual(observed[index]["str"], u"t\xe9st")
        self.assertEqual(sio.getvalue().splitlines()[index].split("#info] ")[1], "T\xc3\xa9st t\xc3\xa9st") 
Example #7
Source File: test_streamedlogs.py    From gridsync with GNU General Public License v3.0 5 votes vote down vote up
def twlog():
    from sys import stdout
    from twisted.logger import globalLogBeginner
    from twisted.logger import textFileLogObserver

    globalLogBeginner.beginLoggingTo([textFileLogObserver(stdout)]) 
Example #8
Source File: _twistd_unix.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _getLogObserver(self):
        """
        Create and return a suitable log observer for the given configuration.

        The observer will go to syslog using the prefix C{_syslogPrefix} if
        C{_syslog} is true.  Otherwise, it will go to the file named
        C{_logfilename} or, if C{_nodaemon} is true and C{_logfilename} is
        C{"-"}, to stdout.

        @return: An object suitable to be passed to C{log.addObserver}.
        """
        if self._syslog:
            from twisted.python import syslog
            return syslog.SyslogObserver(self._syslogPrefix).emit

        if self._logfilename == '-':
            if not self._nodaemon:
                sys.exit('Daemons cannot log to stdout, exiting!')
            logFile = sys.stdout
        elif self._nodaemon and not self._logfilename:
            logFile = sys.stdout
        else:
            if not self._logfilename:
                self._logfilename = 'twistd.log'
            logFile = logfile.LogFile.fromFullPath(self._logfilename)
            try:
                import signal
            except ImportError:
                pass
            else:
                # Override if signal is set to None or SIG_DFL (0)
                if not signal.getsignal(signal.SIGUSR1):
                    def rotateLog(signal, frame):
                        from twisted.internet import reactor
                        reactor.callFromThread(logFile.rotate)
                    signal.signal(signal.SIGUSR1, rotateLog)
        return logger.textFileLogObserver(logFile) 
Example #9
Source File: test_options.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_logFormatJSON(self):
        """
        L{TwistOptions.opt_log_format} given C{"text"} uses a
        L{textFileLogObserver}.
        """
        self._testLogFormat("json", jsonFileLogObserver) 
Example #10
Source File: test_options.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_logFormatText(self):
        """
        L{TwistOptions.opt_log_format} given C{"text"} uses a
        L{textFileLogObserver}.
        """
        self._testLogFormat("text", textFileLogObserver) 
Example #11
Source File: app.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _getLogObserver(self):
        """
        Create a log observer to be added to the logging system before running
        this application.
        """
        if self._logfilename == '-' or not self._logfilename:
            logFile = sys.stdout
        else:
            logFile = logfile.LogFile.fromFullPath(self._logfilename)
        return logger.textFileLogObserver(logFile) 
Example #12
Source File: logs.py    From worker with GNU General Public License v3.0 5 votes vote down vote up
def init(outFile):
    level = levels[config.LOG_LEVEL]
    predicate = LogLevelFilterPredicate(defaultLogLevel=level)
    observer = FilteringLogObserver(textFileLogObserver(outFile=outFile), [predicate])
    observer._encoding = "utf-8"
    globalLogPublisher.addObserver(observer)
    log.info("Start logging with {l}", l=level) 
Example #13
Source File: test_log.py    From ccs-twistedextensions with Apache License 2.0 5 votes vote down vote up
def test_old_style(self):
        """
        L{Logger} handles old style log strings.
        """
        observer = LogPublisher()

        observed = []
        observer.addObserver(observed.append)

        sio = StringIO()
        observer.addObserver(textFileLogObserver(sio))

        logger = Logger(observer=observer)

        index = 0
        logger.info("test")
        self.assertEqual(observed[index]["log_level"], LogLevel.info)
        self.assertEqual(observed[index]["log_format"], u"{msg}")
        self.assertEqual(observed[index]["msg"], u"test")
        self.assertEqual(sio.getvalue().splitlines()[index].split("#info] ")[1], "test")

        index += 1
        logger.info("test {}")
        self.assertEqual(observed[index]["log_level"], LogLevel.info)
        self.assertEqual(observed[index]["log_format"], u"{msg}")
        self.assertEqual(observed[index]["msg"], u"test {}")
        self.assertEqual(sio.getvalue().splitlines()[index].split("#info] ")[1], "test {}")

        index += 1
        logger.info("test {foo}")
        self.assertEqual(observed[index]["log_level"], LogLevel.info)
        self.assertEqual(observed[index]["log_format"], u"{msg}")
        self.assertEqual(observed[index]["msg"], u"test {foo}")
        self.assertEqual(sio.getvalue().splitlines()[index].split("#info] ")[1], "test {foo}") 
Example #14
Source File: _twistd_unix.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _getLogObserver(self):
        """
        Create and return a suitable log observer for the given configuration.

        The observer will go to syslog using the prefix C{_syslogPrefix} if
        C{_syslog} is true.  Otherwise, it will go to the file named
        C{_logfilename} or, if C{_nodaemon} is true and C{_logfilename} is
        C{"-"}, to stdout.

        @return: An object suitable to be passed to C{log.addObserver}.
        """
        if self._syslog:
            # FIXME: Requires twisted.python.syslog to be ported to Py3
            # https://twistedmatrix.com/trac/ticket/7957
            from twisted.python import syslog
            return syslog.SyslogObserver(self._syslogPrefix).emit

        if self._logfilename == '-':
            if not self._nodaemon:
                sys.exit('Daemons cannot log to stdout, exiting!')
            logFile = sys.stdout
        elif self._nodaemon and not self._logfilename:
            logFile = sys.stdout
        else:
            if not self._logfilename:
                self._logfilename = 'twistd.log'
            logFile = logfile.LogFile.fromFullPath(self._logfilename)
            try:
                import signal
            except ImportError:
                pass
            else:
                # Override if signal is set to None or SIG_DFL (0)
                if not signal.getsignal(signal.SIGUSR1):
                    def rotateLog(signal, frame):
                        from twisted.internet import reactor
                        reactor.callFromThread(logFile.rotate)
                    signal.signal(signal.SIGUSR1, rotateLog)
        return logger.textFileLogObserver(logFile) 
Example #15
Source File: test_options.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_logFormatJSON(self):
        """
        L{TwistOptions.opt_log_format} given C{"text"} uses a
        L{textFileLogObserver}.
        """
        self._testLogFormat("json", jsonFileLogObserver) 
Example #16
Source File: test_options.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_logFormatText(self):
        """
        L{TwistOptions.opt_log_format} given C{"text"} uses a
        L{textFileLogObserver}.
        """
        self._testLogFormat("text", textFileLogObserver) 
Example #17
Source File: app.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _getLogObserver(self):
        """
        Create a log observer to be added to the logging system before running
        this application.
        """
        if self._logfilename == '-' or not self._logfilename:
            logFile = sys.stdout
        else:
            logFile = logfile.LogFile.fromFullPath(self._logfilename)
        return logger.textFileLogObserver(logFile) 
Example #18
Source File: logs.py    From worker with GNU General Public License v3.0 5 votes vote down vote up
def audit():
    outFile = sys.stdout if config.LOG_DIRECTORY == "stdout" else daily("audit.log")
    observer = textFileLogObserver(outFile=outFile)
    observer._encoding = "utf-8"
    return Logger(observer=observer)