Logging no longer uses root logger.

Each module should now log into its own logger.
This commit is contained in:
Lance Stout 2010-11-06 01:28:59 -04:00
parent d0c506f930
commit 4fb77ac878
22 changed files with 342 additions and 272 deletions

View File

@ -26,6 +26,9 @@ from sleekxmpp.xmlstream.matcher import *
from sleekxmpp.xmlstream.handler import *
log = logging.getLogger(__name__)
# Flag indicating if DNS SRV records are available for use.
SRV_SUPPORT = True
try:
@ -192,9 +195,9 @@ class BaseXMPP(XMLStream):
xep = "(XEP-%s) " % self.plugin[plugin].xep
desc = (xep, self.plugin[plugin].description)
logging.debug("Loaded Plugin %s%s" % desc)
log.debug("Loaded Plugin %s%s" % desc)
except:
logging.exception("Unable to load plugin: %s", plugin)
log.exception("Unable to load plugin: %s", plugin)
def register_plugins(self):
"""
@ -228,7 +231,7 @@ class BaseXMPP(XMLStream):
if key in self.plugin:
return self.plugin[key]
else:
logging.warning("""Plugin "%s" is not loaded.""" % key)
log.warning("""Plugin "%s" is not loaded.""" % key)
return False
def get(self, key, default):
@ -446,12 +449,12 @@ class BaseXMPP(XMLStream):
"""
Attribute accessor for bare jid
"""
logging.warning("jid property deprecated. Use boundjid.bare")
log.warning("jid property deprecated. Use boundjid.bare")
return self.boundjid.bare
@jid.setter
def jid(self, value):
logging.warning("jid property deprecated. Use boundjid.bare")
log.warning("jid property deprecated. Use boundjid.bare")
self.boundjid.bare = value
@property
@ -459,12 +462,12 @@ class BaseXMPP(XMLStream):
"""
Attribute accessor for full jid
"""
logging.warning("fulljid property deprecated. Use boundjid.full")
log.warning("fulljid property deprecated. Use boundjid.full")
return self.boundjid.full
@fulljid.setter
def fulljid(self, value):
logging.warning("fulljid property deprecated. Use boundjid.full")
log.warning("fulljid property deprecated. Use boundjid.full")
self.boundjid.full = value
@property
@ -472,12 +475,12 @@ class BaseXMPP(XMLStream):
"""
Attribute accessor for jid resource
"""
logging.warning("resource property deprecated. Use boundjid.resource")
log.warning("resource property deprecated. Use boundjid.resource")
return self.boundjid.resource
@resource.setter
def resource(self, value):
logging.warning("fulljid property deprecated. Use boundjid.full")
log.warning("fulljid property deprecated. Use boundjid.full")
self.boundjid.resource = value
@property
@ -485,12 +488,12 @@ class BaseXMPP(XMLStream):
"""
Attribute accessor for jid usernode
"""
logging.warning("username property deprecated. Use boundjid.user")
log.warning("username property deprecated. Use boundjid.user")
return self.boundjid.user
@username.setter
def username(self, value):
logging.warning("username property deprecated. Use boundjid.user")
log.warning("username property deprecated. Use boundjid.user")
self.boundjid.user = value
@property
@ -498,17 +501,17 @@ class BaseXMPP(XMLStream):
"""
Attribute accessor for jid host
"""
logging.warning("server property deprecated. Use boundjid.host")
log.warning("server property deprecated. Use boundjid.host")
return self.boundjid.server
@server.setter
def server(self, value):
logging.warning("server property deprecated. Use boundjid.host")
log.warning("server property deprecated. Use boundjid.host")
self.boundjid.server = value
def set_jid(self, jid):
"""Rip a JID apart and claim it as our own."""
logging.debug("setting jid to %s" % jid)
log.debug("setting jid to %s" % jid)
self.boundjid.full = jid
def getjidresource(self, fulljid):
@ -588,7 +591,7 @@ class BaseXMPP(XMLStream):
# disconnects. Determine if this was the last connection
# for the JID.
if show == 'unavailable':
logging.debug("%s %s got offline" % (jid, resource))
log.debug("%s %s got offline" % (jid, resource))
del connections[resource]
if not connections and not self.roster[jid]['in_roster']:
@ -604,7 +607,7 @@ class BaseXMPP(XMLStream):
self.event("changed_status", presence)
if got_online:
self.event("got_online", presence)
logging.debug("STATUS: %s%s/%s[%s]: %s" % (name, jid, resource,
log.debug("STATUS: %s%s/%s[%s]: %s" % (name, jid, resource,
show, status))
def _handle_subscribe(self, presence):

View File

@ -32,6 +32,9 @@ except:
SRV_SUPPORT = False
log = logging.getLogger(__name__)
class ClientXMPP(BaseXMPP):
"""
@ -133,7 +136,7 @@ class ClientXMPP(BaseXMPP):
def _session_timeout_check(self):
if not self.session_started_event.isSet():
logging.debug("Session start has taken more than 15 seconds")
log.debug("Session start has taken more than 15 seconds")
self.disconnect(reconnect=self.auto_reconnect)
def connect(self, address=tuple()):
@ -150,19 +153,19 @@ class ClientXMPP(BaseXMPP):
self.session_started_event.clear()
if not address or len(address) < 2:
if not self.srv_support:
logging.debug("Did not supply (address, port) to connect" + \
log.debug("Did not supply (address, port) to connect" + \
" to and no SRV support is installed" + \
" (http://www.dnspython.org)." + \
" Continuing to attempt connection, using" + \
" server hostname from JID.")
else:
logging.debug("Since no address is supplied," + \
log.debug("Since no address is supplied," + \
"attempting SRV lookup.")
try:
xmpp_srv = "_xmpp-client._tcp.%s" % self.server
answers = dns.resolver.query(xmpp_srv, dns.rdatatype.SRV)
except dns.resolver.NXDOMAIN:
logging.debug("No appropriate SRV record found." + \
log.debug("No appropriate SRV record found." + \
" Using JID server name.")
else:
# Pick a random server, weighted by priority.
@ -276,7 +279,7 @@ class ClientXMPP(BaseXMPP):
self.send_xml(xml)
return True
else:
logging.warning("The module tlslite is required to log in" +\
log.warning("The module tlslite is required to log in" +\
" to some servers, and has not been found.")
return False
@ -286,7 +289,7 @@ class ClientXMPP(BaseXMPP):
Restarts the stream.
"""
logging.debug("Starting TLS")
log.debug("Starting TLS")
if self.start_tls():
raise RestartStream()
@ -300,7 +303,7 @@ class ClientXMPP(BaseXMPP):
if '{urn:ietf:params:xml:ns:xmpp-tls}starttls' in self.features:
return False
logging.debug("Starting SASL Auth")
log.debug("Starting SASL Auth")
sasl_ns = 'urn:ietf:params:xml:ns:xmpp-sasl'
self.add_handler("<success xmlns='%s' />" % sasl_ns,
self._handle_auth_success,
@ -334,7 +337,7 @@ class ClientXMPP(BaseXMPP):
sasl_ns,
'ANONYMOUS'))
else:
logging.error("No appropriate login method.")
log.error("No appropriate login method.")
self.disconnect()
return True
@ -356,7 +359,7 @@ class ClientXMPP(BaseXMPP):
Arguments:
xml -- The SASL authentication failure element.
"""
logging.info("Authentication failed.")
log.info("Authentication failed.")
self.event("failed_auth", direct=True)
self.disconnect()
@ -367,7 +370,7 @@ class ClientXMPP(BaseXMPP):
Arguments:
xml -- The bind feature element.
"""
logging.debug("Requesting resource: %s" % self.boundjid.resource)
log.debug("Requesting resource: %s" % self.boundjid.resource)
xml.clear()
iq = self.Iq(stype='set')
if self.boundjid.resource:
@ -381,10 +384,10 @@ class ClientXMPP(BaseXMPP):
self.set_jid(response.xml.find('{%s}bind/{%s}jid' % (bind_ns,
bind_ns)).text)
self.bound = True
logging.info("Node set to: %s" % self.boundjid.fulljid)
log.info("Node set to: %s" % self.boundjid.fulljid)
session_ns = 'urn:ietf:params:xml:ns:xmpp-session'
if "{%s}session" % session_ns not in self.features or self.bindfail:
logging.debug("Established Session")
log.debug("Established Session")
self.sessionstarted = True
self.session_started_event.set()
self.event("session_start")
@ -399,7 +402,7 @@ class ClientXMPP(BaseXMPP):
if self.authenticated and self.bound:
iq = self.makeIqSet(xml)
response = iq.send()
logging.debug("Established Session")
log.debug("Established Session")
self.sessionstarted = True
self.session_started_event.set()
self.event("session_start")

View File

@ -22,6 +22,9 @@ from sleekxmpp.xmlstream.matcher import *
from sleekxmpp.xmlstream.handler import *
log = logging.getLogger(__name__)
class ComponentXMPP(BaseXMPP):
"""
@ -82,7 +85,7 @@ class ComponentXMPP(BaseXMPP):
Overrides XMLStream.connect.
"""
logging.debug("Connecting to %s:%s" % (self.server_host,
log.debug("Connecting to %s:%s" % (self.server_host,
self.server_port))
return XMLStream.connect(self, self.server_host,
self.server_port)

View File

@ -14,6 +14,9 @@ from .. xmlstream.stanzabase import registerStanzaPlugin, ElementBase, ET, JID
from .. stanza.iq import Iq
log = logging.getLogger(__name__)
class GmailQuery(ElementBase):
namespace = 'google:mail:notify'
name = 'query'
@ -118,12 +121,12 @@ class gmail_notify(base.base_plugin):
def handle_gmail(self, iq):
mailbox = iq['mailbox']
approx = ' approximately' if mailbox['estimated'] else ''
logging.info('Gmail: Received%s %s emails' % (approx, mailbox['total-matched']))
log.info('Gmail: Received%s %s emails' % (approx, mailbox['total-matched']))
self.last_result_time = mailbox['result-time']
self.xmpp.event('gmail_messages', iq)
def handle_new_mail(self, iq):
logging.info("Gmail: New emails received!")
log.info("Gmail: New emails received!")
self.xmpp.event('gmail_notify')
self.checkEmail()
@ -135,9 +138,9 @@ class gmail_notify(base.base_plugin):
def search(self, query=None, newer=None):
if query is None:
logging.info("Gmail: Checking for new emails")
log.info("Gmail: Checking for new emails")
else:
logging.info('Gmail: Searching for emails matching: "%s"' % query)
log.info('Gmail: Searching for emails matching: "%s"' % query)
iq = self.xmpp.Iq()
iq['type'] = 'get'
iq['to'] = self.xmpp.jid

View File

@ -3,6 +3,10 @@ import logging
from xml.etree import cElementTree as ET
import types
log = logging.getLogger(__name__)
class jobs(base.base_plugin):
def plugin_init(self):
self.xep = 'pubsubjob'
@ -40,7 +44,7 @@ class jobs(base.base_plugin):
iq['psstate']['payload'] = state
result = iq.send()
if result is None or type(result) == types.BooleanType or result['type'] != 'result':
logging.error("Unable to change %s:%s to %s" % (node, jobid, state))
log.error("Unable to change %s:%s to %s" % (node, jobid, state))
return False
return True

View File

@ -6,12 +6,16 @@
See the file LICENSE for copying permission.
"""
from . import base
import logging
import log
from xml.etree import cElementTree as ET
import copy
import logging
#TODO support item groups and results
log = logging.getLogger(__name__)
class old_0004(base.base_plugin):
def plugin_init(self):
@ -22,7 +26,7 @@ class old_0004(base.base_plugin):
def post_init(self):
base.base_plugin.post_init(self)
self.xmpp.plugin['xep_0030'].add_feature('jabber:x:data')
logging.warning("This implementation of XEP-0004 is deprecated.")
log.warning("This implementation of XEP-0004 is deprecated.")
def handler_message_xform(self, xml):
object = self.handle_form(xml)

View File

@ -16,6 +16,9 @@ from .. stanza.message import Message
import types
log = logging.getLogger(__name__)
class Form(ElementBase):
namespace = 'jabber:x:data'
name = 'x'
@ -55,11 +58,11 @@ class Form(ElementBase):
return field
def getXML(self, type='submit'):
logging.warning("Form.getXML() is deprecated API compatibility with plugins/old_0004.py")
log.warning("Form.getXML() is deprecated API compatibility with plugins/old_0004.py")
return self.xml
def fromXML(self, xml):
logging.warning("Form.fromXML() is deprecated API compatibility with plugins/old_0004.py")
log.warning("Form.fromXML() is deprecated API compatibility with plugins/old_0004.py")
n = Form(xml=xml)
return n

View File

@ -16,6 +16,9 @@ from .. xmlstream.matcher.xpath import MatchXPath
from .. xmlstream import ElementBase, ET, JID, register_stanza_plugin
log = logging.getLogger(__name__)
class LastActivity(ElementBase):
name = 'query'
namespace = 'jabber:iq:last'
@ -68,10 +71,10 @@ class xep_0012(base.base_plugin):
def handle_last_activity_query(self, iq):
if iq['type'] == 'get':
logging.debug("Last activity requested by %s" % iq['from'])
log.debug("Last activity requested by %s" % iq['from'])
self.xmpp.event('last_activity_request', iq)
elif iq['type'] == 'result':
logging.debug("Last activity result from %s" % iq['from'])
log.debug("Last activity result from %s" % iq['from'])
self.xmpp.event('last_activity', iq)
def handle_last_activity(self, iq):

View File

@ -13,6 +13,10 @@ from .. xmlstream.matcher.xpath import MatchXPath
from .. xmlstream.stanzabase import registerStanzaPlugin, ElementBase, ET, JID
from .. stanza.iq import Iq
log = logging.getLogger(__name__)
class DiscoInfo(ElementBase):
namespace = 'http://jabber.org/protocol/disco#info'
name = 'query'
@ -222,18 +226,18 @@ class xep_0030(base.base_plugin):
def handle_item_query(self, iq):
if iq['type'] == 'get':
logging.debug("Items requested by %s" % iq['from'])
log.debug("Items requested by %s" % iq['from'])
self.xmpp.event('disco_items_request', iq)
elif iq['type'] == 'result':
logging.debug("Items result from %s" % iq['from'])
log.debug("Items result from %s" % iq['from'])
self.xmpp.event('disco_items', iq)
def handle_info_query(self, iq):
if iq['type'] == 'get':
logging.debug("Info requested by %s" % iq['from'])
log.debug("Info requested by %s" % iq['from'])
self.xmpp.event('disco_info_request', iq)
elif iq['type'] == 'result':
logging.debug("Info result from %s" % iq['from'])
log.debug("Info result from %s" % iq['from'])
self.xmpp.event('disco_info', iq)
def handle_disco_info(self, iq, forwarded=False):
@ -248,13 +252,13 @@ class xep_0030(base.base_plugin):
if not node_name:
node_name = 'main'
logging.debug("Using default handler for disco#info on node '%s'." % node_name)
log.debug("Using default handler for disco#info on node '%s'." % node_name)
if node_name in self.nodes:
node = self.nodes[node_name]
iq.reply().setPayload(node.info.xml).send()
else:
logging.debug("Node %s requested, but does not exist." % node_name)
log.debug("Node %s requested, but does not exist." % node_name)
iq.reply().error().setPayload(iq['disco_info'].xml)
iq['error']['code'] = '404'
iq['error']['type'] = 'cancel'
@ -276,13 +280,13 @@ class xep_0030(base.base_plugin):
if not node_name:
node_name = 'main'
logging.debug("Using default handler for disco#items on node '%s'." % node_name)
log.debug("Using default handler for disco#items on node '%s'." % node_name)
if node_name in self.nodes:
node = self.nodes[node_name]
iq.reply().setPayload(node.items.xml).send()
else:
logging.debug("Node %s requested, but does not exist." % node_name)
log.debug("Node %s requested, but does not exist." % node_name)
iq.reply().error().setPayload(iq['disco_items'].xml)
iq['error']['code'] = '404'
iq['error']['type'] = 'cancel'

View File

@ -15,6 +15,10 @@ from .. xmlstream.handler.callback import Callback
from .. xmlstream.matcher.xpath import MatchXPath
from .. xmlstream.matcher.xmlmask import MatchXMLMask
log = logging.getLogger(__name__)
class MUCPresence(ElementBase):
name = 'x'
namespace = 'http://jabber.org/protocol/muc#user'
@ -87,19 +91,19 @@ class MUCPresence(ElementBase):
return self.parent()['from'].bare
def setNick(self, value):
logging.warning("Cannot set nick through mucpresence plugin.")
log.warning("Cannot set nick through mucpresence plugin.")
return self
def setRoom(self, value):
logging.warning("Cannot set room through mucpresence plugin.")
log.warning("Cannot set room through mucpresence plugin.")
return self
def delNick(self):
logging.warning("Cannot delete nick through mucpresence plugin.")
log.warning("Cannot delete nick through mucpresence plugin.")
return self
def delRoom(self):
logging.warning("Cannot delete room through mucpresence plugin.")
log.warning("Cannot delete room through mucpresence plugin.")
return self
class xep_0045(base.base_plugin):
@ -135,7 +139,7 @@ class xep_0045(base.base_plugin):
if entry['nick'] not in self.rooms[entry['room']]:
got_online = True
self.rooms[entry['room']][entry['nick']] = entry
logging.debug("MUC presence from %s/%s : %s" % (entry['room'],entry['nick'], entry))
log.debug("MUC presence from %s/%s : %s" % (entry['room'],entry['nick'], entry))
self.xmpp.event("groupchat_presence", pr)
self.xmpp.event("muc::%s::presence" % entry['room'], pr)
if got_offline:

View File

@ -6,6 +6,10 @@ from .. xmlstream.stanzabase import registerStanzaPlugin, ElementBase, ET
from . import stanza_pubsub
from . xep_0004 import Form
log = logging.getLogger(__name__)
class xep_0060(base.base_plugin):
"""
XEP-0060 Publish Subscribe
@ -110,14 +114,14 @@ class xep_0060(base.base_plugin):
#self.xmpp.add_handler("<iq id='%s'/>" % id, self.handlerCreateNodeResponse)
result = iq.send()
if result is None or result == False or result['type'] == 'error':
logging.warning("got error instead of config")
log.warning("got error instead of config")
return False
if node is not None:
form = result.find('{http://jabber.org/protocol/pubsub#owner}pubsub/{http://jabber.org/protocol/pubsub#owner}configure/{jabber:x:data}x')
else:
form = result.find('{http://jabber.org/protocol/pubsub#owner}pubsub/{http://jabber.org/protocol/pubsub#owner}default/{jabber:x:data}x')
if not form or form is None:
logging.error("No form found.")
log.error("No form found.")
return False
return Form(xml=form)
@ -133,7 +137,7 @@ class xep_0060(base.base_plugin):
id = iq['id']
result = iq.send()
if result is None or result == False or result['type'] == 'error':
logging.warning("got error instead of config")
log.warning("got error instead of config")
return False
else:
results = result.findall('{http://jabber.org/protocol/pubsub#owner}pubsub/{http://jabber.org/protocol/pubsub#owner}subscriptions/{http://jabber.org/protocol/pubsub#owner}subscription')
@ -156,7 +160,7 @@ class xep_0060(base.base_plugin):
id = iq['id']
result = iq.send()
if result is None or result == False or result['type'] == 'error':
logging.warning("got error instead of config")
log.warning("got error instead of config")
return False
else:
results = result.findall('{http://jabber.org/protocol/pubsub#owner}pubsub/{http://jabber.org/protocol/pubsub#owner}affiliations/{http://jabber.org/protocol/pubsub#owner}affiliation')
@ -264,7 +268,7 @@ class xep_0060(base.base_plugin):
try:
config.field['pubsub#collection'].setValue(parent)
except KeyError:
logging.warning("pubsub#collection doesn't exist in config, trying to add it")
log.warning("pubsub#collection doesn't exist in config, trying to add it")
config.addField('pubsub#collection', value=parent)
if not self.setNodeConfig(jid, child, config):
return False
@ -298,7 +302,7 @@ class xep_0060(base.base_plugin):
try:
config.field['pubsub#collection'].setValue(parent)
except KeyError:
logging.warning("pubsub#collection doesn't exist in config, trying to add it")
log.warning("pubsub#collection doesn't exist in config, trying to add it")
config.addField('pubsub#collection', value=parent)
if not self.setNodeConfig(jid, child, config):
return False

View File

@ -12,6 +12,9 @@ import hashlib
from . import base
log = logging.getLogger(__name__)
class xep_0078(base.base_plugin):
"""
XEP-0078 NON-SASL Authentication
@ -30,7 +33,7 @@ class xep_0078(base.base_plugin):
self.auth()
def auth(self, xml=None):
logging.debug("Starting jabber:iq:auth Authentication")
log.debug("Starting jabber:iq:auth Authentication")
auth_request = self.xmpp.makeIqGet()
auth_request_query = ET.Element('{jabber:iq:auth}query')
auth_request.attrib['to'] = self.xmpp.server
@ -47,12 +50,12 @@ class xep_0078(base.base_plugin):
query.append(username)
query.append(resource)
if rquery.find('{jabber:iq:auth}digest') is None:
logging.warning("Authenticating via jabber:iq:auth Plain.")
log.warning("Authenticating via jabber:iq:auth Plain.")
password = ET.Element('password')
password.text = self.xmpp.password
query.append(password)
else:
logging.debug("Authenticating via jabber:iq:auth Digest")
log.debug("Authenticating via jabber:iq:auth Digest")
digest = ET.Element('digest')
digest.text = hashlib.sha1(b"%s%s" % (self.streamid, self.xmpp.password)).hexdigest()
query.append(digest)
@ -64,6 +67,6 @@ class xep_0078(base.base_plugin):
self.xmpp.sessionstarted = True
self.xmpp.event("session_start")
else:
logging.info("Authentication failed")
log.info("Authentication failed")
self.xmpp.disconnect()
self.xmpp.event("failed_auth")

View File

@ -14,6 +14,9 @@ from .. xmlstream.stanzabase import registerStanzaPlugin, ElementBase, ET, JID
from .. stanza.message import Message
log = logging.getLogger(__name__)
class ChatState(ElementBase):
namespace = 'http://jabber.org/protocol/chatstates'
plugin_attrib = 'chat_state'
@ -97,5 +100,5 @@ class xep_0085(base.base_plugin):
def _handleChatState(self, msg):
state = msg['chat_state'].name
logging.debug("Chat State: %s, %s" % (state, msg['from'].jid))
log.debug("Chat State: %s, %s" % (state, msg['from'].jid))
self.xmpp.event('chatstate_%s' % state, msg)

View File

@ -10,6 +10,10 @@ from . import base
import time
import logging
log = logging.getLogger(__name__)
class xep_0199(base.base_plugin):
"""XEP-0199 XMPP Ping"""
@ -30,7 +34,7 @@ class xep_0199(base.base_plugin):
time.sleep(self.config.get('frequency', 300))
while self.sendPing(self.xmpp.server, self.config.get('timeout', 30)) is not False:
time.sleep(self.config.get('frequency', 300))
logging.debug("Did not recieve ping back in time. Requesting Reconnect.")
log.debug("Did not recieve ping back in time. Requesting Reconnect.")
self.xmpp.disconnect(reconnect=True)
def handler_ping(self, xml):

View File

@ -17,6 +17,9 @@ from .. xmlstream.matcher.xpath import MatchXPath
from .. xmlstream import ElementBase, ET, JID, register_stanza_plugin
log = logging.getLogger(__name__)
class EntityTime(ElementBase):
name = 'time'
namespace = 'urn:xmpp:time'
@ -84,10 +87,10 @@ class xep_0202(base.base_plugin):
def handle_entity_time_query(self, iq):
if iq['type'] == 'get':
logging.debug("Entity time requested by %s" % iq['from'])
log.debug("Entity time requested by %s" % iq['from'])
self.xmpp.event('entity_time_request', iq)
elif iq['type'] == 'result':
logging.debug("Entity time result from %s" % iq['from'])
log.debug("Entity time result from %s" % iq['from'])
self.xmpp.event('entity_time', iq)
def handle_entity_time(self, iq):

View File

@ -15,6 +15,9 @@ from sleekxmpp.stanza import Error
from sleekxmpp.xmlstream import ET, StanzaBase, register_stanza_plugin
log = logging.getLogger(__name__)
class RootStanza(StanzaBase):
"""
@ -58,7 +61,7 @@ class RootStanza(StanzaBase):
self['error']['text'] = "SleekXMPP got into trouble."
else:
self['error']['text'] = traceback.format_tb(e.__traceback__)
logging.exception('Error handling {%s}%s stanza' %
log.exception('Error handling {%s}%s stanza' %
(self.namespace, self.name))
self.send()

View File

@ -86,7 +86,7 @@ class StateMachine(object):
while not self.lock.acquire(False):
time.sleep(.001)
if (start + wait - time.time()) <= 0.0:
logging.debug("Could not acquire lock")
log.debug("Could not acquire lock")
return False
while not self.__current_state in from_states:
@ -95,7 +95,7 @@ class StateMachine(object):
if remainder > 0:
self.notifier.wait(remainder)
else:
logging.debug("State was not ready")
log.debug("State was not ready")
self.lock.release()
return False

View File

@ -16,6 +16,9 @@ from sleekxmpp.xmlstream import StanzaBase, RESPONSE_TIMEOUT
from sleekxmpp.xmlstream.handler.base import BaseHandler
log = logging.getLogger(__name__)
class Waiter(BaseHandler):
"""
@ -85,7 +88,7 @@ class Waiter(BaseHandler):
stanza = self._payload.get(True, timeout)
except queue.Empty:
stanza = False
logging.warning("Timed out waiting for %s" % self.name)
log.warning("Timed out waiting for %s" % self.name)
self.stream.removeHandler(self.name)
return stanza

View File

@ -6,6 +6,8 @@
See the file LICENSE for copying permission.
"""
import logging
from xml.parsers.expat import ExpatError
from sleekxmpp.xmlstream.stanzabase import ET
@ -18,6 +20,9 @@ from sleekxmpp.xmlstream.matcher.base import MatcherBase
IGNORE_NS = False
log = logging.getLogger(__name__)
class MatchXMLMask(MatcherBase):
"""
@ -97,8 +102,7 @@ class MatchXMLMask(MatcherBase):
try:
mask = ET.fromstring(mask)
except ExpatError:
logging.log(logging.WARNING,
"Expat error: %s\nIn parsing: %s" % ('', mask))
log.warning("Expat error: %s\nIn parsing: %s" % ('', mask))
if not use_ns:
# Compare the element without using namespaces.

View File

@ -15,6 +15,9 @@ except ImportError:
import Queue as queue
log = logging.getLogger(__name__)
class Task(object):
"""
@ -168,13 +171,13 @@ class Scheduler(object):
except KeyboardInterrupt:
self.run = False
if self.parentstop is not None:
logging.debug("stopping parent")
log.debug("stopping parent")
self.parentstop.set()
except SystemExit:
self.run = False
if self.parentstop is not None:
self.parentstop.set()
logging.debug("Quitting Scheduler thread")
log.debug("Quitting Scheduler thread")
if self.parentqueue is not None:
self.parentqueue.put(('quit', None, None))

View File

@ -16,6 +16,9 @@ from sleekxmpp.xmlstream import JID
from sleekxmpp.xmlstream.tostring import tostring
log = logging.getLogger(__name__)
# Used to check if an argument is an XML object.
XML_TYPE = type(ET.Element('xml'))
@ -1140,7 +1143,7 @@ class StanzaBase(ElementBase):
Meant to be overridden.
"""
logging.exception('Error handling {%s}%s stanza' % (self.namespace,
log.exception('Error handling {%s}%s stanza' % (self.namespace,
self.name))
def send(self):

View File

@ -44,6 +44,9 @@ HANDLER_THREADS = 1
SSL_SUPPORT = True
log = logging.getLogger(__name__)
class RestartStream(Exception):
"""
Exception to restart stream processing, including
@ -206,7 +209,7 @@ class XMLStream(object):
# Used in Windows
signal.signal(signal.SIGTERM, self._handle_kill)
except:
logging.debug("Can not set interrupt signal handlers. " + \
log.debug("Can not set interrupt signal handlers. " + \
"SleekXMPP is not running from a main thread.")
def _handle_kill(self, signum, frame):
@ -275,7 +278,7 @@ class XMLStream(object):
self.socket = self.socket_class(Socket.AF_INET, Socket.SOCK_STREAM)
self.socket.settimeout(None)
if self.use_ssl and self.ssl_support:
logging.debug("Socket Wrapped for SSL")
log.debug("Socket Wrapped for SSL")
ssl_socket = ssl.wrap_socket(self.socket)
if hasattr(self.socket, 'socket'):
# We are using a testing socket, so preserve the top
@ -285,7 +288,7 @@ class XMLStream(object):
self.socket = ssl_socket
try:
logging.debug("Connecting to %s:%s" % self.address)
log.debug("Connecting to %s:%s" % self.address)
self.socket.connect(self.address)
self.set_socket(self.socket, ignore=True)
#this event is where you should set your application state
@ -293,7 +296,7 @@ class XMLStream(object):
return True
except Socket.error as serr:
error_msg = "Could not connect to %s:%s. Socket Error #%s: %s"
logging.error(error_msg % (self.address[0], self.address[1],
log.error(error_msg % (self.address[0], self.address[1],
serr.errno, serr.strerror))
time.sleep(1)
return False
@ -338,10 +341,10 @@ class XMLStream(object):
"""
Reset the stream's state and reconnect to the server.
"""
logging.debug("reconnecting...")
log.debug("reconnecting...")
self.state.transition('connected', 'disconnected', wait=2.0,
func=self._disconnect, args=(True,))
logging.debug("connecting...")
log.debug("connecting...")
return self.state.transition('disconnected', 'connected',
wait=2.0, func=self._connect)
@ -378,8 +381,8 @@ class XMLStream(object):
to be restarted.
"""
if self.ssl_support:
logging.info("Negotiating TLS")
logging.info("Using SSL version: %s" % str(self.ssl_version))
log.info("Negotiating TLS")
log.info("Using SSL version: %s" % str(self.ssl_version))
ssl_socket = ssl.wrap_socket(self.socket,
ssl_version=self.ssl_version,
do_handshake_on_connect=False)
@ -393,7 +396,7 @@ class XMLStream(object):
self.set_socket(self.socket)
return True
else:
logging.warning("Tried to enable TLS, but ssl module not found.")
log.warning("Tried to enable TLS, but ssl module not found.")
return False
def start_stream_handler(self, xml):
@ -557,7 +560,7 @@ class XMLStream(object):
handler[0](copy.copy(data))
except Exception as e:
error_msg = 'Error processing event handler: %s'
logging.exception(error_msg % str(handler[0]))
log.exception(error_msg % str(handler[0]))
if hasattr(data, 'exception'):
data.exception(e)
else:
@ -622,7 +625,7 @@ class XMLStream(object):
mask = mask.xml
data = str(data)
if mask is not None:
logging.warning("Use of send mask waiters is deprecated.")
log.warning("Use of send mask waiters is deprecated.")
wait_for = Waiter("SendWait_%s" % self.new_id(),
MatchXMLMask(mask))
self.register_handler(wait_for)
@ -679,7 +682,7 @@ class XMLStream(object):
self.__thread[name].start()
for t in range(0, HANDLER_THREADS):
logging.debug("Starting HANDLER THREAD")
log.debug("Starting HANDLER THREAD")
start_thread('stream_event_handler_%s' % t, self._event_runner)
start_thread('send_thread', self._send_thread)
@ -717,16 +720,16 @@ class XMLStream(object):
if self.is_client:
self.send_raw(self.stream_header)
except KeyboardInterrupt:
logging.debug("Keyboard Escape Detected in _process")
log.debug("Keyboard Escape Detected in _process")
self.stop.set()
except SystemExit:
logging.debug("SystemExit in _process")
log.debug("SystemExit in _process")
self.stop.set()
except Socket.error:
logging.exception('Socket Error')
log.exception('Socket Error')
except:
if not self.stop.isSet():
logging.exception('Connection error.')
log.exception('Connection error.')
if not self.stop.isSet() and self.auto_reconnect:
self.reconnect()
else:
@ -756,7 +759,7 @@ class XMLStream(object):
if depth == 0:
# The stream's root element has closed,
# terminating the stream.
logging.debug("End of stream recieved")
log.debug("End of stream recieved")
self.stream_end_event.set()
return False
elif depth == 1:
@ -770,7 +773,7 @@ class XMLStream(object):
# Keep the root element empty of children to
# save on memory use.
root.clear()
logging.debug("Ending read XML loop")
log.debug("Ending read XML loop")
def _build_stanza(self, xml, default_ns=None):
"""
@ -803,7 +806,7 @@ class XMLStream(object):
Arguments:
xml -- The XML stanza to analyze.
"""
logging.debug("RECV: %s" % tostring(xml,
log.debug("RECV: %s" % tostring(xml,
xmlns=self.default_ns,
stream=self))
# Apply any preprocessing filters.
@ -852,7 +855,7 @@ class XMLStream(object):
func(*args)
except Exception as e:
error_msg = 'Error processing event handler: %s'
logging.exception(error_msg % str(func))
log.exception(error_msg % str(func))
if hasattr(args[0], 'exception'):
args[0].exception(e)
@ -865,7 +868,7 @@ class XMLStream(object):
Stream event handlers will all execute in this thread. Custom event
handlers may be spawned in individual threads.
"""
logging.debug("Loading event runner")
log.debug("Loading event runner")
try:
while not self.stop.isSet():
try:
@ -883,14 +886,14 @@ class XMLStream(object):
handler.run(args[0])
except Exception as e:
error_msg = 'Error processing stream handler: %s'
logging.exception(error_msg % handler.name)
log.exception(error_msg % handler.name)
args[0].exception(e)
elif etype == 'schedule':
try:
logging.debug(args)
log.debug(args)
handler(*args[0])
except:
logging.exception('Error processing scheduled task')
log.exception('Error processing scheduled task')
elif etype == 'event':
func, threaded, disposable = handler
try:
@ -904,14 +907,14 @@ class XMLStream(object):
func(*args)
except Exception as e:
error_msg = 'Error processing event handler: %s'
logging.exception(error_msg % str(func))
log.exception(error_msg % str(func))
if hasattr(args[0], 'exception'):
args[0].exception(e)
elif etype == 'quit':
logging.debug("Quitting event runner thread")
log.debug("Quitting event runner thread")
return False
except KeyboardInterrupt:
logging.debug("Keyboard Escape Detected in _event_runner")
log.debug("Keyboard Escape Detected in _event_runner")
self.disconnect()
return
except SystemExit:
@ -929,14 +932,14 @@ class XMLStream(object):
data = self.send_queue.get(True, 1)
except queue.Empty:
continue
logging.debug("SEND: %s" % data)
log.debug("SEND: %s" % data)
try:
self.socket.send(data.encode('utf-8'))
except:
logging.warning("Failed to send %s" % data)
log.warning("Failed to send %s" % data)
self.disconnect(self.auto_reconnect)
except KeyboardInterrupt:
logging.debug("Keyboard Escape Detected in _send_thread")
log.debug("Keyboard Escape Detected in _send_thread")
self.disconnect()
return
except SystemExit: