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


Python Logger.error方法代码示例

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


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

示例1: LoggingProcessProtocol

# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import error [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

示例2: test_logger_namespace

# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import error [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

示例3: MFTests

# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import error [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

示例4: IRCd

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

#.........这里部分代码省略.........
			raise ConfigValidationError("server_ping_frequency", "invalid number")

		for module in self.loadedModules.itervalues():
			module.verifyConfig(config)

	def logConfigValidationWarning(self, key, message, default):
		self.log.warn("Config value \"{configKey}\" is invalid ({message}); the value has been set to a default of \"{default}\".", configKey=key, message=message, default=default)

	def rehash(self):
		"""
		Reloads the configuration file and applies changes.
		"""
		self.log.info("Rehashing...")
		self.config.reload()
		d = self._unbindPorts() # Unbind the ports that are bound
		if d: # And then bind the new ones
			DeferredList(d).addCallback(lambda result: self._bindPorts())
		else:
			self._bindPorts()
		
		try:
			self._logFilter.setLogLevelForNamespace("txircd", LogLevel.levelWithName(self.config["log_level"]))
		except (KeyError, InvalidLogLevelError):
			pass # If we can't set a new log level, we'll keep the old one
		
		for module in self.loadedModules.itervalues():
			module.rehash()
	
	def _bindPorts(self):
		for bindDesc in self.config["bind_client"]:
			try:
				endpoint = serverFromString(reactor, unescapeEndpointDescription(bindDesc))
			except ValueError as e:
				self.log.error(e)
				continue
			listenDeferred = endpoint.listen(UserFactory(self))
			listenDeferred.addCallback(self._savePort, bindDesc, "client")
			listenDeferred.addErrback(self._logNotBound, bindDesc)
		for bindDesc in self.config["bind_server"]:
			try:
				endpoint = serverFromString(reactor, unescapeEndpointDescription(bindDesc))
			except ValueError as e:
				self.log.error(e)
				continue
			listenDeferred = endpoint.listen(ServerListenFactory(self))
			listenDeferred.addCallback(self._savePort, bindDesc, "server")
			listenDeferred.addErrback(self._logNotBound, bindDesc)
	
	def _unbindPorts(self):
		deferreds = []
		for port in self.boundPorts.itervalues():
			d = port.stopListening()
			if d:
				deferreds.append(d)
		return deferreds
	
	def _savePort(self, port, desc, portType):
		self.boundPorts[desc] = port
		self.log.debug("Bound endpoint '{endpointDescription}' for {portType} connections.", endpointDescription=desc, portType=portType)
	
	def _logNotBound(self, err, desc):
		self.log.error("Could not bind '{endpointDescription}': {errorMsg}", endpointDescription=desc, errorMsg=err)
	
	def createUUID(self):
		"""
		Gets the next UUID for a new client.
开发者ID:ElementalAlchemist,项目名称:txircd,代码行数:70,代码来源:ircd.py

示例5: Rest

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

    def __init__(
            self,
            host='https://developer-api.nest.com',
            token=None,
            event_handler=None,
            net_type='lan'):
        self.log = Logger()
        self.host = host
        self.token = token
        self.event_handler = event_handler
        self.pool = HTTPConnectionPool(reactor, persistent=True)
        self.loc = None
        self.reconnect = False
        self.fail_count = 0
        if event_handler:
            self.reconnect = True
            d = self.request(headers={'User-Agent': ['onDemand Rest Client'],
                                      'Accept': ['text/event-stream']})
            d.addCallback(self.on_disconnect)

    def __getattr__(self, name):
        try:
            super(Rest, self).__getattr__(name)
        except AttributeError:
            return RestCall(self, name)

    def on_disconnect(self, reason):
        if not reason:
            reason = {'reason': 'no_message'}
        self.log.critical(
            'disconnected: {reason}', reason=reason['reason'])
        if self.fail_count > 10:
            self.log.error('Max error count reached, aborting connection')

        def test_connectivity(count):
            if self.fail_count == count:
                self.fail_count = 0

        self.fail_count += 1
        c = self.fail_count
        reactor.callLater(10, test_connectivity, c)  # @UndefinedVariable
        if self.reconnect:
            d = self.request(headers={'User-Agent': ['onDemand Rest Client'],
                                      'Accept': ['text/event-stream']})
            d.addCallback(self.on_disconnect)

    def request(self, method='GET',
                path='',
                headers={'User-Agent': ['onDemand/1.0 (Rest_Client)'],
                         'Accept': ['application/json']},
                body=None):

        data = None
        if self.loc:
            host = '/'.join((self.loc, path))
        else:
            host = '/'.join((self.host, path))
        if self.token:
            host += '?auth=' + self.token
        if body:
            headers.update({'Content-Type': ['application/json']})
            data = FileBodyProducer(StringIO(json.dumps(body)))
        agent = RedirectAgent(Agent(reactor, pool=self.pool))
        d = agent.request(method, host, Headers(headers), data)

        def cbFail(fail):

            if hasattr(fail.value, 'response'):
                if hasattr(fail.value.response, 'code'):
                    if fail.value.response.code == 307:
                        loc = fail.value.response.headers.getRawHeaders(
                            'location')
                        new = urlparse(loc[0])
                        newhost = '://'.join((new.scheme, new.netloc))
                        if newhost == self.host:
                            self.loc = None
                        else:
                            self.loc = newhost
                        self.log.debug('redirect: %s' % self.loc)
                        data = FileBodyProducer(StringIO(json.dumps(body)))
                        d = agent.request(
                            method, loc[0], Headers(headers), data)
                        d.addCallbacks(cbRequest, cbFail)
                        return d
                    elif fail.value.response.code == 404 and self.loc:
                        self.loc = None
                        host = '/'.join((self.host, path))
                        if self.token:
                            host += '?auth=' + self.token
                        d = self.request(method, host, Headers(headers), body)
                        d.addCallbacks(cbRequest, cbFail)
                        return d
                else:
                    print(dir(fail.value))
                    print(fail.value.message)
                    print(fail.value.args)

            self.log.error('unhandled failure: %s -- %s' % (
#.........这里部分代码省略.........
开发者ID:bverdu,项目名称:onDemand,代码行数:103,代码来源:rest.py

示例6: Controller

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

#.........这里部分代码省略.........
        if self.lan:
            t = task.LoopingCall(self.search_devices)
            t.start(15)
            self.log.debug('SSDP Service started')

    def resume(self):
        self.app_paused = False
        if not self.connected:
            if self.cloud:
                self.connector.connect(self.factory)
                self.log.debug('Cloud Service started')
            if self.lan:
                t = task.LoopingCall(self.search_devices)
                t.start(15)
                self.log.debug('SSDP Service started')

    def stopService(self):
        self.log.debug('Stopping controller service...')
        self.clean()
#         d.addCallback(lambda ignored: service.MultiService.stopService(self))
        service.MultiService.stopService(self)
#         reactor.callLater(10, reactor.stop)  # @UndefinedVariable

    def cloud_disconnected(self, reason):
        if not reason:
            reason = 'Unknown'
        self.log.warn('Cloud Server disconnected: %s' % reason)
        self.connected = False
        if not self.app_paused and self.fail_count < 10:
            self.fail_count += 1
            self.resume()

    def cloud_failed(self, failure):
        self.log.error('Cloud Login failed: %s' % str(failure))

#         self.xmlstream.sendFooter()

    def clean(self):
        return reactor.callInThread(  # @UndefinedVariable
            threads.blockingCallFromThread, *(reactor, self.cleanfunc))

    def cleanfunc(self):

        def cleaned(res):
            self.log.debug('cleaned')
            if self.cloud:
                self.xmlstream.sendFooter()
        dl = []
        if self.lan:
            for name in self.subscriptions.keys():
                dl.append(self.unsubscribe(name))
        if self.cloud:
            for name in self.subscriptions_cloud.keys():
                dl.append(self.unsubscribe(name))
        d = defer.DeferredList(dl)
        d.addCallback(cleaned)
        return d

    def cloud_connected(self, xs):
        self.log.debug('Cloud Connected')
        self.fail_count = 0
        self.connected = True
        self._services = {}
        self.subscriptions = {}
        self.xmlstream = xs
#         xs.rawDataInFn = self.rawDataIn
开发者ID:bverdu,项目名称:onDemand,代码行数:70,代码来源:controller.py

示例7: XmppEvent

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

    def __init__(self, nodeId, parent, pubsub_addr):
        self.log = Logger()
        self.nodeId = nodeId
        self.parent = parent
        self.addr = pubsub_addr

    def publish(self, event):

        if len(self.parent.active_controllers) == 0:
            #             self.log.debug('event cancelled')
            self.parent.registrations = []
            return

        def success(res):
            #             print('event sent')
            if res['type'] == 'error':
                self.log.error('Publish Event failed :%s' % res.toXml())
            else:
                if 'Id' in res.children[0].children[0]['node']:
                    self.log.debug('Event Published: %s' % res.toXml())
        name, data = event
        if name == 'Seconds':
            return
        iq = IQ(self.parent.xmlstream, 'set')
        ps = domish.Element(('http://jabber.org/protocol/pubsub', 'pubsub'))
        publish = domish.Element((None, 'publish'))
        publish['node'] = '/'.join((self.nodeId, name))
        item = domish.Element((None, 'item'))
        propertyset = domish.Element(
            ('urn:schemas-upnp-org:event-1-0', 'propertyset'),
            localPrefixes={'e': 'urn:schemas-upnp-org:event-1-0'})
        prop = domish.Element((None, 'e:property'))
        evt = domish.Element((None, name))
        if isinstance(data.value, dict):
            ev = domish.Element((data.namespace, 'Event'))
            inst = domish.Element((None, 'InstanceID'))
            inst['val'] = '0'
            for k, v in data.value.items:
                if 'namespace' in v:
                    var = domish.Element((v['namespace'], k))
                else:
                    var = domish.Element((None, k))
                if 'attrib' in v:
                    attr = v['attrib']
                else:
                    attr = {}
                value = v['value']
                if isinstance(value, bool):
                    value = int(value)
                attr.update(
                    {'val': str(value)
                     .decode('utf-8')})
                for attname, attval in attr:
                    var[attname] = attval
                inst.addChild(var)
            ev.addChild(inst)
            evt.addChild(ev)
        else:
            #             print(str(data.value).decode('utf-8'))
            if isinstance(data.value, bool):
                data.value = int(data.value)
            evt.addContent(str(data.value).decode('utf-8'))
        prop.addChild(evt)
        propertyset.addChild(prop)
        item.addChild(propertyset)
        publish.addChild(item)
        ps.addChild(publish)
        iq.addChild(ps)
        iq.addCallback(success)
        iq.send(to=self.addr)
开发者ID:lazytech-org,项目名称:onDemand,代码行数:74,代码来源:event.py

示例8: Discord

# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import error [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

示例9: MpdProtocol

# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import error [as 别名]
class MpdProtocol(LineReceiver):
    """
    Twisted protocol to control remote mpd server
    """

    def __init__(self):
        """
        doc
        """
        self.log = Logger()
        self.delimiter = "\n"
        self.deferreds = []
        self.buff = {}
        self.idle = False
        self.list_index = 0

    def connectionLost(self, reason):
        self.log.error("connection lost : {reason}", reason=reason)
        self._event({"changed": "disconnected"})
        self.idle = False
        try:
            d = self.deferreds.pop(0)
        except:
            pass
        else:
            d.errback(reason)

    def connectionMade(self):
        self.log.debug("connected")

    def addCallback(self, d):
        self.deferreds.append(d)

    def noidle(self):
        d = defer.Deferred()
        d.addCallback(lambda ignored: ignored)
        self.deferreds.insert(0, d)
        self.sendLine("noidle")
        self.idle = False

    #         print('noidle')

    def set_idle(self):
        self.sendLine("idle")
        self.idle = True

    #         print('idle')

    def lineReceived(self, line):
        #  print(line)
        if line.startswith("OK MPD"):
            self._event({"changed": "connected"})
        elif line.startswith("OK"):
            #             print('deferred length: %d' % len(self.deferreds))
            self.list_index = 1
            try:
                d = self.deferreds.pop(0)
            except:
                self.set_idle()
                self._event(self.buff)
                self.buff = {}
                return
            else:
                d.callback(self.buff)
            self.buff = {}
        elif line.startswith("ACK"):
            #             print('deferred length: %d' % len(self.deferreds))
            try:
                d = self.deferreds.pop(0)
            except:
                self.set_idle()
                self._event({"Error": line.split("}")[1]})
                self.buff = {}
                return
            else:
                d.errback(Exception(line.split("}")[1]))
            self.buff = {}
        else:
            if len(line) > 0:
                k = line.split(":")[0]
                if isinstance(self.buff, list):
                    if k in self.buff[self.list_index]:
                        self.list_index += 1
                        self.buff.append({})
                    self.buff[self.list_index].update({k: " ".join(line.split()[1:])})
                else:
                    if k in self.buff:
                        self.buff = [self.buff]
                        self.list_index = 1
                        self.buff.append({k: " ".join(line.split()[1:])})
                    #                         if str(self.list_index) + k in self.buff:
                    #                             self.list_index += 1
                    #                         self.buff.update(
                    #                             {str(self.list_index) + line.split(':')[0]:
                    #                              ' '.join(line.split()[1:])})
                    else:
                        self.buff.update({k: " ".join(line.split()[1:])})
            return
        if len(self.deferreds) == 0:
            self.set_idle()
开发者ID:bverdu,项目名称:onDemand,代码行数:102,代码来源:mpd.py

示例10: BaseProtocol

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

    def __init__(self, shorthand=True, callback=None, escaped=False,
                 error_callback=None):

        serialBytesProtocol.__init__(self)
        if callback:
            self.callbacks = [callback]
        else:
            self.callbacks = []
        self.setRawMode()
        self.shorthand = shorthand
        self._escaped = escaped
        self.log = Logger()
        self.requests = {}
        self.command_id = 0
        self.buffer = None
#         self.reading = False

    def get_id(self):
        try:
            self.command_id += 1
            return intToByte(self.command_id)
        except ValueError:
            self.command_id = 1
            return intToByte(1)

    def connect(self, f):
        if f.callback:
            self.callbacks.append(f.callback)
        f.proto = self

    def rawDataReceived(self, data):
        for byte in data:
            if self.buffer:
                self.buffer.fill(byte)
                if self.buffer.remaining_bytes() == 0:
                    try:
                        # Try to parse and return result
                        self.buffer.parse()
                        # Ignore empty frames
                        if len(self.buffer.data) == 0:
                            self.buffer = None

                    except ValueError:
                        # Bad frame, so restart
                        self.log.warn('Bad frame: %r'
                                      % self.buffer.raw_data)

                    else:
                        self.read_frame(self.buffer.data)
                    self.buffer = None
#                     self.reading = False
            else:
                if byte == Frame.START_BYTE:
                    #                     self.reading == True
                    self.buffer = Frame(escaped=self._escaped)

    def read_frame(self, frame):
        """
        read_frame: binary data -> {'id':str,
                                         'param':binary data,
                                         ...}
        read_frame takes a data packet received from an XBee device
        and converts it into a dictionary. This dictionary provides
        names for each segment of binary data as specified in the
        api_responses spec.
        """
        # Fetch the first byte, identify the packet
        # If the spec doesn't exist, raise exception
        packet_id = frame[0:1]
        try:
            name = self.api_responses[packet_id]
        except AttributeError:
            raise NotImplementedError(
                "API response specifications could not be found; " +
                "use a derived class which defines 'api_responses'.")
        except KeyError:
            # Check to see if this ID can be found among transmittible packets
            for cmd_name, cmd in list(self.api_frames.items()):
                if cmd['id']['default'] == packet_id:
                    msg = "Incoming frame with id {packet_id} looks like a " +\
                        "command frame of type '{cmd_name}' (these should " +\
                        " not be received). Are you sure your devices " +\
                        "are in API mode?"
                    self.log.error(
                        msg, packet_id=bytes(frame), cmd_name=cmd_name)
                    return

            self.log.error("Unrecognized response packet with id byte {f}",
                           f=frame[0])
            return

        # Current byte index in the data stream
        packet = self.api_frames[name]
        index = 0
        callback = False

        # Result info
        info = {'id': name}
#.........这里部分代码省略.........
开发者ID:bverdu,项目名称:onDemand,代码行数:103,代码来源:base.py


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