当前位置: 首页>>代码示例>>Python>>正文


Python Logger.info方法代码示例

本文整理汇总了Python中twisted.logger.Logger.info方法的典型用法代码示例。如果您正苦于以下问题:Python Logger.info方法的具体用法?Python Logger.info怎么用?Python Logger.info使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twisted.logger.Logger的用法示例。


在下文中一共展示了Logger.info方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: start_upload_server

# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import info [as 别名]
def start_upload_server():
	import argparse

	from twisted.internet import reactor
	from twisted.logger import Logger, globalLogPublisher, STDLibLogObserver
	from twisted.web.server import Site
	from twisted.web.resource import Resource

	from cheesepi.server.upload import UploadHandler

	# Argument parsing
	parser = argparse.ArgumentParser()
	parser.add_argument('--port', type=int, default=18090,
	                    help='Port to listen on')
	args = parser.parse_args()

	init_logging()

	# Make twisted logging write to pythons logging module
	globalLogPublisher.addObserver(STDLibLogObserver(name="cheesepi.server.upload"))

	# Use twisted logger when in twisted
	log = Logger()

	root = Resource()
	root.putChild("upload", UploadHandler())
	upload_server = Site(root)

	reactor.listenTCP(args.port, upload_server)
	log.info("Starting upload server on port %d..." % args.port)
	reactor.run()
开发者ID:haf,项目名称:cheesepi,代码行数:33,代码来源:utils.py

示例2: LoggingProcessProtocol

# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import info [as 别名]
class LoggingProcessProtocol(ProcessProtocol, object):
    """
    A ProcessProtocol that logs all output to a file
    """
    def __init__(self, commandname, maxbackups=3):
        log_name = commandname + ".log"
        log_dir = os.path.join(fs.adirs.user_log_dir, "processes")
        if not os.path.isdir(log_dir):
            os.makedirs(log_dir)
        log_name = os.path.join(log_dir, log_name)
        _backup_logs(log_name, maxbackups)
        self.log = Logger(observer=textFileLogObserver(io.open(log_name, "w")),
                          namespace="")
        super(LoggingProcessProtocol, self).__init__()

    def connectionMade(self):
        self.finished = defer.Deferred()

    def outReceived(self, data):
        self.log.info("{data}", data=bytes_to_str(data.strip()))

    def errReceived(self, data):
        self.log.error("{data}", data=bytes_to_str(data.strip()))

    def processEnded(self, reason):
        if reason.check(ProcessDone):
            self.finished.callback(True)
            self.log.info("Process finished without error")
        else:
            self.finished.errback(reason)
            self.log.error("Process ended with error: {reason!r}",
                           reason=reason)
开发者ID:DefaultUser,项目名称:PyTIBot,代码行数:34,代码来源:async_process.py

示例3: start_control_server

# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import info [as 别名]
def start_control_server():
	import argparse

	from twisted.internet import reactor
	from twisted.logger import Logger, globalLogPublisher, STDLibLogObserver

	from cheesepi.server.control import (CheeseRPCServerFactory,
	                                     CheeseRPCServer)
	from cheesepi.server.storage.mongo import MongoDAO

	# Argument parsing
	parser = argparse.ArgumentParser()
	parser.add_argument('--port', type=int, default=18080,
	                    help='Port to listen on')
	args = parser.parse_args()

	init_logging()

	# Make twisted logging write to pythons logging module
	globalLogPublisher.addObserver(STDLibLogObserver(name="cheesepi.server.control"))

	# Use twisted logger when in twisted
	log = Logger()

	# Logging
	#log = Logger()
	#globalLogPublisher.addObserver(PrintingObserver())

	#dao = MongoDAO()
	dao = MongoDAO('localhost', 27017)
	control_server = CheeseRPCServer(dao).getStreamFactory(CheeseRPCServerFactory)

	reactor.listenTCP(args.port, control_server)
	log.info("Starting control server on port %d..." % args.port)
	reactor.run()
开发者ID:haf,项目名称:cheesepi,代码行数:37,代码来源:utils.py

示例4: test_logger_namespace

# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import info [as 别名]
    def test_logger_namespace(self):
        """
        A `twisted.logger.Logger` with a namespace gets that namespace as a prefix.
        """
        fout = StringIO()
        log = Logger(namespace="ns", observer=FileLogObserver(fout, formatForSystemd))

        log.info("info\n{more}", more="info")
        log.error("err")

        self.assertEqual((
            "<6>[ns] info\n"
            "<6>  info\n"
            "<3>[ns] err\n"
        ), fout.getvalue())
开发者ID:twm,项目名称:yarrharr,代码行数:17,代码来源:test_application.py

示例5: _relaying_test

# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import info [as 别名]
    def _relaying_test(self, eliot_logger, observer):
        """
        Publish an event using ``twisted.logger`` with ``observer`` hooked up and
        assert that the event ends up being seen by ``eliot_logger``.
        """
        twisted_logger = TwistedLogger(observer=observer)
        twisted_logger.info("Hello, world.")

        [event] = eliot_logger.messages
        self.assertThat(
            event,
            ContainsDict(dict(
                # A couple things from the Twisted side of the fence.
                log_namespace=Equals("lae_util.test.test_eliot"),
                log_format=Equals("Hello, world."),
                # And also some Eliot stuff.
                task_uuid=IsInstance(unicode),
                task_level=IsInstance(list),
            )),
        )
开发者ID:LeastAuthority,项目名称:leastauthority.com,代码行数:22,代码来源:test_eliot.py

示例6: MFTests

# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import info [as 别名]
class MFTests(object):

    def __init__(self):
        self.log = Logger()

    def start_static(self):
        resource = File(os.getcwd() + '/tests/pages')
        factory = Site(resource)
        endpoint = endpoints.TcP4ServerEndpoint(reactor, 0)
        endpoint.listen(factory)
        # reactor.run()

    def send_request(self):
        pass

    def stop_callback(self, none):
        reactor.stop()

    def test_log_handler(self):
        handler = LogHandler()
        self.log.info('Test msg with {parameter} is OK', parameter="value")
        self.log.error('Test error with {parameter} is OK', parameter="value")
        self.log.error('Test error with {parameter} (isError={isError}) is OK', parameter="value", isError=False)
        self.log.error('Test error with {parameter} (isError={isError}) is OK', parameter="value", isError=True)

        d = defer.Deferred()
        reactor.callLater(0, d.callback, None)
        d.addCallback(self.stop_callback)
        d.addErrback(lambda err: print("callback error: %s\ncallback traceback: %s" % (err.getErrorMessage(), err.getTraceback())))

        reactor.run()

    def test_server(self):
        d = defer.Deferred()
        reactor.callLater(3, d.callback, None)
        d.addCallback(self.stop_callback)
        #d.addCallback(self.send_request)
        d.addErrback(lambda err: print("callback error: %s\ncallback traceback: %s" % (err.getErrorMessage(), err.getTraceback())))

        Server(port=1234, db_creds=None, snapshot_dir='~/tmp', user_agent='', debug=False).run()
开发者ID:taroved,项目名称:pol,代码行数:42,代码来源:test_downloader.py

示例7: IRCd

# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import info [as 别名]
class IRCd(Service):
	def __init__(self, configFileName):
		self.config = Config(self, configFileName)
		
		self.boundPorts = {}
		self.loadedModules = {}
		self._loadedModuleData = {}
		self._unloadingModules = {}
		self.commonModules = set()
		self.userCommands = {}
		self.serverCommands = {}
		self.channelModes = ({}, {}, {}, {})
		self.channelStatuses = {}
		self.channelStatusSymbols = {}
		self.channelStatusOrder = []
		self.channelModeTypes = {}
		self.userModes = ({}, {}, {}, {})
		self.userModeTypes = {}
		self.actions = {}
		self.storage = None
		self.storageSyncer = None
		self.dataCache = {}
		self.functionCache = {}
		
		self.serverID = None
		self.name = None
		self.isupport_tokens = {
			"CASEMAPPING": "strict-rfc1459",
			"CHANTYPES": "#",
		}
		self._uid = self._genUID()
		
		self.users = {}
		self.userNicks = CaseInsensitiveDictionary()
		self.channels = CaseInsensitiveDictionary(WeakValueDictionary)
		self.servers = {}
		self.serverNames = CaseInsensitiveDictionary()
		self.recentlyQuitUsers = {}
		self.recentlyQuitServers = {}
		self.recentlyDestroyedChannels = CaseInsensitiveDictionary()
		self.pruneRecentlyQuit = None
		self.pruneRecentChannels = None
		
		self._logFilter = LogLevelFilterPredicate()
		filterObserver = FilteringLogObserver(globalLogPublisher, (self._logFilter,))
		self.log = Logger("txircd", observer=filterObserver)
		
		self.startupTime = None
	
	def startService(self):
		self.log.info("Starting up...")
		self.startupTime = now()
		self.log.info("Loading configuration...")
		self.config.reload()
		self.name = self.config["server_name"]
		self.serverID = self.config["server_id"]
		self.log.info("Loading storage...")
		self.storage = shelve.open(self.config["datastore_path"], writeback=True)
		self.storageSyncer = LoopingCall(self.storage.sync)
		self.storageSyncer.start(self.config.get("storage_sync_interval", 5), now=False)
		self.log.info("Starting processes...")
		self.pruneRecentlyQuit = LoopingCall(self.pruneQuit)
		self.pruneRecentlyQuit.start(10, now=False)
		self.pruneRecentChannels = LoopingCall(self.pruneChannels)
		self.pruneRecentChannels.start(15, now=False)
		self.log.info("Loading modules...")
		self._loadModules()
		self.log.info("Binding ports...")
		self._bindPorts()
		self.log.info("txircd started!")
		try:
			self._logFilter.setLogLevelForNamespace("txircd", LogLevel.levelWithName(self.config["log_level"]))
		except (KeyError, InvalidLogLevelError):
			self._logFilter.setLogLevelForNamespace("txircd", LogLevel.warn)
		self.runActionStandard("startup")
	
	def stopService(self):
		stopDeferreds = []
		self.log.info("Disconnecting servers...")
		serverList = self.servers.values() # Take the list of server objects
		self.servers = {} # And then destroy the server dict to inhibit server objects generating lots of noise
		for server in serverList:
			if server.nextClosest == self.serverID:
				stopDeferreds.append(server.disconnectedDeferred)
				allUsers = self.users.keys()
				for user in allUsers:
					if user[:3] == server.serverID:
						del self.users[user]
				server.transport.loseConnection()
		self.log.info("Disconnecting users...")
		userList = self.users.values() # Basically do the same thing I just did with the servers
		self.users = {}
		for user in userList:
			if user.transport:
				stopDeferreds.append(user.disconnectedDeferred)
				user.transport.loseConnection()
		self.log.info("Unloading modules...")
		moduleList = self.loadedModules.keys()
		for module in moduleList:
			self._unloadModule(module, False) # Incomplete unload is done to save time and because side effects are destroyed anyway
#.........这里部分代码省略.........
开发者ID:ElementalAlchemist,项目名称:txircd,代码行数:103,代码来源:ircd.py

示例8: LogCapture

# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import info [as 别名]
app.state = "idle"
app.iterationsToGo = 0
app.snapshot = 'No Snapshot'
app.mainSockets = []
app.modelSockets = []
app.buildSockets = []
app.models = []
app.model = ""
app.accuracy_arr = []
app.train_err_arr = []

app.logvar = LogCapture(app)
# log.startLogging(sys.stdout) # Print to actual console
# globalLogBeginner.beginLoggingTo([app.logvar], redirectStandardIO=True)
# log.startLogging(app.logvar)
log.info("wow")




@gen.coroutine
def main():
	# http_server = tornado.httpserver.HTTPServer(app, ssl_options={
	# 	"certfile": "ssl\certificate.crt",
	# 	"keyfile": "ssl\privatekey.key",
	# })	
	# http_server.listen(443)
	app.listen(80)
	tornado.ioloop.IOLoop.current().spawn_callback(consumer)
	# future = futureCreator(consumer)
	# gen.with_timeout(time.time() + 100, future)
开发者ID:Healbadbad,项目名称:NeuralNetworkManager,代码行数:33,代码来源:NeuralManager.py

示例9: Logger

# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import info [as 别名]
from __future__ import print_function, absolute_import

from twisted.internet import reactor
from twisted.logger import Logger, globalLogPublisher

from cheeselib.logger import PrintingObserver
from cheeselib.server.rpc import CheeseRPCServerFactory, CheeseRPCServer
from cheeselib.server.storage.mongo import MongoDAO

SERVER_PORT = 18080

log = Logger()

globalLogPublisher.addObserver(PrintingObserver())

dao = MongoDAO()

rpc_server = CheeseRPCServer(dao).getStreamFactory(CheeseRPCServerFactory)

reactor.listenTCP(SERVER_PORT, rpc_server)
log.info("Starting server on port %d..." % SERVER_PORT)
reactor.run()
开发者ID:haf,项目名称:cheesepi,代码行数:24,代码来源:test_server.py

示例10: Discord

# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import info [as 别名]
class Discord(IRCClient):

	nickname = "discord"
	realname = "Discord"
	username = "discord"
	versionName = "Discord"
	versionNum = "0.01"

	magicFile = "true.txt"

	def __init__(self, accessList):
		self.logger = Logger(observer=textFileLogObserver(sys.stdout))

		self.accessList = [nick.lower() for nick in accessList]

		if not os.path.exists(self.magicFile):
			self.logger.info("Creating magic file")

			try:
				with open(self.magicFile, "a"):
					pass

			except Exception as ex:
				self.logger.error("Unable to create magic file! {0}".format(ex.message))
				reactor.stop()

		self.markovGenerator = pymarkov.MarkovChainGenerator(self.magicFile)

		self.channels = []
		self.channelPhrasers = {}

		self.logger.debug("Discord initialized")

		# Maybe add hook/plugin system here?

		self.commands = Commands.Commands(self)		

	def removeChannel(self, channel):
		try:
			self.channels.remove(channel)

			self.channelPhrasers[channel].stop()
			
			del self.channelPhrasers[channel]

		except:
			self.logger.error("Error removing {channel} from collection", channel=channel)

	def insertPhrase(self, phrase):
		try:
			with open(self.magicFile, "a") as magicFile:
				magicFile.write("{0}\n".format(phrase))

			try:
				file, ext = os.path.splitext(self.magicFile)
				os.remove("{0}-pickled{1}".format(file, ext))

				# Simply re-populating the dictionary isn't enough for some reason
				self.markovGenerator = pymarkov.MarkovChainGenerator(self.magicFile, 2)

			except IOError as ex:
				self.logger.error("Unable to delete pickled file. {0}".format(ex.message))			

		except Exception as ex:
			self.logger.error("Unable to insert phrase into magic file! {0}".format(ex.message))

	def kickedFrom(self, channel, kicker, message):
		self.removeChannel(channel)

		self.logger.info("Kicked from {channel} by {kicker}", channel=channel, kicker=kicker)

	def left(self, channel):
		self.removeChannel(channel)

		self.logger.info("Left {channel}", channel=channel)

	def handleMessage(self, user, channel, message):
		senderNickname = user.split("!")[0]

		if message.startswith("~reload") and senderNickname in self.accessList:
			self.logger.info("Reloading commands module")
			self.say(channel, "Reloading.")

			try:
				commandsModule = reload(Commands)
				self.commands = commandsModule.Commands(self)

			except Exception as ex:
				self.say(channel, "Failed to load commands module - {0}".format(ex.message))

		elif message.startswith("~"):
			# Don't log commands to the brain
			commandMessage = message[1:]

			self.commands.handleCommand(user, channel, commandMessage)

		else:
			self.logger.info("Adding {message!r} to brain", message=message)

			# Avoid storing anything with the bot's name in it
#.........这里部分代码省略.........
开发者ID:TunnelBlanket,项目名称:Discord,代码行数:103,代码来源:Discord.py

示例11: MyLogObserver

# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import info [as 别名]
# Logging services
#
@implementer(ILogObserver)
class MyLogObserver(object):
    def __call__(self, event):
        text = event['log_format'].format(**event)
        sys.stdout.write(text + '\n')
        sys.stdout.flush()

#globalLogBeginner.beginLoggingTo([textFileLogObserver(sys.stdout)])
#globalLogBeginner.beginLoggingTo([LegacySyslogObserver('telldus-logger')])
#globalLogBeginner.beginLoggingTo([MyLogObserver()])
globalLogPublisher.addObserver(MyLogObserver())

log = Logger()
log.info("Starting logging")



class GraphiteProtocol(Protocol):
    noisy = False

    def __init__(self, name, readings):
        self.msg = self.compile_msg(name, readings)
        log.info("Sending {n}: {v}", n=name, v=readings)


    def compile_msg(self, name, readings):

        # Some sensors have a tendency to glitch. So if the temp difference
        # from the last reading is >20 degrees, then this reading is a glitch
开发者ID:sveinse,项目名称:lumina,代码行数:33,代码来源:telldus-logger.py

示例12: Logger

# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import info [as 别名]
import sys

from twisted.internet import reactor, endpoints
from twisted.logger import Logger
from twisted.python import log
from twisted.web import server

from chat import NetCatChatFactory
from api import Root

# Configure logging to standard out.
logger = Logger()
log.startLogging(sys.stdout)

# Create an instance of the factories.
factory = NetCatChatFactory()
site = server.Site(Root(factory))

# Listen on TCP port 1400 for chat and port 8080 for the API.
endpoints.serverFromString(reactor, "tcp:1400").listen(factory)
endpoints.serverFromString(reactor, "tcp:8080").listen(site)

# Start listening for connections (and run the event-loop).
logger.info("Listening for netcat on port 1400")
logger.info("Listening for HTTP on port 8080")
reactor.run()

# Note that any code after this point will *not* be executed. reactor.run enters
# an infinite loop until shutdown.
开发者ID:percipient,项目名称:talks,代码行数:31,代码来源:runner.py

示例13: toggle_chat

# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import info [as 别名]
        """
        Показывает уведомление вверху экрана.
        """

        self.notifications_mgr.notify(text)

    def toggle_chat(self, button):
        self.chat.toggle()


class StdoutHook():
    """
    Дублирует stdout в окно чата.
    """

    def __init__(self, chat):
        self.ex_stdout = sys.stdout # in case there's already a hook installed by someone
        sys.stdout = self
        self.chat = chat

    def write(self, s):
        s = s.strip()
        if s:
            self.ex_stdout.write(s)
            self.chat.text += 'STDOUT> ' + s + '\n'


if __name__ == '__main__':
    log.info('Start client')
    TwistedClientApp().run()
开发者ID:Ecialo,项目名称:PyCard,代码行数:32,代码来源:client.py


注:本文中的twisted.logger.Logger.info方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。