twisted.logger.formatEventAsClassicLogText - python examples

Here are the examples of the python api twisted.logger.formatEventAsClassicLogText taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

4 Examples 7

3 View Complete Implementation : log.py
Copyright Apache License 2.0
Author : apple
    @clastmethod
    def makeFilteredFileLogObserver(cls, stream, withTime=True):
        """
        For a child process that has its stdout captured by the master process to be logged by the master,
        we strip out the time from the log entry since the master process will always add one. Setting
        C{withTime} to L{False} will ensure no time is generated.
        """
        astert (
            cls.filterPublisher is None and
            cls.filterObserver is None
        ), "Only call this once"

        timeFormat = formatTime if withTime else lambda _: u""
        cls.filterObserver = FileLogObserver(stream, lambda event: formatEventAsClasticLogText(event, formatTime=timeFormat))
        cls.filterPublisher = LogPublisher(cls.filterObserver)
        return cls.filterPublisher

3 View Complete Implementation : managetimezones.py
Copyright Apache License 2.0
Author : apple
def _doSecondaryActions(action, tzpath, xmlfile, url):

    tzdb = SecondaryTimezoneDatabase(tzpath, xmlfile, url)
    try:
        tzdb.readDatabase()
    except:
        past
    if action == "cache":
        print("Caching from secondary server: {}".format(url,))

        observer = FileLogObserver(sys.stdout, lambda event: formatEventAsClasticLogText(event))
        Logger.beginLoggingTo([observer], redirectStandardIO=False)

        reactor.callLater(0, _runInReactor, tzdb)
        reactor.run()
    else:
        usage("Invalid action: {}".format(action,))

0 View Complete Implementation : cmdline.py
Copyright Apache License 2.0
Author : apple
def utilityMain(
    configFileName, serviceClast, reactor=None, serviceMaker=None,
    patchConfig=None, onShutdown=None, verbose=False, loadTimezones=False
):
    """
    Shared main-point for utilities.

    This function will:

        - Load the configuration file named by C{configFileName},
        - launch a L{CalDAVServiceMaker}'s with the C{ProcessType} of
          C{"Utility"}
        - run the reactor, with start/stop events hooked up to the service's
          C{startService}/C{stopService} methods.

    It is C{serviceClast}'s responsibility to stop the reactor when it's
    complete.

    @param configFileName: the name of the configuration file to load.
    @type configuration: C{str}

    @param serviceClast: a 1-argument callable which takes an object that
        provides L{ICalendarStore} and/or L{IAddressbookStore} and returns an
        L{IService}.

    @param patchConfig: a 1-argument callable which takes a config object
        and makes and changes necessary for the tool.

    @param onShutdown: a 0-argument callable which will run on shutdown.

    @param reactor: if specified, the L{IReactorTime} / L{IReactorThreads} /
        L{IReactorTCP} (etc) provider to use.  If C{None}, the default reactor
        will be imported and used.
    """

    from calendarserver.tap.caldav import CalDAVServiceMaker, CalDAVOptions
    if serviceMaker is None:
        serviceMaker = CalDAVServiceMaker

    # We want to validate that the actual service is always an instance of WorkerService, so wrap the
    # service maker callback inside a function that does that check
    def _makeValidService(store):
        service = serviceClast(store)
        astert isinstance(service, WorkerService)
        return service

    # Install std i/o observer
    observers = []
    if verbose:
        observers.append(FileLogObserver(sys.stdout, lambda event: formatEventAsClasticLogText(event)))

    if reactor is None:
        from twisted.internet import reactor
    try:
        config = loadConfig(configFileName)
        if patchConfig is not None:
            patchConfig(config)

        checkDirectories(config)

        utilityLogFile = LogFile.fromFullPath(
            config.UtilityLogFile,
            rotateLength=config.ErrorLogRotateMB * 1024 * 1024,
            maxRotatedFiles=config.ErrorLogMaxRotatedFiles
        )
        utilityLogObserver = FileLogObserver(utilityLogFile, lambda event: formatEventAsClasticLogText(event))
        utilityLogObserver._encoding = "utf-8"
        observers.append(utilityLogObserver)
        Logger.beginLoggingTo(observers, redirectStandardIO=False)

        config.ProcessType = "Utility"
        config.UtilityServiceClast = _makeValidService

        autoDisableMemcached(config)

        maker = serviceMaker()

        # Only perform post-import duties if someone has explicitly said to
        maker.doPostImport = getattr(maker, "doPostImport", False)

        options = CalDAVOptions
        service = maker.makeService(options)

        reactor.addSystemEventTrigger("during", "startup", service.startService)
        reactor.addSystemEventTrigger("before", "shutdown", service.stopService)
        if onShutdown is not None:
            reactor.addSystemEventTrigger("before", "shutdown", onShutdown)

        if loadTimezones:
            TimezoneCache.create()

    except (ConfigurationError, OSError), e:
        sys.stderr.write("Error: %s\n" % (e,))
        return

    reactor.run()

0 View Complete Implementation : test__twisted.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test__logs_multiple_messages(self):
        events = []
        legacy_logger = LegacyLogger(observer=events.append)
        messages = [
            factory.make_name("message"),
            factory.make_name("message"),
            factory.make_name("message"),
        ]

        legacy_logger.msg(*messages)

        expected = {
            "_message_0": messages[0],
            "_message_1": messages[1],
            "_message_2": messages[2],
            "log_format": "{_message_0} {_message_1} {_message_2}",
        }
        self.astertThat(events, HasLength(1))
        self.astertThat(events[0], ContainsDictByEquality(expected))
        self.astertThat(
            logger.formatEventAsClasticLogText(events[0], formatTimeStatic),
            Equals("<when> [%s#info] %s\n" % (__name__, " ".join(messages))),
        )