diff options
author | lovetox <philipp@hoerist.com> | 2020-03-20 17:51:17 +0300 |
---|---|---|
committer | lovetox <philipp@hoerist.com> | 2020-03-20 17:51:17 +0300 |
commit | 5cc8dca3126365ac2dd2296060d516814781f606 (patch) | |
tree | 09a5b05a961452a5b7b4a3c3128ec4f671f75912 /nbxmpp | |
parent | 0c7293b8bb01f16a717e736727d7bcad4f888d57 (diff) |
Logging: Add context to logging output
Diffstat (limited to 'nbxmpp')
48 files changed, 673 insertions, 639 deletions
diff --git a/nbxmpp/auth.py b/nbxmpp/auth.py index 4d24dcf..c145b6a 100644 --- a/nbxmpp/auth.py +++ b/nbxmpp/auth.py @@ -28,6 +28,7 @@ from nbxmpp.protocol import SASL_ERROR_CONDITIONS from nbxmpp.protocol import SASL_AUTH_MECHS from nbxmpp.util import b64decode from nbxmpp.util import b64encode +from nbxmpp.util import LogAdapter from nbxmpp.const import GSSAPIState from nbxmpp.const import StreamState @@ -45,10 +46,7 @@ class SASL: """ Implements SASL authentication. """ - def __init__(self, client): - """ - :param client: Client object - """ + def __init__(self, client, log_context): self._client = client self._password = None @@ -58,6 +56,8 @@ class SASL: self._method = None self._error = None + self._log = LogAdapter(log, {'context': log_context}) + @property def error(self): return self._error @@ -95,14 +95,14 @@ class SASL: self._enabled_mechs.discard('GSSAPI') available_mechs = features.get_mechs() & self._enabled_mechs - log.info('Available mechanisms: %s', available_mechs) + self._log.info('Available mechanisms: %s', available_mechs) domain_based_name = features.get_domain_based_name() if domain_based_name is not None: - log.info('Found domain based name: %s', domain_based_name) + self._log.info('Found domain based name: %s', domain_based_name) if not available_mechs: - log.error('No available auth mechanisms found') + self._log.error('No available auth mechanisms found') self._abort_auth('invalid-mechanism') return @@ -113,11 +113,11 @@ class SASL: break if chosen_mechanism is None: - log.error('No available auth mechanisms found') + self._log.error('No available auth mechanisms found') self._abort_auth('invalid-mechanism') return - log.info('Chosen auth mechanism: %s', chosen_mechanism) + self._log.info('Chosen auth mechanism: %s', chosen_mechanism) if chosen_mechanism in ('SCRAM-SHA-256', 'SCRAM-SHA-1', 'PLAIN'): if not self._password: @@ -160,26 +160,26 @@ class SASL: self._client.domain) else: - log.error('Unknown auth mech') + self._log.error('Unknown auth mech') def _on_challenge(self, stanza): try: self._method.response(stanza.getData()) except AttributeError: - log.info('Mechanism has no response method') + self._log.info('Mechanism has no response method') self._abort_auth() except AuthFail as error: - log.error(error) + self._log.error(error) self._abort_auth() def _on_success(self, stanza): - log.info('Successfully authenticated with remote server') + self._log.info('Successfully authenticated with remote server') try: self._method.success(stanza.getData()) except AttributeError: pass except AuthFail as error: - log.error(error) + self._log.error(error) self._abort_auth() return @@ -197,7 +197,7 @@ class SASL: reason = name break - log.info('Failed SASL authentification: %s %s', reason, text) + self._log.info('Failed SASL authentification: %s %s', reason, text) self._abort_auth(reason, text) def _abort_auth(self, reason='malformed-request', text=None): @@ -379,7 +379,6 @@ class SCRAM: server_key = self._hmac(salted_password, 'Server Key') self._server_signature = self._hmac(server_key, auth_message) - log.debug('Response: %s', client_finale_message) payload = b64encode(client_finale_message) node = Node('response', attrs={'xmlns': NS_SASL}, diff --git a/nbxmpp/client.py b/nbxmpp/client.py index 57576a7..4312dda 100644 --- a/nbxmpp/client.py +++ b/nbxmpp/client.py @@ -48,6 +48,7 @@ from nbxmpp.util import get_stanza_id from nbxmpp.util import Observable from nbxmpp.util import validate_stream_header from nbxmpp.util import is_error_result +from nbxmpp.util import LogAdapter log = logging.getLogger('nbxmpp.stream') @@ -55,7 +56,7 @@ log = logging.getLogger('nbxmpp.stream') class Client(Observable): - def __init__(self): + def __init__(self, log_context=None): ''' Signals: resume-failed @@ -67,7 +68,15 @@ class Client(Observable): stanza-sent stanza-received ''' - Observable.__init__(self, log) + + self._log_context = log_context + if log_context is None: + self._log_context = str(id(self)) + + self._log = LogAdapter(log, {'context': self._log_context}) + + Observable.__init__(self, self._log) + self._jid = None self._lang = 'en' self._domain = None @@ -108,17 +117,21 @@ class Client(Observable): self._ping_source_id = None - self._dispatcher = StanzaDispatcher(self) + self._dispatcher = StanzaDispatcher(self, self._log_context) self._dispatcher.subscribe('before-dispatch', self._on_before_dispatch) self._dispatcher.subscribe('parsing-error', self._on_parsing_error) self._dispatcher.subscribe('stream-end', self._on_stream_end) - self._smacks = Smacks(self) - self._sasl = SASL(self) + self._smacks = Smacks(self, self._log_context) + self._sasl = SASL(self, self._log_context) self._state = StreamState.DISCONNECTED @property + def log_context(self): + return self._log_context + + @property def features(self): return self._stream_features @@ -215,7 +228,7 @@ class Client(Observable): @state.setter def state(self, value): self._state = value - log.info('Set state: %s', value) + self._log.info('Set state: %s', value) def set_state(self, state): self.state = state @@ -281,18 +294,20 @@ class Client(Observable): self._error = None, None, None def _set_error(self, domain, error, text=None): - log.info('Set error: %s, %s, %s', domain, error, text) + self._log.info('Set error: %s, %s, %s', domain, error, text) self._error = domain, error, text def _connect(self): if self._state not in (StreamState.DISCONNECTED, StreamState.RESOLVED): - log.error('Stream can\'t connect, stream state: %s', self._state) + self._log.error('Stream can\'t connect, stream state: %s', + self._state) return self.state = StreamState.CONNECTING self._reset_error() - self._con = self._get_connection(self._current_address, + self._con = self._get_connection(self._log_context, + self._current_address, self._accepted_certificates, self._ignore_tls_errors, self._ignored_tls_errors, @@ -314,15 +329,16 @@ class Client(Observable): def connect(self): if self._state != StreamState.DISCONNECTED: - log.error('Stream can\'t reconnect, stream state: %s', self._state) + self._log.error('Stream can\'t reconnect, stream state: %s', + self._state) return if self._connect_successful: - log.info('Reconnect') + self._log.info('Reconnect') self._connect() return - log.info('Connect') + self._log.info('Connect') self._reset_error() self.state = StreamState.RESOLVE @@ -333,8 +349,8 @@ class Client(Observable): self._addresses.resolve() def _on_addresses_resolved(self, _addresses, _signal_name): - log.info('Domain resolved') - log.info(self._addresses) + self._log.info('Domain resolved') + self._log.info(self._addresses) self.state = StreamState.RESOLVED self._address_generator = self._addresses.get_next_address( self.connection_types, @@ -348,14 +364,14 @@ class Client(Observable): except NoMoreAddresses: self._current_address = None self.state = StreamState.DISCONNECTED - log.error('Unable to connect to %s', self._addresses.domain) + self._log.error('Unable to connect to %s', self._addresses.domain) self._set_error(StreamError.CONNECTION_FAILED, 'connection-failed', 'Unable to connect to %s' % self._addresses.domain) self.notify('connection-failed') return - log.info('Current address: %s', self._current_address) + self._log.info('Current address: %s', self._current_address) self._connect() def disconnect(self, immediate=False): @@ -370,8 +386,8 @@ class Client(Observable): if self._state in (StreamState.DISCONNECTED, StreamState.DISCONNECTING): - log.warning('Stream can\'t disconnect, stream state: %s', - self._state) + self._log.warning('Stream can\'t disconnect, stream state: %s', + self._state) return self._disconnect(immediate=immediate) @@ -457,7 +473,7 @@ class Client(Observable): self._peer_certificate, self._peer_certificate_errors = connection.peer_certificate def accept_certificate(self): - log.info('Certificate accepted') + self._log.info('Certificate accepted') self._accepted_certificates.append(self._peer_certificate) self._connect() @@ -482,17 +498,17 @@ class Client(Observable): return if self._ping_source_id is not None: - log.info('Remove ping timer') + self._log.info('Remove ping timer') GLib.source_remove(self._ping_source_id) self._ping_source_id = None - log.info('Start ping timer') + self._log.info('Start ping timer') self._ping_source_id = GLib.timeout_add_seconds(180, self._ping) def _remove_ping_timer(self): if self._ping_source_id is None: return - log.info('Remove ping timer') + self._log.info('Remove ping timer') GLib.source_remove(self._ping_source_id) self._ping_source_id = None @@ -523,10 +539,10 @@ class Client(Observable): self._con.send(nonza, now) def _xmpp_state_machine(self, stanza=None): - log.info('Execute state machine') + self._log.info('Execute state machine') if stanza is not None: if stanza.getName() == 'error': - log.info('Stream error') + self._log.info('Stream error') # TODO: # self._disconnect_with_error(StreamError.SASL, # stanza.get_condition()) @@ -549,7 +565,7 @@ class Client(Observable): self._domain, self.is_websocket) except StanzaMalformed as error: - log.error(error) + self._log.error(error) self._disconnect_with_error(StreamError.STREAM, 'stanza-malformed', 'Invalid stream header') @@ -567,7 +583,7 @@ class Client(Observable): elif self.state == StreamState.WAIT_FOR_FEATURES: if stanza.getName() != 'features': - log.error('Invalid response: %s', stanza) + self._log.error('Invalid response: %s', stanza) self._disconnect_with_error( StreamError.STREAM, 'stanza-malformed', @@ -594,7 +610,7 @@ class Client(Observable): self._start_stream() return - log.error('Invalid response') + self._log.error('Invalid response') self._disconnect_with_error(StreamError.TLS, 'stanza-malformed', 'Invalid TLS response') @@ -677,21 +693,21 @@ class Client(Observable): tls_supported, required = features.has_starttls() if self._current_address.type == ConnectionType.PLAIN: if tls_supported and required: - log.error('Server requires TLS') + self._log.error('Server requires TLS') self._disconnect_with_error(StreamError.TLS, 'tls-required') return self._start_auth(features) return if not tls_supported: - log.error('Server does not support TLS') + self._log.error('Server does not support TLS') self._disconnect_with_error(StreamError.TLS, 'tls-not-supported') return self._start_tls() def _start_stream(self): - log.info('Start stream') + self._log.info('Start stream') self._stream_id = None self._dispatcher.reset_parser() header = get_stream_header(self._domain, self._lang, self.is_websocket) @@ -704,7 +720,7 @@ class Client(Observable): def _start_auth(self, features): if not features.has_sasl(): - log.error('Server does not support SASL') + self._log.error('Server does not support SASL') self._disconnect_with_error(StreamError.SASL, 'sasl-not-supported') return @@ -712,28 +728,28 @@ class Client(Observable): self._sasl.start_auth(features) def _start_bind(self): - log.info('Send bind') + self._log.info('Send bind') bind_request = BindRequest(self.resource) self.send_stanza(bind_request) self.state = StreamState.WAIT_FOR_BIND def _on_bind(self, stanza): if not isResultNode(stanza): - log.error('Binding failed: %s.', stanza.getTag('error')) + self._log.error('Binding failed: %s.', stanza.getTag('error')) if stanza.getError() == 'conflict' and self.resource is not None: - log.info('Try to request server generated resource') + self._log.info('Try to request server generated resource') self._start_bind() return self.set_state(StreamState.BIND_FAILED) return jid = stanza.getTag('bind').getTagData('jid') - log.info('Successfully bound %s', jid) + self._log.info('Successfully bound %s', jid) self._set_bound_jid(jid) if not self._session_required: # Server don't want us to initialize a session - log.info('No session required') + self._log.info('No session required') self.set_state(StreamState.BIND_SUCCESSFUL) else: session_request = SessionRequest() @@ -742,26 +758,26 @@ class Client(Observable): def _on_session(self, stanza): if isResultNode(stanza): - log.info('Successfully started session') + self._log.info('Successfully started session') self.set_state(StreamState.BIND_SUCCESSFUL) else: - log.error('Session open failed') + self._log.error('Session open failed') self.set_state(StreamState.SESSION_FAILED) def _ping(self): iq = Iq('get', to=self._jid.getBare()) iq.addChild(name='ping', namespace=NS_PING) self.send_stanza(iq, timeout=10, callback=self._on_pong) - log.info('Ping') + self._log.info('Ping') def _on_pong(self, _client, result): self._ping_source_id = None if is_error_result(result): if result.condition == 'timeout': - log.info('Ping timeout') + self._log.info('Ping timeout') self._disconnect(immediate=True) return - log.info('Pong') + self._log.info('Pong') def register_handler(self, *args, **kwargs): self._dispatcher.register_handler(*args, **kwargs) diff --git a/nbxmpp/connection.py b/nbxmpp/connection.py index 9eefad1..af7ea26 100644 --- a/nbxmpp/connection.py +++ b/nbxmpp/connection.py @@ -21,6 +21,7 @@ from gi.repository import Gio from nbxmpp.const import TCPState from nbxmpp.util import Observable +from nbxmpp.util import LogAdapter log = logging.getLogger('nbxmpp.connection') @@ -39,12 +40,16 @@ class Connection(Observable): disconnected ''' def __init__(self, + log_context, address, accepted_certificates, ignore_tls_errors, ignored_tls_errors, client_cert): - Observable.__init__(self, log) + + self._log = LogAdapter(log, {'context': log_context}) + + Observable.__init__(self, self._log) self._client_cert = client_cert self._address = address @@ -72,23 +77,23 @@ class Connection(Observable): @state.setter def state(self, value): - log.info('Set Connection State: %s', value) + self._log.info('Set Connection State: %s', value) self._state = value def _accept_certificate(self): if not self._peer_certificate_errors: return True - log.info('Found TLS certificate errors: %s', - self._peer_certificate_errors) + self._log.info('Found TLS certificate errors: %s', + self._peer_certificate_errors) if self._ignore_tls_errors: - log.warning('Ignore all errors') + self._log.warning('Ignore all errors') return True if self._ignored_tls_errors: - log.warning('Ignore TLS certificate errors: %s', - self._ignored_tls_errors) + self._log.warning('Ignore TLS certificate errors: %s', + self._ignored_tls_errors) self._peer_certificate_errors -= self._ignored_tls_errors if Gio.TlsCertificateFlags.UNKNOWN_CA in self._peer_certificate_errors: @@ -111,14 +116,13 @@ class Connection(Observable): def send(self, stanza, now=False): raise NotImplementedError - @staticmethod - def _log_stanza(data, received=True): + def _log_stanza(self, data, received=True): direction = 'RECEIVED' if received else 'SENT' message = ('::::: DATA %s ::::' '\n_____________\n' '%s' '\n_____________') - log.info(message, direction, data) + self._log.info(message, direction, data) def start_tls_negotiation(self): raise NotImplementedError diff --git a/nbxmpp/dispatcher.py b/nbxmpp/dispatcher.py index c91be32..73fca70 100644 --- a/nbxmpp/dispatcher.py +++ b/nbxmpp/dispatcher.py @@ -84,6 +84,7 @@ from nbxmpp.util import get_invalid_xml_regex from nbxmpp.util import is_websocket_close from nbxmpp.util import is_websocket_stream_error from nbxmpp.util import Observable +from nbxmpp.util import LogAdapter log = logging.getLogger('nbxmpp.dispatcher') @@ -100,13 +101,15 @@ class StanzaDispatcher(Observable): """ - def __init__(self, client): + def __init__(self, client, log_context): Observable.__init__(self, log) self._client = client self._modules = {} self._parser = None self._websocket_stream_error = None + self._log = LogAdapter(log, {'context': log_context}) + self._handlers = {} self._id_callbacks = {} @@ -132,7 +135,7 @@ class StanzaDispatcher(Observable): self._register_modules() def set_dispatch_callback(self, callback): - log.info('Set dispatch callback: %s', callback) + self._log.info('Set dispatch callback: %s', callback) self._dispatch_callback = callback def get_module(self, name): @@ -212,7 +215,7 @@ class StanzaDispatcher(Observable): self._websocket_stream_error = name elif is_websocket_close(stanza): - log.info('Stream <close> received') + self._log.info('Stream <close> received') self.notify('stream-end', self._websocket_stream_error) return @@ -222,13 +225,13 @@ class StanzaDispatcher(Observable): try: self._parser.Parse(data) except (ExpatError, ValueError) as error: - log.error('XML parsing error: %s', error) + self._log.error('XML parsing error: %s', error) self.notify('parsing-error', error) return # end stream:stream tag received if self._parser.has_received_endtag(): - log.info('End of stream: %s', self._parser.streamError) + self._log.info('End of stream: %s', self._parser.streamError) self.notify('stream-end', self._parser.streamError) return @@ -236,7 +239,7 @@ class StanzaDispatcher(Observable): """ Setup handler structure for namespace """ - log.debug('Register namespace "%s"', xmlns) + self._log.debug('Register namespace "%s"', xmlns) self._handlers[xmlns] = {} self._register_protocol('error', Protocol, xmlns=xmlns) self._register_protocol('unknown', Protocol, xmlns=xmlns) @@ -248,8 +251,8 @@ class StanzaDispatcher(Observable): """ if xmlns is None: xmlns = NS_CLIENT - log.debug('Register protocol "%s (%s)" as %s', - tag_name, xmlns, protocol) + self._log.debug('Register protocol "%s (%s)" as %s', + tag_name, xmlns, protocol) self._handlers[xmlns][tag_name] = {'type': protocol, 'default': []} def register_handler(self, name, handler, typ='', ns='', @@ -272,8 +275,8 @@ class StanzaDispatcher(Observable): if not typ and not ns: typ = 'default' - log.debug('Register handler %s for "%s" type->%s ns->%s(%s) priority->%s', - handler, name, typ, ns, xmlns, priority) + self._log.debug('Register handler %s for "%s" type->%s ns->%s(%s) priority->%s', + handler, name, typ, ns, xmlns, priority) if xmlns not in self._handlers: self._register_namespace(xmlns) @@ -313,11 +316,11 @@ class StanzaDispatcher(Observable): try: self._handlers[xmlns][name][specific].remove(handler_dict) except ValueError: - log.warning('Unregister failed: %s for "%s" type->%s ns->%s(%s)', - handler, name, typ, ns, xmlns) + self._log.warning('Unregister failed: %s for "%s" type->%s ns->%s(%s)', + handler, name, typ, ns, xmlns) else: - log.debug('Unregister handler %s for "%s" type->%s ns->%s(%s)', - handler, name, typ, ns, xmlns) + self._log.debug('Unregister handler %s for "%s" type->%s ns->%s(%s)', + handler, name, typ, ns, xmlns) def _default_handler(self, stanza): """ @@ -344,19 +347,19 @@ class StanzaDispatcher(Observable): xmlns = stanza.getNamespace() if xmlns not in self._handlers: - log.warning('Unknown namespace: %s', xmlns) + self._log.warning('Unknown namespace: %s', xmlns) xmlns = 'unknown' if name not in self._handlers[xmlns]: - log.warning('Unknown stanza: %s', stanza) + self._log.warning('Unknown stanza: %s', stanza) name = 'unknown' # Convert simplexml to Protocol object try: stanza = self._handlers[xmlns][name]['type'](node=stanza) except InvalidJid: - log.warning('Invalid JID, ignoring stanza') - log.warning(stanza) + self._log.warning('Invalid JID, ignoring stanza') + self._log.warning(stanza) return own_jid = self._client.get_bound_jid() @@ -376,7 +379,8 @@ class StanzaDispatcher(Observable): if to is None: stanza.setTo(own_jid) elif not to.bareMatch(own_jid): - log.warning('Message addressed to someone else: %s', stanza) + self._log.warning('Message addressed to someone else: %s', + stanza) return if stanza.getFrom() is None: @@ -386,19 +390,19 @@ class StanzaDispatcher(Observable): try: stanza, properties.carbon = unwrap_carbon(stanza, own_jid) except (InvalidFrom, InvalidJid) as exc: - log.warning(exc) - log.warning(stanza) + self._log.warning(exc) + self._log.warning(stanza) return except NodeProcessed as exc: - log.info(exc) + self._log.info(exc) return # Unwrap mam try: stanza, properties.mam = unwrap_mam(stanza, own_jid) except (InvalidStanza, InvalidJid) as exc: - log.warning(exc) - log.warning(stanza) + self._log.warning(exc) + self._log.warning(stanza) return typ = stanza.getType() @@ -408,7 +412,7 @@ class StanzaDispatcher(Observable): typ = '' stanza.props = stanza.getProperties() - log.debug('type: %s, properties: %s', typ, stanza.props) + self._log.debug('type: %s, properties: %s', typ, stanza.props) # Process callbacks _id = stanza.getID() @@ -421,7 +425,7 @@ class StanzaDispatcher(Observable): try: func(self._client, stanza, **user_data) except Exception: - log.exception('Error while handling stanza') + self._log.exception('Error while handling stanza') return # Gather specifics depending on stanza properties @@ -444,13 +448,13 @@ class StanzaDispatcher(Observable): chain.sort(key=lambda x: x['priority']) for handler in chain: - log.info('Call handler: %s', handler['func'].__qualname__) + self._log.info('Call handler: %s', handler['func'].__qualname__) try: handler['func'](self._client, stanza, properties) except NodeProcessed: return except Exception: - log.exception('Handler exception:') + self._log.exception('Handler exception:') return # Stanza was not processed call default handler @@ -458,16 +462,16 @@ class StanzaDispatcher(Observable): def add_callback_for_id(self, id_, func, timeout, user_data): if timeout is not None and self._timeout_id is None: - log.info('Add timeout source') + self._log.info('Add timeout source') self._timeout_id = GLib.timeout_add_seconds( 1, self._timeout_check) timeout = time.monotonic() + timeout self._id_callbacks[id_] = (func, timeout, user_data) def _timeout_check(self): - log.info('Run timeout check') + self._log.info('Run timeout check') if not self._id_callbacks: - log.info('Remove timeout source, no callbacks scheduled') + self._log.info('Remove timeout source, no callbacks scheduled') self._timeout_id = None return False diff --git a/nbxmpp/examples/client.py b/nbxmpp/examples/client.py index 82f6f5c..211a971 100644 --- a/nbxmpp/examples/client.py +++ b/nbxmpp/examples/client.py @@ -25,8 +25,9 @@ log = logging.getLogger('nbxmpp') log.setLevel('INFO') log.addHandler(consoleloghandler) -formatter = logging.Formatter('%(asctime)s %(levelname)-7s %(name)-18s %(message)s', - datefmt='%H:%M:%S') +formatter = logging.Formatter( + '%(asctime)s %(levelname)-7s %(name)-25s %(message)s', + datefmt='%H:%M:%S') consoleloghandler.setFormatter(formatter) @@ -77,7 +78,7 @@ class TestClient(Gtk.Window): self._load_config() def _create_client(self): - self._client = Client() + self._client = Client(log_context='TEST') self._client.set_domain(self.address.getDomain()) self._client.set_username(self.address.getNode()) self._client.set_resource('test') diff --git a/nbxmpp/modules/activity.py b/nbxmpp/modules/activity.py index 09e5026..f8411d5 100644 --- a/nbxmpp/modules/activity.py +++ b/nbxmpp/modules/activity.py @@ -15,8 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_ACTIVITY from nbxmpp.protocol import NS_PUBSUB_EVENT from nbxmpp.protocol import Node @@ -24,12 +22,13 @@ from nbxmpp.protocol import NodeProcessed from nbxmpp.structs import StanzaHandler from nbxmpp.structs import ActivityData from nbxmpp.const import ACTIVITIES - -log = logging.getLogger('nbxmpp.m.activity') +from nbxmpp.modules.base import BaseModule -class Activity: +class Activity(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -52,7 +51,8 @@ class Activity: activity_node = item.getTag('activity', namespace=NS_ACTIVITY) if not activity_node.getChildren(): - log.info('Received activity: %s - no activity set', properties.jid) + self._log.info('Received activity: %s - no activity set', + properties.jid) return activity, subactivity, text = None, None, None @@ -65,13 +65,13 @@ class Activity: subactivity = self._parse_sub_activity(child) if activity is None and activity_node.getPayload(): - log.warning('No valid activity value found') - log.warning(stanza) + self._log.warning('No valid activity value found') + self._log.warning(stanza) raise NodeProcessed data = ActivityData(activity, subactivity, text) pubsub_event = properties.pubsub_event._replace(data=data) - log.info('Received activity: %s - %s', properties.jid, data) + self._log.info('Received activity: %s - %s', properties.jid, data) properties.pubsub_event = pubsub_event diff --git a/nbxmpp/modules/adhoc.py b/nbxmpp/modules/adhoc.py index 39f4cb1..a5b9490 100644 --- a/nbxmpp/modules/adhoc.py +++ b/nbxmpp/modules/adhoc.py @@ -15,8 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_COMMANDS from nbxmpp.protocol import NS_DISCO_ITEMS from nbxmpp.protocol import NS_DATA @@ -32,13 +30,13 @@ from nbxmpp.const import AdHocStatus from nbxmpp.const import AdHocAction from nbxmpp.const import AdHocNoteType from nbxmpp.modules.discovery import get_disco_request +from nbxmpp.modules.base import BaseModule -log = logging.getLogger('nbxmpp.m.adhoc') - - -class AdHoc: +class AdHoc(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [] @@ -51,11 +49,11 @@ class AdHoc: @callback def _command_list_received(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) payload = stanza.getQueryPayload() if payload is None: - return raise_error(log.warning, stanza, 'stanza-malformed') + return raise_error(self._log.warning, stanza, 'stanza-malformed') command_list = [] for item in payload: @@ -64,8 +62,10 @@ class AdHoc: try: command_list.append(AdHocCommand(**item.getAttrs())) except Exception as error: - log.warning(error) - return raise_error(log.warning, stanza, 'stanza-malformed') + self._log.warning(error) + return raise_error(self._log.warning, + stanza, + 'stanza-malformed') return command_list @@ -89,11 +89,11 @@ class AdHoc: @callback def _command_result_received(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) command = stanza.getTag('command', namespace=NS_COMMANDS) if command is None: - return raise_error(log.warning, stanza, 'stanza-malformed') + return raise_error(self._log.warning, stanza, 'stanza-malformed') attrs = command.getAttrs() notes = [] @@ -121,5 +121,5 @@ class AdHoc: actions=actions, notes=notes) except Exception as error: - log.warning(error) - return raise_error(log.warning, stanza, 'stanza-malformed') + self._log.warning(error) + return raise_error(self._log.warning, stanza, 'stanza-malformed') diff --git a/nbxmpp/modules/annotations.py b/nbxmpp/modules/annotations.py index 507e27f..894e759 100644 --- a/nbxmpp/modules/annotations.py +++ b/nbxmpp/modules/annotations.py @@ -15,8 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_PRIVATE from nbxmpp.protocol import NS_ROSTERNOTES from nbxmpp.protocol import Iq @@ -29,12 +27,13 @@ from nbxmpp.modules.date_and_time import parse_datetime from nbxmpp.util import call_on_response from nbxmpp.util import callback from nbxmpp.util import raise_error - -log = logging.getLogger('nbxmpp.m.annotations') +from nbxmpp.modules.base import BaseModule -class Annotations: +class Annotations(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [] @@ -44,18 +43,18 @@ class Annotations: @call_on_response('_annotations_received') def request_annotations(self): - log.info('Request annotations for %s', self.domain) + self._log.info('Request annotations for %s', self.domain) payload = Node('storage', attrs={'xmlns': NS_ROSTERNOTES}) return Iq(typ='get', queryNS=NS_PRIVATE, payload=payload) @callback def _annotations_received(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) storage = stanza.getQueryChild('storage') if storage is None: - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, stanza, 'stanza-malformed', 'No annotations found') notes = [] @@ -63,8 +62,8 @@ class Annotations: try: jid = JID(note.getAttr('jid')) except Exception as error: - log.warning('Invalid JID: %s, %s', - note.getAttr('jid'), error) + self._log.warning('Invalid JID: %s, %s', + note.getAttr('jid'), error) continue cdate = note.getAttr('cdate') @@ -79,16 +78,16 @@ class Annotations: notes.append(AnnotationNote(jid=jid, cdate=cdate, mdate=mdate, data=data)) - log.info('Received annotations from %s:', self.domain) + self._log.info('Received annotations from %s:', self.domain) for note in notes: - log.info(note) + self._log.info(note) return notes @call_on_response('_default_response') def set_annotations(self, notes): - log.info('Set annotations for %s:', self.domain) + self._log.info('Set annotations for %s:', self.domain) for note in notes: - log.info(note) + self._log.info(note) storage = Node('storage', attrs={'xmlns': NS_ROSTERNOTES}) for note in notes: node = Node('note', attrs={'jid': note.jid}) @@ -103,5 +102,5 @@ class Annotations: @callback def _default_response(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) return CommonResult(jid=stanza.getFrom()) diff --git a/nbxmpp/modules/attention.py b/nbxmpp/modules/attention.py index 109bfde..efdc3fe 100644 --- a/nbxmpp/modules/attention.py +++ b/nbxmpp/modules/attention.py @@ -15,17 +15,16 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_ATTENTION from nbxmpp.protocol import NS_DELAY2 from nbxmpp.structs import StanzaHandler - -log = logging.getLogger('nbxmpp.m.attention') +from nbxmpp.modules.base import BaseModule -class Attention: +class Attention(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', diff --git a/nbxmpp/modules/base.py b/nbxmpp/modules/base.py new file mode 100644 index 0000000..b245b6a --- /dev/null +++ b/nbxmpp/modules/base.py @@ -0,0 +1,27 @@ +# Copyright (C) 2018 Philipp Hörist <philipp AT hoerist.com> +# +# This file is part of nbxmpp. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 3 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; If not, see <http://www.gnu.org/licenses/>. + +import logging + +from nbxmpp.util import LogAdapter + + +class BaseModule: + def __init__(self, client): + logger_name = 'nbxmpp.m.%s' % self.__class__.__name__.lower() + self._log = LogAdapter(logging.getLogger(logger_name), + {'context': client.log_context}) diff --git a/nbxmpp/modules/blocking.py b/nbxmpp/modules/blocking.py index 5fac9e6..2615c1c 100644 --- a/nbxmpp/modules/blocking.py +++ b/nbxmpp/modules/blocking.py @@ -15,8 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_BLOCKING from nbxmpp.protocol import Iq from nbxmpp.protocol import isResultNode @@ -25,12 +23,13 @@ from nbxmpp.structs import CommonResult from nbxmpp.util import call_on_response from nbxmpp.util import callback from nbxmpp.util import raise_error - -log = logging.getLogger('nbxmpp.m.blocking') +from nbxmpp.modules.base import BaseModule -class Blocking: +class Blocking(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [] @@ -44,21 +43,21 @@ class Blocking: def _blocking_list_received(self, stanza): blocked = [] if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) blocklist = stanza.getTag('blocklist', namespace=NS_BLOCKING) if blocklist is None: - return raise_error(log.warning, stanza, 'stanza-malformed') + return raise_error(self._log.warning, stanza, 'stanza-malformed') for item in blocklist.getTags('item'): blocked.append(item.getAttr('jid')) - log.info('Received blocking list: %s', blocked) + self._log.info('Received blocking list: %s', blocked) return BlockingListResult(blocking_list=blocked) @call_on_response('_default_response') def block(self, jids): - log.info('Block: %s', jids) + self._log.info('Block: %s', jids) iq = Iq('set', NS_BLOCKING) query = iq.setQuery(name='block') for jid in jids: @@ -67,7 +66,7 @@ class Blocking: @call_on_response('_default_response') def unblock(self, jids): - log.info('Unblock: %s', jids) + self._log.info('Unblock: %s', jids) iq = Iq('set', NS_BLOCKING) query = iq.setQuery(name='unblock') for jid in jids: @@ -77,5 +76,5 @@ class Blocking: @callback def _default_response(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) return CommonResult(jid=stanza.getFrom()) diff --git a/nbxmpp/modules/bookmarks.py b/nbxmpp/modules/bookmarks.py index 0642566..3e61981 100644 --- a/nbxmpp/modules/bookmarks.py +++ b/nbxmpp/modules/bookmarks.py @@ -15,8 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_BOOKMARKS from nbxmpp.protocol import NS_BOOKMARKS_2 from nbxmpp.protocol import NS_PUBSUB_EVENT @@ -39,9 +37,7 @@ from nbxmpp.modules.pubsub import get_pubsub_item from nbxmpp.modules.pubsub import get_pubsub_items from nbxmpp.modules.pubsub import get_pubsub_request from nbxmpp.modules.pubsub import get_publish_options - - -log = logging.getLogger('nbxmpp.m.bookmarks') +from nbxmpp.modules.base import BaseModule BOOKMARK_1_OPTIONS = { @@ -59,8 +55,10 @@ BOOKMARK_2_OPTIONS = { } -class Bookmarks: +class Bookmarks(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -92,19 +90,19 @@ class Bookmarks: storage_node = item.getTag('storage', namespace=NS_BOOKMARKS) if storage_node is None: - log.warning('No storage node found') - log.warning(stanza) + self._log.warning('No storage node found') + self._log.warning(stanza) raise NodeProcessed bookmarks = self._parse_bookmarks(storage_node) if not bookmarks: - log.info('Bookmarks removed') + self._log.info('Bookmarks removed') return pubsub_event = properties.pubsub_event._replace(data=bookmarks) - log.info('Received bookmarks from: %s', properties.jid) + self._log.info('Received bookmarks from: %s', properties.jid) for bookmark in bookmarks: - log.info(bookmark) + self._log.info(bookmark) properties.pubsub_event = pubsub_event @@ -125,13 +123,12 @@ class Bookmarks: raise NodeProcessed pubsub_event = properties.pubsub_event._replace(data=bookmark_item) - log.info('Received bookmark item from: %s', properties.jid) - log.info(bookmark_item) + self._log.info('Received bookmark item from: %s', properties.jid) + self._log.info(bookmark_item) properties.pubsub_event = pubsub_event - @staticmethod - def _parse_bookmarks(storage): + def _parse_bookmarks(self, storage): bookmarks = [] confs = storage.getTags('conference') for conf in confs: @@ -142,15 +139,15 @@ class Bookmarks: try: autojoin = from_xs_boolean(autojoin) except ValueError as error: - log.warning(error) - log.warning(storage) + self._log.warning(error) + self._log.warning(storage) autojoin = False try: jid = JID(conf.getAttr('jid')) except Exception as error: - log.warning('Invalid JID: %s, %s', - conf.getAttr('jid'), error) + self._log.warning('Invalid JID: %s, %s', + conf.getAttr('jid'), error) continue bookmark = BookmarkData( @@ -163,24 +160,23 @@ class Bookmarks: return bookmarks - @staticmethod - def _parse_bookmarks2(item): + def _parse_bookmarks2(self, item): jid = item.getAttr('id') if jid is None: - log.warning('No id attr found') + self._log.warning('No id attr found') return None try: jid = JID(jid) except Exception as error: - log.warning('Invalid JID: %s', error) - log.warning(item) + self._log.warning('Invalid JID: %s', error) + self._log.warning(item) return None conference = item.getTag('conference', namespace=NS_BOOKMARKS_2) if conference is None: - log.warning('No conference node found') - log.warning(item) + self._log.warning('No conference node found') + self._log.warning(item) return None autojoin = conference.getAttr('autojoin') in ('True', 'true', '1') @@ -203,30 +199,32 @@ class Bookmarks: def request_bookmarks(self, type_): jid = self._client.get_bound_jid().getBare() if type_ == BookmarkStoreType.PUBSUB_BOOKMARK_2: - log.info('Request bookmarks 2 (PubSub)') + self._log.info('Request bookmarks 2 (PubSub)') request = get_pubsub_request(jid, NS_BOOKMARKS_2) return request, {'type_': type_} if type_ == BookmarkStoreType.PUBSUB_BOOKMARK_1: - log.info('Request bookmarks (PubSub)') + self._log.info('Request bookmarks (PubSub)') request = get_pubsub_request(jid, NS_BOOKMARKS, max_items=1) return request, {'type_': type_} if type_ == BookmarkStoreType.PRIVATE: - log.info('Request bookmarks (Private Storage)') + self._log.info('Request bookmarks (Private Storage)') return self.get_private_request(), {'type_': type_} return None @callback def _bookmarks_received(self, stanza, type_): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) bookmarks = [] if type_ == BookmarkStoreType.PUBSUB_BOOKMARK_2: items = get_pubsub_items(stanza, NS_BOOKMARKS_2) if items is None: - return raise_error(log.warning, stanza, 'stanza-malformed') + return raise_error(self._log.warning, + stanza, + 'stanza-malformed') for item in items: bookmark_item = self._parse_bookmarks2(item) @@ -238,7 +236,9 @@ class Bookmarks: if item is not None: storage_node = item.getTag('storage', namespace=NS_BOOKMARKS) if storage_node is None: - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, + stanza, + 'stanza-malformed', 'No storage node') if storage_node.getChildren(): @@ -248,7 +248,9 @@ class Bookmarks: query = stanza.getQuery() storage_node = query.getTag('storage', namespace=NS_BOOKMARKS) if storage_node is None: - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, + stanza, + 'stanza-malformed', 'No storage node') if storage_node.getChildren(): @@ -257,9 +259,9 @@ class Bookmarks: from_ = stanza.getFrom() if from_ is None: from_ = self._client.get_bound_jid().getBare() - log.info('Received bookmarks from: %s', from_) + self._log.info('Received bookmarks from: %s', from_) for bookmark in bookmarks: - log.info(bookmark) + self._log.info(bookmark) return bookmarks @staticmethod @@ -298,14 +300,14 @@ class Bookmarks: self._store_with_private(bookmarks) def retract_bookmark(self, bookmark_jid): - log.info('Retract Bookmark: %s', bookmark_jid) + self._log.info('Retract Bookmark: %s', bookmark_jid) jid = self._client.get_bound_jid().getBare() self._client.get_module('PubSub').retract(jid, NS_BOOKMARKS_2, str(bookmark_jid)) def _store_bookmark_1(self, bookmarks): - log.info('Store Bookmarks 1 (PubSub)') + self._log.info('Store Bookmarks 1 (PubSub)') jid = self._client.get_bound_jid().getBare() self._bookmark_1_queue = bookmarks item = self._build_storage_node(bookmarks) @@ -321,10 +323,10 @@ class Bookmarks: def _store_bookmark_2(self, bookmarks): if self._node_configuration_not_possible: - log.warning('Node configuration not possible') + self._log.warning('Node configuration not possible') return - log.info('Store Bookmarks 2 (PubSub)') + self._log.info('Store Bookmarks 2 (PubSub)') jid = self._client.get_bound_jid().getBare() for bookmark in bookmarks: self._bookmark_2_queue[bookmark.jid] = bookmark @@ -360,11 +362,11 @@ class Bookmarks: else: self._bookmark_1_queue = [] self._bookmark_2_queue.pop(result.id, None) - log.warning(result) + self._log.warning(result) def _on_node_configuration_received(self, result): if is_error_result(result): - log.warning(result) + self._log.warning(result) self._bookmark_1_queue = [] self._bookmark_2_queue.clear() return @@ -383,13 +385,13 @@ class Bookmarks: def _on_node_configuration_finished(self, result): self._node_configuration_in_progress = False if is_error_result(result): - log.warning(result) + self._log.warning(result) self._bookmark_2_queue.clear() self._bookmark_1_queue = [] self._node_configuration_not_possible = True return - log.info('Republish bookmarks') + self._log.info('Republish bookmarks') if self._bookmark_2_queue: bookmarks = self._bookmark_2_queue.copy() self._bookmark_2_queue.clear() @@ -411,12 +413,11 @@ class Bookmarks: @call_on_response('_on_private_store_result') def _store_with_private(self, bookmarks): - log.info('Store Bookmarks (Private Storage)') + self._log.info('Store Bookmarks (Private Storage)') storage_node = self._build_storage_node(bookmarks) return Iq('set', NS_PRIVATE, payload=storage_node) - @staticmethod - def _on_private_store_result(_client, stanza): + def _on_private_store_result(self, _client, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) return None diff --git a/nbxmpp/modules/captcha.py b/nbxmpp/modules/captcha.py index 8e4f90a..08a00e9 100644 --- a/nbxmpp/modules/captcha.py +++ b/nbxmpp/modules/captcha.py @@ -15,20 +15,19 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_CAPTCHA from nbxmpp.protocol import NS_DATA from nbxmpp.structs import StanzaHandler from nbxmpp.structs import CaptchaData from nbxmpp.modules.dataforms import extend_form from nbxmpp.modules.bits_of_binary import parse_bob_data - -log = logging.getLogger('nbxmpp.m.captcha') +from nbxmpp.modules.base import BaseModule -class Captcha: +class Captcha(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -37,16 +36,15 @@ class Captcha: priority=40), ] - @staticmethod - def _process_captcha(_client, stanza, properties): + def _process_captcha(self, _client, stanza, properties): captcha = stanza.getTag('captcha', namespace=NS_CAPTCHA) if captcha is None: return data_form = captcha.getTag('x', namespace=NS_DATA) if data_form is None: - log.warning('Invalid captcha form') - log.warning(stanza) + self._log.warning('Invalid captcha form') + self._log.warning(stanza) return form = extend_form(node=data_form) diff --git a/nbxmpp/modules/chat_markers.py b/nbxmpp/modules/chat_markers.py index eec8fa6..a086f63 100644 --- a/nbxmpp/modules/chat_markers.py +++ b/nbxmpp/modules/chat_markers.py @@ -15,17 +15,16 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_CHATMARKERS from nbxmpp.structs import StanzaHandler from nbxmpp.structs import ChatMarker - -log = logging.getLogger('nbxmpp.m.chat_markers') +from nbxmpp.modules.base import BaseModule -class ChatMarkers: +class ChatMarkers(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -34,8 +33,7 @@ class ChatMarkers: priority=15), ] - @staticmethod - def _process_message_marker(_client, stanza, properties): + def _process_message_marker(self, _client, stanza, properties): type_ = stanza.getTag('received', namespace=NS_CHATMARKERS) if type_ is None: type_ = stanza.getTag('displayed', namespace=NS_CHATMARKERS) @@ -47,8 +45,8 @@ class ChatMarkers: name = type_.getName() id_ = type_.getAttr('id') if id_ is None: - log.warning('Chatmarker without id') - log.warning(stanza) + self._log.warning('Chatmarker without id') + self._log.warning(stanza) return properties.marker = ChatMarker(name, id_) diff --git a/nbxmpp/modules/chatstates.py b/nbxmpp/modules/chatstates.py index 8f9869f..2fc13d3 100644 --- a/nbxmpp/modules/chatstates.py +++ b/nbxmpp/modules/chatstates.py @@ -15,18 +15,17 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_CHATSTATES from nbxmpp.protocol import NS_DELAY2 from nbxmpp.structs import StanzaHandler from nbxmpp.const import CHATSTATES - -log = logging.getLogger('nbxmpp.m.chatstates') +from nbxmpp.modules.base import BaseModule -class Chatstates: +class Chatstates(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -47,8 +46,8 @@ class Chatstates: return if chatstate not in CHATSTATES: - log.warning('Invalid chatstate: %s', chatstate) - log.warning(stanza) + self._log.warning('Invalid chatstate: %s', chatstate) + self._log.warning(stanza) return properties.chatstate = chatstate diff --git a/nbxmpp/modules/correction.py b/nbxmpp/modules/correction.py index 68d6376..e4a3858 100644 --- a/nbxmpp/modules/correction.py +++ b/nbxmpp/modules/correction.py @@ -15,17 +15,16 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_CORRECT from nbxmpp.structs import StanzaHandler from nbxmpp.structs import CorrectionData - -log = logging.getLogger('nbxmpp.m.correction') +from nbxmpp.modules.base import BaseModule -class Correction: +class Correction(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -41,8 +40,8 @@ class Correction: id_ = replace.getAttr('id') if id_ is None: - log.warning('Correcton without id attribute') - log.warning(stanza) + self._log.warning('Correcton without id attribute') + self._log.warning(stanza) return properties.correction = CorrectionData(id_) diff --git a/nbxmpp/modules/delay.py b/nbxmpp/modules/delay.py index 859ad1a..dbf42b3 100644 --- a/nbxmpp/modules/delay.py +++ b/nbxmpp/modules/delay.py @@ -20,12 +20,15 @@ import logging from nbxmpp.protocol import NS_DELAY2 from nbxmpp.structs import StanzaHandler from nbxmpp.modules.date_and_time import parse_datetime +from nbxmpp.modules.base import BaseModule log = logging.getLogger('nbxmpp.m.delay') -class Delay: +class Delay(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', diff --git a/nbxmpp/modules/discovery.py b/nbxmpp/modules/discovery.py index c849afd..894d8f7 100644 --- a/nbxmpp/modules/discovery.py +++ b/nbxmpp/modules/discovery.py @@ -24,6 +24,7 @@ from nbxmpp.protocol import NS_DISCO_ITEMS from nbxmpp.protocol import NS_DATA from nbxmpp.protocol import isResultNode from nbxmpp.modules.dataforms import extend_form +from nbxmpp.modules.base import BaseModule from nbxmpp.structs import DiscoIdentity from nbxmpp.structs import DiscoInfo from nbxmpp.structs import DiscoItems @@ -36,31 +37,33 @@ from nbxmpp.util import raise_error log = logging.getLogger('nbxmpp.m.discovery') -class Discovery: +class Discovery(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [] @call_on_response('_disco_info_received') def disco_info(self, jid, node=None): - log.info('Disco info: %s, node: %s', jid, node) + self._log.info('Disco info: %s, node: %s', jid, node) return get_disco_request(NS_DISCO_INFO, jid, node) @callback def _disco_info_received(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) return parse_disco_info(stanza) @call_on_response('_disco_items_received') def disco_items(self, jid, node=None): - log.info('Disco items: %s, node: %s', jid, node) + self._log.info('Disco items: %s, node: %s', jid, node) return get_disco_request(NS_DISCO_ITEMS, jid, node) @callback def _disco_items_received(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) return parse_disco_items(stanza) diff --git a/nbxmpp/modules/eme.py b/nbxmpp/modules/eme.py index 84b1d3e..10643d5 100644 --- a/nbxmpp/modules/eme.py +++ b/nbxmpp/modules/eme.py @@ -15,17 +15,16 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_EME from nbxmpp.structs import StanzaHandler from nbxmpp.structs import EMEData - -log = logging.getLogger('nbxmpp.m.eme') +from nbxmpp.modules.base import BaseModule -class EME: +class EME(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -34,8 +33,7 @@ class EME: priority=40) ] - @staticmethod - def _process_eme(_client, stanza, properties): + def _process_eme(self, _client, stanza, properties): encryption = stanza.getTag('encryption', namespace=NS_EME) if encryption is None: return @@ -43,8 +41,8 @@ class EME: name = encryption.getAttr('name') namespace = encryption.getAttr('namespace') if namespace is None: - log.warning('No namespace on message') + self._log.warning('No namespace on message') return properties.eme = EMEData(name=name, namespace=namespace) - log.info('Found data: %s', properties.eme) + self._log.info('Found data: %s', properties.eme) diff --git a/nbxmpp/modules/entity_caps.py b/nbxmpp/modules/entity_caps.py index dd04ee2..bc18afb 100644 --- a/nbxmpp/modules/entity_caps.py +++ b/nbxmpp/modules/entity_caps.py @@ -15,17 +15,16 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_CAPS from nbxmpp.structs import StanzaHandler from nbxmpp.structs import EntityCapsData - -log = logging.getLogger('nbxmpp.m.entity_caps') +from nbxmpp.modules.base import BaseModule -class EntityCaps: +class EntityCaps(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='presence', diff --git a/nbxmpp/modules/http_auth.py b/nbxmpp/modules/http_auth.py index 5488f77..ab2a45f 100644 --- a/nbxmpp/modules/http_auth.py +++ b/nbxmpp/modules/http_auth.py @@ -15,17 +15,15 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_HTTP_AUTH from nbxmpp.structs import StanzaHandler from nbxmpp.structs import HTTPAuthData - -log = logging.getLogger('nbxmpp.m.http_auth') +from nbxmpp.modules.base import BaseModule -class HTTPAuth: +class HTTPAuth(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) self._client = client self.handlers = [ StanzaHandler(name='message', @@ -39,8 +37,7 @@ class HTTPAuth: priority=40) ] - @staticmethod - def _process_http_auth(_client, stanza, properties): + def _process_http_auth(self, _client, stanza, properties): confirm = stanza.getTag('confirm', namespace=NS_HTTP_AUTH) if confirm is None: return @@ -51,4 +48,5 @@ class HTTPAuth: method = attrs.get('method') url = attrs.get('url') properties.http_auth = HTTPAuthData(id_, method, url, body) - log.info('HTTPAuth received: %s %s %s %s', id_, method, url, body) + self._log.info('HTTPAuth received: %s %s %s %s', + id_, method, url, body) diff --git a/nbxmpp/modules/http_upload.py b/nbxmpp/modules/http_upload.py index f912923..12251a7 100644 --- a/nbxmpp/modules/http_upload.py +++ b/nbxmpp/modules/http_upload.py @@ -15,8 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_HTTPUPLOAD_0 from nbxmpp.protocol import Iq from nbxmpp.protocol import isResultNode @@ -24,15 +22,16 @@ from nbxmpp.structs import HTTPUploadData from nbxmpp.util import call_on_response from nbxmpp.util import callback from nbxmpp.util import raise_error +from nbxmpp.modules.base import BaseModule ALLOWED_HEADERS = ['Authorization', 'Cookie', 'Expires'] -log = logging.getLogger('nbxmpp.m.http_upload') - -class HTTPUpload: +class HTTPUpload(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [] @@ -50,32 +49,32 @@ class HTTPUpload: @callback def _received_slot(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) slot = stanza.getTag('slot', namespace=NS_HTTPUPLOAD_0) if slot is None: - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, stanza, 'stanza-malformed', 'No slot node found') put_uri = slot.getTagAttr('put', 'url') if put_uri is None: - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, stanza, 'stanza-malformed', 'No put uri found') get_uri = slot.getTagAttr('get', 'url') if get_uri is None: - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, stanza, 'stanza-malformed', 'No get uri found') headers = {} for header in slot.getTag('put').getTags('header'): name = header.getAttr('name') if name not in ALLOWED_HEADERS: - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, stanza, 'stanza-malformed', 'Not allowed header found: %s' % name) data = header.getData() if '\n' in data: - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, stanza, 'stanza-malformed', 'NNewline in header data found') headers[name] = data diff --git a/nbxmpp/modules/ibb.py b/nbxmpp/modules/ibb.py index 402f5eb..000c07a 100644 --- a/nbxmpp/modules/ibb.py +++ b/nbxmpp/modules/ibb.py @@ -15,8 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import Error as ErrorStanza from nbxmpp.protocol import ERR_BAD_REQUEST from nbxmpp.protocol import ERR_FEATURE_NOT_IMPLEMENTED @@ -32,12 +30,13 @@ from nbxmpp.util import b64encode from nbxmpp.util import call_on_response from nbxmpp.util import callback from nbxmpp.util import raise_error - -log = logging.getLogger('nbxmpp.m.ibb') +from nbxmpp.modules.base import BaseModule -class IBB: +class IBB(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='iq', @@ -68,19 +67,19 @@ class IBB: try: block_size = int(attrs.get('block-size')) except Exception as error: - log.warning(error) - log.warning(stanza) + self._log.warning(error) + self._log.warning(stanza) self._client.send_stanza(ErrorStanza(stanza, ERR_BAD_REQUEST)) raise NodeProcessed if block_size > 65535: - log.warning('Invalid block-size') + self._log.warning('Invalid block-size') self._client.send_stanza(ErrorStanza(stanza, ERR_BAD_REQUEST)) raise NodeProcessed sid = attrs.get('sid') if not sid: - log.warning('Invalid sid') + self._log.warning('Invalid sid') self._client.send_stanza(ErrorStanza(stanza, ERR_BAD_REQUEST)) raise NodeProcessed @@ -95,7 +94,7 @@ class IBB: def _parse_close(self, stanza, close): sid = close.getAttrs().get('sid') if sid is None: - log.warning('Invalid sid') + self._log.warning('Invalid sid') self._client.send_stanza(ErrorStanza(stanza, ERR_BAD_REQUEST)) raise NodeProcessed return IBBData(type='close', sid=sid) @@ -105,21 +104,21 @@ class IBB: sid = attrs.get('sid') if sid is None: - log.warning('Invalid sid') + self._log.warning('Invalid sid') self._client.send_stanza(ErrorStanza(stanza, ERR_BAD_REQUEST)) raise NodeProcessed try: seq = int(attrs.get('seq')) except Exception: - log.exception('Invalid seq') + self._log.exception('Invalid seq') self._client.send_stanza(ErrorStanza(stanza, ERR_BAD_REQUEST)) raise NodeProcessed try: decoded_data = b64decode(data.getData(), return_type=bytes) except Exception: - log.exception('Failed to decode IBB data') + self._log.exception('Failed to decode IBB data') self._client.send_stanza(ErrorStanza(stanza, ERR_BAD_REQUEST)) raise NodeProcessed @@ -157,5 +156,5 @@ class IBB: @callback def _default_response(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) return CommonResult(jid=stanza.getFrom()) diff --git a/nbxmpp/modules/idle.py b/nbxmpp/modules/idle.py index 81870f2..a2b6c03 100644 --- a/nbxmpp/modules/idle.py +++ b/nbxmpp/modules/idle.py @@ -15,17 +15,16 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_IDLE from nbxmpp.structs import StanzaHandler from nbxmpp.modules.date_and_time import parse_datetime - -log = logging.getLogger('nbxmpp.m.idle') +from nbxmpp.modules.base import BaseModule -class Idle: +class Idle(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='presence', @@ -34,21 +33,20 @@ class Idle: priority=15) ] - @staticmethod - def _process_idle(_client, stanza, properties): + def _process_idle(self, _client, stanza, properties): idle_tag = stanza.getTag('idle', namespace=NS_IDLE) if idle_tag is None: return since = idle_tag.getAttr('since') if since is None: - log.warning('No since attr in idle node') - log.warning(stanza) + self._log.warning('No since attr in idle node') + self._log.warning(stanza) return timestamp = parse_datetime(since, convert='utc', epoch=True) if timestamp is None: - log.warning('Invalid timestamp received: %s', since) - log.warning(stanza) + self._log.warning('Invalid timestamp received: %s', since) + self._log.warning(stanza) properties.idle_timestamp = timestamp diff --git a/nbxmpp/modules/iq.py b/nbxmpp/modules/iq.py index 35b92ea..29bf288 100644 --- a/nbxmpp/modules/iq.py +++ b/nbxmpp/modules/iq.py @@ -15,20 +15,19 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import Error as ErrorStanza from nbxmpp.protocol import ERR_BAD_REQUEST from nbxmpp.protocol import NodeProcessed from nbxmpp.structs import StanzaHandler from nbxmpp.util import error_factory from nbxmpp.const import IqType - -log = logging.getLogger('nbxmpp.m.iq') +from nbxmpp.modules.base import BaseModule -class BaseIq: +class BaseIq(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='iq', @@ -40,8 +39,8 @@ class BaseIq: try: properties.type = IqType(stanza.getType()) except ValueError: - log.warning('Message with invalid type: %s', stanza.getType()) - log.warning(stanza) + self._log.warning('Message with invalid type: %s', stanza.getType()) + self._log.warning(stanza) self._client.send_stanza(ErrorStanza(stanza, ERR_BAD_REQUEST)) raise NodeProcessed diff --git a/nbxmpp/modules/location.py b/nbxmpp/modules/location.py index 872014c..6c3e7d3 100644 --- a/nbxmpp/modules/location.py +++ b/nbxmpp/modules/location.py @@ -15,20 +15,19 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_LOCATION from nbxmpp.protocol import NS_PUBSUB_EVENT from nbxmpp.protocol import Node from nbxmpp.structs import StanzaHandler from nbxmpp.structs import LocationData from nbxmpp.const import LOCATION_DATA - -log = logging.getLogger('nbxmpp.m.location') +from nbxmpp.modules.base import BaseModule -class Location: +class Location(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -51,7 +50,8 @@ class Location: location_node = item.getTag('geoloc', namespace=NS_LOCATION) if not location_node.getChildren(): - log.info('Received location: %s - no location set', properties.jid) + self._log.info('Received location: %s - no location set', + properties.jid) return location_dict = {} @@ -59,7 +59,7 @@ class Location: location_dict[node] = location_node.getTagData(node) data = LocationData(**location_dict) pubsub_event = properties.pubsub_event._replace(data=data) - log.info('Received location: %s - %s', properties.jid, data) + self._log.info('Received location: %s - %s', properties.jid, data) properties.pubsub_event = pubsub_event diff --git a/nbxmpp/modules/message.py b/nbxmpp/modules/message.py index 23c4022..a30369d 100644 --- a/nbxmpp/modules/message.py +++ b/nbxmpp/modules/message.py @@ -15,8 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NodeProcessed from nbxmpp.protocol import NS_DATA from nbxmpp.protocol import NS_XHTML @@ -25,12 +23,13 @@ from nbxmpp.structs import StanzaIDData from nbxmpp.structs import XHTMLData from nbxmpp.util import error_factory from nbxmpp.const import MessageType - -log = logging.getLogger('nbxmpp.m.message') +from nbxmpp.modules.base import BaseModule -class BaseMessage: +class BaseMessage(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -71,8 +70,7 @@ class BaseMessage: if properties.type.is_error: properties.error = error_factory(stanza) - @staticmethod - def _process_message_after_base(_client, stanza, properties): + def _process_message_after_base(self, _client, stanza, properties): # This handler runs after decryption handlers had the chance # to decrypt the body properties.body = stanza.getBody() @@ -87,14 +85,13 @@ class BaseMessage: return if xhtml.getTag('body', namespace=NS_XHTML) is None: - log.warning('xhtml without body found') - log.warning(stanza) + self._log.warning('xhtml without body found') + self._log.warning(stanza) return properties.xhtml = XHTMLData(xhtml) - @staticmethod - def _parse_type(stanza): + def _parse_type(self, stanza): type_ = stanza.getType() if type_ is None: return MessageType.NORMAL @@ -102,8 +99,8 @@ class BaseMessage: try: return MessageType(type_) except ValueError: - log.warning('Message with invalid type: %s', type_) - log.warning(stanza) + self._log.warning('Message with invalid type: %s', type_) + self._log.warning(stanza) raise NodeProcessed @staticmethod diff --git a/nbxmpp/modules/mood.py b/nbxmpp/modules/mood.py index 7f02025..41e863e 100644 --- a/nbxmpp/modules/mood.py +++ b/nbxmpp/modules/mood.py @@ -15,8 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_MOOD from nbxmpp.protocol import NS_PUBSUB_EVENT from nbxmpp.protocol import Node @@ -24,12 +22,13 @@ from nbxmpp.protocol import NodeProcessed from nbxmpp.structs import StanzaHandler from nbxmpp.structs import MoodData from nbxmpp.const import MOODS - -log = logging.getLogger('nbxmpp.m.mood') +from nbxmpp.modules.base import BaseModule -class Mood: +class Mood(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -52,7 +51,7 @@ class Mood: mood_node = item.getTag('mood', namespace=NS_MOOD) if not mood_node.getChildren(): - log.info('Received mood: %s - removed mood', properties.jid) + self._log.info('Received mood: %s - removed mood', properties.jid) return mood, text = None, None @@ -64,13 +63,13 @@ class Mood: mood = name if mood is None and mood_node.getPayload(): - log.warning('No valid mood value found') - log.warning(stanza) + self._log.warning('No valid mood value found') + self._log.warning(stanza) raise NodeProcessed data = MoodData(mood, text) pubsub_event = properties.pubsub_event._replace(data=data) - log.info('Received mood: %s - %s', properties.jid, data) + self._log.info('Received mood: %s - %s', properties.jid, data) properties.pubsub_event = pubsub_event diff --git a/nbxmpp/modules/muc.py b/nbxmpp/modules/muc.py index 0792dd4..94a1812 100644 --- a/nbxmpp/modules/muc.py +++ b/nbxmpp/modules/muc.py @@ -15,8 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_MUC_USER from nbxmpp.protocol import NS_MUC from nbxmpp.protocol import NS_CONFERENCE @@ -53,12 +51,13 @@ from nbxmpp.util import call_on_response from nbxmpp.util import callback from nbxmpp.util import raise_error from nbxmpp.modules.dataforms import extend_form - -log = logging.getLogger('nbxmpp.m.muc') +from nbxmpp.modules.base import BaseModule -class MUC: +class MUC(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='presence', @@ -118,8 +117,9 @@ class MUC: try: alternate = JID(alternate) except Exception as error: - log.warning('Invalid alternate JID provided: %s', error) - log.warning(stanza) + self._log.warning('Invalid alternate JID provided: %s', + error) + self._log.warning(stanza) alternate = None properties.muc_destroyed = MucDestroyed( alternate=alternate, @@ -150,9 +150,9 @@ class MUC: try: code = StatusCode(status.getAttr('code')) except ValueError: - log.warning('Received invalid status code: %s', - status.getAttr('code')) - log.warning(stanza) + self._log.warning('Received invalid status code: %s', + status.getAttr('code')) + self._log.warning(stanza) continue if code in message_status_codes: codes.add(code) @@ -178,8 +178,7 @@ class MUC: if address is not None: properties.muc_ofrom = JID(address.getAttr('jid')) - @staticmethod - def _process_message(_client, stanza, properties): + def _process_message(self, _client, stanza, properties): muc_user = stanza.getTag('x', namespace=NS_MUC_USER) if muc_user is None: return @@ -219,9 +218,9 @@ class MUC: try: code = StatusCode(status.getAttr('code')) except ValueError: - log.warning('Received invalid status code: %s', - status.getAttr('code')) - log.warning(stanza) + self._log.warning('Received invalid status code: %s', + status.getAttr('code')) + self._log.warning(stanza) continue if code in message_status_codes: codes.add(code) @@ -291,8 +290,7 @@ class MUC: properties.muc_decline = DeclineData(**data) return - @staticmethod - def _process_voice_request(_client, stanza, properties): + def _process_voice_request(self, _client, stanza, properties): data_form = stanza.getTag('x', namespace=NS_DATA) if data_form is None: return @@ -309,8 +307,8 @@ class MUC: try: jid = JID(data_form['muc#jid'].value) except Exception: - log.warning('Invalid JID on voice request') - log.warning(stanza) + self._log.warning('Invalid JID on voice request') + self._log.warning(stanza) raise NodeProcessed properties.voice_request = VoiceRequest(jid=jid, @@ -336,7 +334,7 @@ class MUC: @callback def _affiliation_received(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) room_jid = stanza.getFrom() query = stanza.getTag('query', namespace=NS_MUC_ADMIN) @@ -346,8 +344,8 @@ class MUC: try: jid = JID(item.getAttr('jid')) except Exception as error: - log.warning('Invalid JID: %s, %s', - item.getAttr('jid'), error) + self._log.warning('Invalid JID: %s, %s', + item.getAttr('jid'), error) continue users_dict[jid] = {} @@ -359,8 +357,8 @@ class MUC: if reason: users_dict[jid]['reason'] = reason - log.info('Affiliations received from %s: %s', - room_jid, users_dict) + self._log.info('Affiliations received from %s: %s', + room_jid, users_dict) return AffiliationResult(jid=room_jid, users=users_dict) @@ -372,8 +370,8 @@ class MUC: destroy.setTagData('reason', reason) if jid: destroy.setAttr('jid', jid) - log.info('Destroy room: %s, reason: %s, alternate: %s', - room_jid, reason, jid) + self._log.info('Destroy room: %s, reason: %s, alternate: %s', + room_jid, reason, jid) return iq @call_on_response('_default_response') @@ -382,7 +380,7 @@ class MUC: query = iq.setQuery() form.setAttr('type', 'submit') query.addChild(node=form) - log.info('Set config for %s', room_jid) + self._log.info('Set config for %s', room_jid) return iq @call_on_response('_config_received') @@ -390,13 +388,13 @@ class MUC: iq = Iq(typ='get', queryNS=NS_MUC_OWNER, to=room_jid) - log.info('Request config for %s', room_jid) + self._log.info('Request config for %s', room_jid) return iq @callback def _config_received(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) jid = stanza.getFrom() payload = stanza.getQueryPayload() @@ -404,7 +402,7 @@ class MUC: for form in payload: if form.getNamespace() == NS_DATA: dataform = extend_form(node=form) - log.info('Config form received for %s', jid) + self._log.info('Config form received for %s', jid) return MucConfigResult(jid=jid, form=dataform) return MucConfigResult(jid=jid) @@ -416,7 +414,7 @@ class MUC: queryNS=NS_MUC_OWNER, payload=cancel, to=room_jid) - log.info('Cancel config for %s', room_jid) + self._log.info('Cancel config for %s', room_jid) return iq @call_on_response('_default_response') @@ -434,7 +432,7 @@ class MUC: if nick is not None: item_tag.setAttr('nick', nick) - log.info('Set affiliation for %s: %s', room_jid, users_dict) + self._log.info('Set affiliation for %s: %s', room_jid, users_dict) return iq @call_on_response('_default_response') @@ -445,12 +443,13 @@ class MUC: item.setAttr('role', role) if reason: item.addChild(name='reason', payload=reason) - log.info('Set role for %s: %s %s %s', room_jid, nick, role, reason) + self._log.info('Set role for %s: %s %s %s', + room_jid, nick, role, reason) return iq def set_subject(self, room_jid, subject): message = Message(room_jid, typ='groupchat', subject=subject) - log.info('Set subject for %s', room_jid) + self._log.info('Set subject for %s', room_jid) self._client.send_stanza(message) def decline(self, room, to, reason=None): @@ -525,7 +524,7 @@ class MUC: @callback def _default_response(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) return CommonResult(jid=stanza.getFrom()) @staticmethod diff --git a/nbxmpp/modules/muclumbus.py b/nbxmpp/modules/muclumbus.py index d749272..feb3af2 100644 --- a/nbxmpp/modules/muclumbus.py +++ b/nbxmpp/modules/muclumbus.py @@ -15,7 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging import json from gi.repository import Soup @@ -33,14 +32,16 @@ from nbxmpp.modules.dataforms import extend_form from nbxmpp.util import call_on_response from nbxmpp.util import callback from nbxmpp.util import raise_error +from nbxmpp.modules.base import BaseModule -log = logging.getLogger('nbxmpp.m.muclumbus') # API Documentation # https://search.jabber.network/docs/api -class Muclumbus: +class Muclumbus(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [] @@ -62,17 +63,17 @@ class Muclumbus: @callback def _parameters_received(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) search = stanza.getTag('search', namespace=NS_MUCLUMBUS) if search is None: - return raise_error(log.warning, stanza, 'stanza-malformed') + return raise_error(self._log.warning, stanza, 'stanza-malformed') dataform = search.getTag('x', namespace=NS_DATA) if dataform is None: - return raise_error(log.warning, stanza, 'stanza-malformed') + return raise_error(self._log.warning, stanza, 'stanza-malformed') - log.info('Muclumbus parameters received') + self._log.info('Muclumbus parameters received') return extend_form(node=dataform) @call_on_response('_search_received') @@ -106,11 +107,11 @@ class Muclumbus: @callback def _search_received(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) result = stanza.getTag('result', namespace=NS_MUCLUMBUS) if result is None: - return raise_error(log.warning, stanza, 'stanza-malformed') + return raise_error(self._log.warning, stanza, 'stanza-malformed') items = result.getTags('item') if not items: @@ -122,14 +123,14 @@ class Muclumbus: set_ = result.getTag('set', namespace=NS_RSM) if set_ is None: - return raise_error(log.warning, stanza, 'stanza-malformed') + return raise_error(self._log.warning, stanza, 'stanza-malformed') first = set_.getTagData('first') last = set_.getTagData('last') try: max_ = int(set_.getTagData('max')) except Exception: - return raise_error(log.warning, stanza, 'stanza-malformed') + return raise_error(self._log.warning, stanza, 'stanza-malformed') results = [] for item in items: @@ -168,7 +169,7 @@ class Muclumbus: soup_body = message.get_property('response-body') if message.status_code != 200: - log.warning(soup_body.data) + self._log.warning(soup_body.data) exec_callback(MuclumbusResult(first=None, last=None, max=None, diff --git a/nbxmpp/modules/nickname.py b/nbxmpp/modules/nickname.py index c9be9bc..4093d8d 100644 --- a/nbxmpp/modules/nickname.py +++ b/nbxmpp/modules/nickname.py @@ -15,19 +15,18 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_NICK from nbxmpp.protocol import NS_PUBSUB_EVENT from nbxmpp.protocol import Node from nbxmpp.structs import StanzaHandler from nbxmpp.const import PresenceType - -log = logging.getLogger('nbxmpp.m.nickname') +from nbxmpp.modules.base import BaseModule -class Nickname: +class Nickname(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -71,10 +70,11 @@ class Nickname: nick = self._parse_nickname(item) if nick is None: - log.info('Received nickname: %s - nickname removed', properties.jid) + self._log.info('Received nickname: %s - nickname removed', + properties.jid) return - log.info('Received nickname: %s - %s', properties.jid, nick) + self._log.info('Received nickname: %s - %s', properties.jid, nick) properties.pubsub_event = properties.pubsub_event._replace(data=nick) @staticmethod diff --git a/nbxmpp/modules/omemo.py b/nbxmpp/modules/omemo.py index ba24d42..29a122d 100644 --- a/nbxmpp/modules/omemo.py +++ b/nbxmpp/modules/omemo.py @@ -15,8 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_OMEMO_TEMP from nbxmpp.protocol import NS_OMEMO_TEMP_DL from nbxmpp.protocol import NS_OMEMO_TEMP_BUNDLE @@ -37,12 +35,13 @@ from nbxmpp.structs import StanzaHandler from nbxmpp.structs import OMEMOMessage from nbxmpp.structs import OMEMOBundle from nbxmpp.modules.pubsub import get_pubsub_request - -log = logging.getLogger('nbxmpp.m.omemo') +from nbxmpp.modules.base import BaseModule -class OMEMO: +class OMEMO(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -58,10 +57,10 @@ class OMEMO: def _process_omemo_message(self, _client, stanza, properties): try: properties.omemo = self._parse_omemo_message(stanza) - log.info('Received message') + self._log.info('Received message') except StanzaMalformed as error: - log.warning(error) - log.warning(stanza) + self._log.warning(error) + self._log.warning(stanza) return @staticmethod @@ -141,18 +140,18 @@ class OMEMO: try: devices = self._parse_devicelist(item) except StanzaMalformed as error: - log.warning(error) - log.warning(stanza) + self._log.warning(error) + self._log.warning(stanza) raise NodeProcessed if not devices: - log.info('Received OMEMO devicelist: %s - no devices set', - properties.jid) + self._log.info('Received OMEMO devicelist: %s - no devices set', + properties.jid) return pubsub_event = properties.pubsub_event._replace(data=devices) - log.info('Received OMEMO devicelist: %s - %s', - properties.jid, devices) + self._log.info('Received OMEMO devicelist: %s - %s', + properties.jid, devices) properties.pubsub_event = pubsub_event @@ -189,7 +188,7 @@ class OMEMO: for device in devicelist: item.addChild('device').setAttr('id', device) - log.info('Set devicelist: %s', devicelist) + self._log.info('Set devicelist: %s', devicelist) jid = self._client.get_bound_jid().getBare() self._client.get_module('PubSub').publish( jid, NS_OMEMO_TEMP_DL, item, id_='current') @@ -198,13 +197,13 @@ class OMEMO: def request_devicelist(self, jid=None): if jid is None: jid = self._client.get_bound_jid().getBare() - log.info('Request devicelist from: %s', jid) + self._log.info('Request devicelist from: %s', jid) return get_pubsub_request(jid, NS_OMEMO_TEMP_DL, max_items=1) @callback def _devicelist_received(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) pubsub_node = stanza.getTag('pubsub') items_node = pubsub_node.getTag('items') @@ -215,12 +214,12 @@ class OMEMO: try: return self._parse_devicelist(item) except StanzaMalformed as error: - return raise_error(log.warning, stanza, + return raise_error(self._log.warning, stanza, 'stanza-malformed', str(error)) def set_bundle(self, bundle, device_id): item = self._create_bundle(bundle) - log.info('Set bundle') + self._log.info('Set bundle') node = '%s:%s' % (NS_OMEMO_TEMP_BUNDLE, device_id) jid = self._client.get_bound_jid().getBare() @@ -279,14 +278,14 @@ class OMEMO: @call_on_response('_bundle_received') def request_bundle(self, jid, device_id): - log.info('Request bundle from: %s %s', jid, device_id) + self._log.info('Request bundle from: %s %s', jid, device_id) node = '%s:%s' % (NS_OMEMO_TEMP_BUNDLE, device_id) return get_pubsub_request(jid, node, max_items=1) @callback def _bundle_received(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) pubsub_node = stanza.getTag('pubsub') items_node = pubsub_node.getTag('items') @@ -295,7 +294,7 @@ class OMEMO: try: return self._parse_bundle(item) except StanzaMalformed as error: - return raise_error(log.warning, stanza, + return raise_error(self._log.warning, stanza, 'stanza-malformed', str(error)) @staticmethod diff --git a/nbxmpp/modules/oob.py b/nbxmpp/modules/oob.py index 0b1f210..e7e4833 100644 --- a/nbxmpp/modules/oob.py +++ b/nbxmpp/modules/oob.py @@ -15,17 +15,16 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_X_OOB from nbxmpp.structs import StanzaHandler from nbxmpp.structs import OOBData - -log = logging.getLogger('nbxmpp.m.oob') +from nbxmpp.modules.base import BaseModule -class OOB: +class OOB(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -41,8 +40,8 @@ class OOB: url = oob.getTagData('url') if url is None: - log.warning('OOB data without url') - log.warning(stanza) + self._log.warning('OOB data without url') + self._log.warning(stanza) return desc = oob.getTagData('desc') diff --git a/nbxmpp/modules/openpgp.py b/nbxmpp/modules/openpgp.py index 40e3d14..5611f32 100644 --- a/nbxmpp/modules/openpgp.py +++ b/nbxmpp/modules/openpgp.py @@ -15,7 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging import time import random import string @@ -41,12 +40,13 @@ from nbxmpp.structs import PGPKeyMetadata from nbxmpp.structs import PGPPublicKey from nbxmpp.modules.date_and_time import parse_datetime from nbxmpp.modules.pubsub import get_pubsub_request +from nbxmpp.modules.base import BaseModule -log = logging.getLogger('nbxmpp.m.openpgp') - -class OpenPGP: +class OpenPGP(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -62,22 +62,22 @@ class OpenPGP: def _process_openpgp_message(self, _client, stanza, properties): openpgp = stanza.getTag('openpgp', namespace=NS_OPENPGP) if openpgp is None: - log.warning('No openpgp node found') - log.warning(stanza) + self._log.warning('No openpgp node found') + self._log.warning(stanza) return data = openpgp.getData() if not data: - log.warning('No data in openpgp node found') - log.warning(stanza) + self._log.warning('No data in openpgp node found') + self._log.warning(stanza) return - log.info('Encrypted message received') + self._log.info('Encrypted message received') try: properties.openpgp = b64decode(data, return_type=bytes) except Exception: - log.warning('b64decode failed') - log.warning(stanza) + self._log.warning('b64decode failed') + self._log.warning(stanza) return def _process_pubsub_openpgp(self, _client, stanza, properties): @@ -110,16 +110,17 @@ class OpenPGP: try: data = self._parse_keylist(properties.jid, item) except StanzaMalformed as error: - log.warning(error) - log.warning(stanza) + self._log.warning(error) + self._log.warning(stanza) raise NodeProcessed if data is None: - log.info('Received PGP keylist: %s - no keys set', properties.jid) + self._log.info('Received PGP keylist: %s - no keys set', + properties.jid) return pubsub_event = properties.pubsub_event._replace(data=data) - log.info('Received PGP keylist: %s - %s', properties.jid, data) + self._log.info('Received PGP keylist: %s - %s', properties.jid, data) properties.pubsub_event = pubsub_event @@ -157,7 +158,7 @@ class OpenPGP: 'date': date} item.addChild('pubkey-metadata', attrs=attrs) - log.info('Set keylist: %s', keylist) + self._log.info('Set keylist: %s', keylist) jid = self._client.get_bound_jid().getBare() self._client.get_module('PubSub').publish( jid, NS_OPENPGP_PK, item, id_='current') @@ -171,14 +172,14 @@ class OpenPGP: data.addData(b64encode(key)) node = '%s:%s' % (NS_OPENPGP_PK, fingerprint) - log.info('Set public key') + self._log.info('Set public key') jid = self._client.get_bound_jid().getBare() self._client.get_module('PubSub').publish( jid, node, item, id_='current') @call_on_response('_public_key_received') def request_public_key(self, jid, fingerprint): - log.info('Request public key from: %s %s', jid, fingerprint) + self._log.info('Request public key from: %s %s', jid, fingerprint) node = '%s:%s' % (NS_OPENPGP_PK, fingerprint) return get_pubsub_request(jid, node, max_items=1) @@ -187,7 +188,7 @@ class OpenPGP: jid = JID(stanza.getFrom().getBare()) if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) pubsub_node = stanza.getTag('pubsub') items_node = pubsub_node.getTag('items') @@ -195,29 +196,29 @@ class OpenPGP: pub_key = item.getTag('pubkey', namespace=NS_OPENPGP) if pub_key is None: - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, stanza, 'stanza-malformed', 'PGP public key has no pubkey node') date = parse_datetime(pub_key.getAttr('date'), epoch=True) data = pub_key.getTag('data') if data is None: - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, stanza, 'stanza-malformed', 'PGP public key has no data node') try: key = b64decode(data.getData(), return_type=bytes) except Exception as error: - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, stanza, 'stanza-malformed', str(error)) key = PGPPublicKey(jid, key, date) - log.info('Received public key: %s %s', key.jid, key.date) + self._log.info('Received public key: %s %s', key.jid, key.date) return key @call_on_response('_keylist_received') def request_keylist(self, jid): - log.info('Request keylist from: %s', jid) + self._log.info('Request keylist from: %s', jid) return get_pubsub_request(jid, NS_OPENPGP_PK, max_items=1) @callback @@ -225,7 +226,7 @@ class OpenPGP: jid = JID(stanza.getFrom().getBare()) if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) pubsub_node = stanza.getTag('pubsub') items_node = pubsub_node.getTag('items') @@ -234,21 +235,21 @@ class OpenPGP: try: keylist = self._parse_keylist(jid, item) except StanzaMalformed as error: - return raise_error(log.warning, stanza, + return raise_error(self._log.warning, stanza, 'stanza-malformed', str(error)) - log.info('Received keylist: %s', keylist) + self._log.info('Received keylist: %s', keylist) return keylist @call_on_response('_secret_key_received') def request_secret_key(self): - log.info('Request secret key') + self._log.info('Request secret key') jid = self._client.get_bound_jid().getBare() return get_pubsub_request(jid, NS_OPENPGP_SK, max_items=1) @callback def _secret_key_received(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) pubsub_node = stanza.getTag('pubsub') items_node = pubsub_node.getTag('items') @@ -256,20 +257,20 @@ class OpenPGP: sec_key = item.getTag('secretkey', namespace=NS_OPENPGP) if sec_key is None: - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, stanza, 'stanza-malformed', 'PGP secretkey node not found') data = sec_key.getData() if not data: - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, stanza, 'stanza-malformed', 'PGP secretkey has no data') try: key = b64decode(data, return_type=bytes) except Exception as error: - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, stanza, 'stanza-malformed', str(error)) - log.info('Received secret key') + self._log.info('Received secret key') return key def set_secret_key(self, secret_key): @@ -277,7 +278,7 @@ class OpenPGP: if secret_key is not None: item.setData(b64encode(secret_key)) - log.info('Set secret key') + self._log.info('Set secret key') jid = self._client.get_bound_jid().getBare() self._client.get_module('PubSub').publish( jid, NS_OPENPGP_SK, item, id_='current') diff --git a/nbxmpp/modules/pgplegacy.py b/nbxmpp/modules/pgplegacy.py index 0f6f458..4ed2cb8 100644 --- a/nbxmpp/modules/pgplegacy.py +++ b/nbxmpp/modules/pgplegacy.py @@ -15,17 +15,16 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_SIGNED from nbxmpp.protocol import NS_ENCRYPTED from nbxmpp.structs import StanzaHandler - -log = logging.getLogger('nbxmpp.m.signed') +from nbxmpp.modules.base import BaseModule -class PGPLegacy: +class PGPLegacy(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -46,19 +45,18 @@ class PGPLegacy: properties.signed = signed.getData() - @staticmethod - def _process_pgplegacy_message(_client, stanza, properties): + def _process_pgplegacy_message(self, _client, stanza, properties): pgplegacy = stanza.getTag('x', namespace=NS_ENCRYPTED) if pgplegacy is None: - log.warning('No x node found') - log.warning(stanza) + self._log.warning('No x node found') + self._log.warning(stanza) return data = pgplegacy.getData() if not data: - log.warning('No data in x node found') - log.warning(stanza) + self._log.warning('No data in x node found') + self._log.warning(stanza) return - log.info('Encrypted message received') + self._log.info('Encrypted message received') properties.pgp_legacy = data diff --git a/nbxmpp/modules/presence.py b/nbxmpp/modules/presence.py index bebb2fa..f6acacc 100644 --- a/nbxmpp/modules/presence.py +++ b/nbxmpp/modules/presence.py @@ -15,8 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import Error as ErrorStanza from nbxmpp.protocol import ERR_BAD_REQUEST from nbxmpp.protocol import NodeProcessed @@ -24,12 +22,13 @@ from nbxmpp.structs import StanzaHandler from nbxmpp.util import error_factory from nbxmpp.const import PresenceType from nbxmpp.const import PresenceShow - -log = logging.getLogger('nbxmpp.m.presence') +from nbxmpp.modules.base import BaseModule -class BasePresence: +class BasePresence(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='presence', @@ -52,8 +51,7 @@ class BasePresence: properties.self_presence = own_jid == properties.jid properties.self_bare = properties.jid.bareMatch(own_jid) - @staticmethod - def _parse_priority(stanza): + def _parse_priority(self, stanza): priority = stanza.getPriority() if priority is None: return 0 @@ -61,13 +59,13 @@ class BasePresence: try: priority = int(priority) except Exception: - log.warning('Invalid priority value: %s', priority) - log.warning(stanza) + self._log.warning('Invalid priority value: %s', priority) + self._log.warning(stanza) return 0 if priority not in range(-129, 128): - log.warning('Invalid priority value: %s', priority) - log.warning(stanza) + self._log.warning('Invalid priority value: %s', priority) + self._log.warning(stanza) return 0 return priority @@ -77,19 +75,18 @@ class BasePresence: try: return PresenceType(type_) except ValueError: - log.warning('Presence with invalid type received') - log.warning(stanza) + self._log.warning('Presence with invalid type received') + self._log.warning(stanza) self._client.send_stanza(ErrorStanza(stanza, ERR_BAD_REQUEST)) raise NodeProcessed - @staticmethod - def _parse_show(stanza): + def _parse_show(self, stanza): show = stanza.getShow() if show is None: return PresenceShow.ONLINE try: return PresenceShow(stanza.getShow()) except ValueError: - log.warning('Presence with invalid show') - log.warning(stanza) + self._log.warning('Presence with invalid show') + self._log.warning(stanza) return PresenceShow.ONLINE diff --git a/nbxmpp/modules/pubsub.py b/nbxmpp/modules/pubsub.py index 06d64e7..fa91eb9 100644 --- a/nbxmpp/modules/pubsub.py +++ b/nbxmpp/modules/pubsub.py @@ -15,8 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_PUBSUB from nbxmpp.protocol import NS_PUBSUB_EVENT from nbxmpp.protocol import NS_PUBSUB_PUBLISH_OPTIONS @@ -35,13 +33,13 @@ from nbxmpp.modules.dataforms import extend_form from nbxmpp.util import call_on_response from nbxmpp.util import callback from nbxmpp.util import raise_error +from nbxmpp.modules.base import BaseModule -log = logging.getLogger('nbxmpp.m.pubsub') - - -class PubSub: +class PubSub(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -79,14 +77,14 @@ class PubSub: return if len(items.getChildren()) != 1: - log.warning('PubSub event with != 1 item') - log.warning(stanza) + self._log.warning('PubSub event with != 1 item') + self._log.warning(stanza) return item = items.getTag('item') if item is None: - log.warning('No item node found') - log.warning(stanza) + self._log.warning('No item node found') + self._log.warning(stanza) return id_ = item.getAttr('id') properties.pubsub_event = PubSubEventData(node, id_, item) @@ -108,7 +106,7 @@ class PubSub: @callback def _publish_result_received(self, stanza): if not isResultNode(stanza): - return raise_error(log.warning, stanza) + return raise_error(self._log.warning, stanza) jid = stanza.getFrom() pubsub = stanza.getTag('pubsub', namespace=NS_PUBSUB) @@ -118,12 +116,12 @@ class PubSub: publish = pubsub.getTag('publish') if publish is None: - return raise_error(log.warning, stanza, 'stanza-malformed') + return raise_error(self._log.warning, stanza, 'stanza-malformed') node = publish.getAttr('node') item = publish.getTag('item') if item is None: - return raise_error(log.warning, stanza, 'stanza-malformed') + return raise_error(self._log.warning, stanza, 'stanza-malformed') id_ = item.getAttr('id') return PubSubPublishResult(jid, node, id_) @@ -141,7 +139,7 @@ class PubSub: @call_on_response('_default_response') def set_node_configuration(self, jid, node, form): - log.info('Set configuration for %s %s', node, jid) + self._log.info('Set configuration for %s %s', node, jid) query = Iq('set', to=jid) pubsub = query.addChild('pubsub', namespace=NS_PUBSUB_OWNER) configure = pubsub.addChild('configure', {'node': node}) @@ -151,7 +149,7 @@ class PubSub: @call_on_response('_node_configuration_received') def get_node_configuration(self, jid, node): - log.info('Request node configuration') + self._log.info('Request node configuration') query = Iq('get', to=jid) pubsub = query.addChild('pubsub', namespace=NS_PUBSUB_OWNER) pubsub.addChild('configure', {'node': node}) @@ -160,17 +158,17 @@ class PubSub: @callback def _node_configuration_received(self, stanza): if not isResultNode(stanza): - return raise_error(log.warning, stanza) + return raise_error(self._log.warning, stanza) jid = stanza.getFrom() pubsub = stanza.getTag('pubsub', namespace=NS_PUBSUB_OWNER) if pubsub is None: - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, stanza, 'stanza-malformed', 'No pubsub node found') configure = pubsub.getTag('configure') if configure is None: - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, stanza, 'stanza-malformed', 'No configure node found') node = configure.getAttr('node') @@ -181,16 +179,16 @@ class PubSub: form_type = dataform.vars.get('FORM_TYPE') if form_type is None or form_type.value != NS_PUBSUB_CONFIG: continue - log.info('Node configuration received from: %s', jid) + self._log.info('Node configuration received from: %s', jid) return PubSubConfigResult(jid=jid, node=node, form=dataform) - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, stanza, 'stanza-malformed', 'No valid form type found') @callback def _default_response(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) return CommonResult(jid=stanza.getFrom()) diff --git a/nbxmpp/modules/receipts.py b/nbxmpp/modules/receipts.py index 2056efe..676e9ad 100644 --- a/nbxmpp/modules/receipts.py +++ b/nbxmpp/modules/receipts.py @@ -15,8 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_RECEIPTS from nbxmpp.protocol import NS_MUC_USER from nbxmpp.protocol import isMucPM @@ -24,12 +22,13 @@ from nbxmpp.protocol import Message from nbxmpp.structs import StanzaHandler from nbxmpp.structs import ReceiptData from nbxmpp.util import generate_id - -log = logging.getLogger('nbxmpp.m.receipts') +from nbxmpp.modules.base import BaseModule -class Receipts: +class Receipts(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -48,8 +47,8 @@ class Receipts: if received is not None: id_ = received.getAttr('id') if id_ is None: - log.warning('Receipt without id attr') - log.warning(stanza) + self._log.warning('Receipt without id attr') + self._log.warning(stanza) return properties.receipt = ReceiptData(received.getName(), id_) diff --git a/nbxmpp/modules/register.py b/nbxmpp/modules/register.py index 3d4d9a9..be84edb 100644 --- a/nbxmpp/modules/register.py +++ b/nbxmpp/modules/register.py @@ -15,8 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_X_OOB from nbxmpp.protocol import NS_DATA from nbxmpp.protocol import NS_REGISTER @@ -34,12 +32,13 @@ from nbxmpp.modules.bits_of_binary import parse_bob_data from nbxmpp.modules.dataforms import extend_form from nbxmpp.modules.dataforms import create_field from nbxmpp.modules.dataforms import SimpleDataForm - -log = logging.getLogger('nbxmpp.m.register') +from nbxmpp.modules.base import BaseModule -class Register: +class Register(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [] @@ -73,7 +72,7 @@ class Register: @callback def _default_response(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) return CommonResult(jid=stanza.getFrom()) @staticmethod @@ -83,8 +82,7 @@ class Register: return oob.getTagData('url') or None return None - @staticmethod - def _parse_form(stanza): + def _parse_form(self, stanza): form = stanza.getQuery().getTag('x', namespace=NS_DATA) if form is None: return None @@ -92,8 +90,8 @@ class Register: form = extend_form(node=form) field = form.vars.get('FORM_TYPE') if field is None: - log.warning('No FORM_TYPE found') - log.warning(stanza) + self._log.warning('No FORM_TYPE found') + self._log.warning(stanza) return None # Invalid urn:xmpp:captcha used by ejabberd @@ -138,12 +136,12 @@ class Register: return ChangePasswordResult(successful=True) if stanza.getQuery() is None: - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) form = get_form(stanza.getQuery(), 'jabber:iq:register:changepassword') if form is None: - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) return ChangePasswordResult(successful=False, form=form) @call_on_response('_default_response') diff --git a/nbxmpp/modules/security_labels.py b/nbxmpp/modules/security_labels.py index ac29d11..b1e812c 100644 --- a/nbxmpp/modules/security_labels.py +++ b/nbxmpp/modules/security_labels.py @@ -15,18 +15,17 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_SECLABEL from nbxmpp.structs import StanzaHandler from nbxmpp.structs import SecurityLabel from nbxmpp.structs import DisplayMarking - -log = logging.getLogger('nbxmpp.m.security_labels') +from nbxmpp.modules.base import BaseModule -class SecurityLabels: +class SecurityLabels(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -46,8 +45,8 @@ class SecurityLabels: label = displaymarking.getData() if not label: - log.warning('No label found') - log.warning(stanza) + self._log.warning('No label found') + self._log.warning(stanza) return fgcolor = displaymarking.getAttr('fgcolor') diff --git a/nbxmpp/modules/software_version.py b/nbxmpp/modules/software_version.py index 23d06b5..aa817c6 100644 --- a/nbxmpp/modules/software_version.py +++ b/nbxmpp/modules/software_version.py @@ -15,8 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_VERSION from nbxmpp.protocol import Iq from nbxmpp.protocol import isResultNode @@ -28,12 +26,13 @@ from nbxmpp.structs import StanzaHandler from nbxmpp.util import call_on_response from nbxmpp.util import callback from nbxmpp.util import raise_error - -log = logging.getLogger('nbxmpp.m.software_version') +from nbxmpp.modules.base import BaseModule -class SoftwareVersion: +class SoftwareVersion(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='iq', @@ -53,19 +52,19 @@ class SoftwareVersion: @call_on_response('_software_version_received') def request_software_version(self, jid): - log.info('Request software version for %s', jid) + self._log.info('Request software version for %s', jid) return Iq(typ='get', to=jid, queryNS=NS_VERSION) @callback def _software_version_received(self, stanza): if not isResultNode(stanza): - return raise_error(log.info, stanza) + return raise_error(self._log.info, stanza) try: return SoftwareVersionResult(*self._parse_info(stanza)) except Exception as error: - log.warning(error) - return raise_error(log.warning, stanza, 'stanza-malformed') + self._log.warning(error) + return raise_error(self._log.warning, stanza, 'stanza-malformed') @staticmethod def _parse_info(stanza): @@ -83,13 +82,13 @@ class SoftwareVersion: self._enabled = True def _answer_request(self, _con, stanza, _properties): - log.info('Request received from %s', stanza.getFrom()) + self._log.info('Request received from %s', stanza.getFrom()) if (not self._enabled or self._name is None or self._version is None): iq = stanza.buildReply('error') iq.addChild(node=ErrorNode(ERR_SERVICE_UNAVAILABLE)) - log.info('Send service-unavailable') + self._log.info('Send service-unavailable') else: iq = stanza.buildReply('result') @@ -98,8 +97,8 @@ class SoftwareVersion: query.setTagData('version', self._version) if self._os is not None: query.setTagData('os', self._os) - log.info('Send software version: %s %s %s', - self._name, self._version, self._os) + self._log.info('Send software version: %s %s %s', + self._name, self._version, self._os) self._client.send_stanza(iq) raise NodeProcessed diff --git a/nbxmpp/modules/tune.py b/nbxmpp/modules/tune.py index c8fde03..9df7398 100644 --- a/nbxmpp/modules/tune.py +++ b/nbxmpp/modules/tune.py @@ -15,20 +15,19 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_TUNE from nbxmpp.protocol import NS_PUBSUB_EVENT from nbxmpp.protocol import Node from nbxmpp.structs import StanzaHandler from nbxmpp.structs import TuneData from nbxmpp.const import TUNE_DATA - -log = logging.getLogger('nbxmpp.m.tune') +from nbxmpp.modules.base import BaseModule -class Tune: +class Tune(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -51,7 +50,7 @@ class Tune: tune_node = item.getTag('tune', namespace=NS_TUNE) if not tune_node.getChildren(): - log.info('Received tune: %s - no tune set', properties.jid) + self._log.info('Received tune: %s - no tune set', properties.jid) return tune_dict = {} @@ -60,7 +59,7 @@ class Tune: data = TuneData(**tune_dict) pubsub_event = properties.pubsub_event._replace(data=data) - log.info('Received tune: %s - %s', properties.jid, data) + self._log.info('Received tune: %s - %s', properties.jid, data) properties.pubsub_event = pubsub_event diff --git a/nbxmpp/modules/user_avatar.py b/nbxmpp/modules/user_avatar.py index b7a33ee..0421a44 100644 --- a/nbxmpp/modules/user_avatar.py +++ b/nbxmpp/modules/user_avatar.py @@ -15,7 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging import base64 from nbxmpp.protocol import NS_AVATAR_DATA @@ -31,12 +30,13 @@ from nbxmpp.util import call_on_response from nbxmpp.util import callback from nbxmpp.util import raise_error from nbxmpp.modules.pubsub import get_pubsub_request +from nbxmpp.modules.base import BaseModule -log = logging.getLogger('nbxmpp.m.user_avatar') - -class UserAvatar: +class UserAvatar(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='message', @@ -59,25 +59,26 @@ class UserAvatar: metadata = item.getTag('metadata', namespace=NS_AVATAR_METADATA) if metadata is None: - log.warning('No metadata node found') - log.warning(stanza) + self._log.warning('No metadata node found') + self._log.warning(stanza) raise NodeProcessed if not metadata.getChildren(): - log.info('Received avatar metadata: %s - no avatar set', - properties.jid) + self._log.info('Received avatar metadata: %s - no avatar set', + properties.jid) return info = metadata.getTags('info', one=True) try: data = AvatarMetaData(**info.getAttrs()) except Exception: - log.warning('Malformed user avatar data') - log.warning(stanza) + self._log.warning('Malformed user avatar data') + self._log.warning(stanza) raise NodeProcessed pubsub_event = properties.pubsub_event._replace(data=data) - log.info('Received avatar metadata: %s - %s', properties.jid, data) + self._log.info('Received avatar metadata: %s - %s', + properties.jid, data) properties.pubsub_event = pubsub_event @@ -92,31 +93,31 @@ class UserAvatar: jid = JID(self._client.get_bound_jid().getBare()) if not isResultNode(stanza): - return raise_error(log.warning, stanza) + return raise_error(self._log.warning, stanza) pubsub_node = stanza.getTag('pubsub') items_node = pubsub_node.getTag('items') item = items_node.getTag('item') if item is None: - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, stanza, 'stanza-malformed', 'No item in node found') sha = item.getAttr('id') data_node = item.getTag('data', namespace=NS_AVATAR_DATA) if data_node is None: - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, stanza, 'stanza-malformed', 'No data node found') data = data_node.getData() if data is None: - return raise_error(log.warning, stanza, 'stanza-malformed', + return raise_error(self._log.warning, stanza, 'stanza-malformed', 'Data node empty') try: data = base64.b64decode(data.encode('utf-8')) except Exception as error: - return raise_error(log.warning, stanza, + return raise_error(self._log.warning, stanza, 'stanza-malformed', str(error)) - log.info('Received avatar data: %s %s', jid, sha) + self._log.info('Received avatar data: %s %s', jid, sha) return AvatarData(jid, sha, data) diff --git a/nbxmpp/modules/vcard_avatar.py b/nbxmpp/modules/vcard_avatar.py index 6e929be..d535ff0 100644 --- a/nbxmpp/modules/vcard_avatar.py +++ b/nbxmpp/modules/vcard_avatar.py @@ -15,18 +15,17 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging - from nbxmpp.protocol import NS_VCARD_UPDATE from nbxmpp.structs import StanzaHandler from nbxmpp.const import PresenceType from nbxmpp.const import AvatarState - -log = logging.getLogger('nbxmpp.m.vcard_avatar') +from nbxmpp.modules.base import BaseModule -class VCardAvatar: +class VCardAvatar(BaseModule): def __init__(self, client): + BaseModule.__init__(self, client) + self._client = client self.handlers = [ StanzaHandler(name='presence', @@ -35,8 +34,7 @@ class VCardAvatar: priority=15) ] - @staticmethod - def _process_avatar(_client, stanza, properties): + def _process_avatar(self, _client, stanza, properties): if properties.type != PresenceType.AVAILABLE: return @@ -47,15 +45,16 @@ class VCardAvatar: avatar_sha = update.getTagData('photo') if avatar_sha is None: properties.avatar_state = AvatarState.NOT_READY - log.info('%s is not ready to promote an avatar', stanza.getFrom()) + self._log.info('%s is not ready to promote an avatar', + stanza.getFrom()) # Empty update element, ignore return if avatar_sha == '': properties.avatar_state = AvatarState.EMPTY - log.info('%s empty avatar advertised', stanza.getFrom()) + self._log.info('%s empty avatar advertised', stanza.getFrom()) return properties.avatar_sha = avatar_sha properties.avatar_state = AvatarState.ADVERTISED - log.info('%s advertises %s', stanza.getFrom(), avatar_sha) + self._log.info('%s advertises %s', stanza.getFrom(), avatar_sha) diff --git a/nbxmpp/smacks.py b/nbxmpp/smacks.py index f1c373a..f2f9efd 100644 --- a/nbxmpp/smacks.py +++ b/nbxmpp/smacks.py @@ -22,6 +22,7 @@ from nbxmpp.protocol import NS_STREAM_MGMT from nbxmpp.protocol import NS_DELAY2 from nbxmpp.simplexml import Node from nbxmpp.const import StreamState +from nbxmpp.util import LogAdapter log = logging.getLogger('nbxmpp.smacks') @@ -36,7 +37,7 @@ class Smacks: number of handled stanzas """ - def __init__(self, client): + def __init__(self, client, log_context): self._client = client self._out_h = 0 # Outgoing stanzas handled self._in_h = 0 # Incoming stanzas handled @@ -58,6 +59,8 @@ class Smacks: self._session_id = None self._location = None + self._log = LogAdapter(log, {'context': log_context}) + self.register_handlers() @property @@ -66,7 +69,7 @@ class Smacks: @sm_supported.setter def sm_supported(self, value): - log.info('Server supports detected: %s', value) + self._log.info('Server supports detected: %s', value) self._sm_supported = value def delegate(self, stanza): @@ -92,12 +95,12 @@ class Smacks: return enable = Node(NS_STREAM_MGMT + ' enable', attrs={'resume': 'true'}) self._client.send_nonza(enable, now=False) - log.debug('Send enable') + self._log.debug('Send enable') self._enable_sent = True def _on_enabled(self, _con, stanza, _properties): if self.enabled: - log.error('Received "enabled", but SM is already enabled') + self._log.error('Received "enabled", but SM is already enabled') return resume = stanza.getAttr('resume') if resume in ('true', 'True', '1'): @@ -106,8 +109,8 @@ class Smacks: self._location = stanza.getAttr('location') self.enabled = True - log.info('Received enabled, location: %s, resume supported: %s, ' - 'session-id: %s', self._location, resume, self._session_id) + self._log.info('Received enabled, location: %s, resume supported: %s, ' + 'session-id: %s', self._location, resume, self._session_id) def count_incoming(self, name): if not self.enabled: @@ -115,7 +118,7 @@ class Smacks: return if name in ('a', 'r', 'resumed', 'enabled'): return - log.debug('IN, %s', name) + self._log.debug('IN, %s', name) self._in_h += 1 def save_in_queue(self, stanza): @@ -132,7 +135,7 @@ class Smacks: attrs['from'] = stanza.getAttr('from') stanza.addChild('delay', namespace=NS_DELAY2, attrs=attrs) self._uqueue.append(stanza) - log.debug('OUT, %s', stanza.getName()) + self._log.debug('OUT, %s', stanza.getName()) self._out_h += 1 if len(self._uqueue) > self.max_queue: @@ -149,7 +152,7 @@ class Smacks: """ if not self._old_uqueue: return - log.info('Resend %s stanzas', len(self._old_uqueue)) + self._log.info('Resend %s stanzas', len(self._old_uqueue)) for stanza in self._old_uqueue: # Use dispatcher so we increment the counter self._client.send_stanza(stanza) @@ -157,7 +160,7 @@ class Smacks: def resume_request(self): if self._session_id is None: - log.error('Attempted to resume without a valid session id') + self._log.error('Attempted to resume without a valid session id') return # Save old messages in an extra "queue" to avoid race conditions @@ -181,8 +184,8 @@ class Smacks: number of stanzas received by the server. Resends stanzas not received by the server in the last session. """ - log.info('Session resumption succeeded, session-id: %s', - self._session_id) + self._log.info('Session resumption succeeded, session-id: %s', + self._session_id) self._validate_ack(stanza, self._old_uqueue) # Set our out h to the h we received self._out_h = int(stanza.getAttr('h')) @@ -195,24 +198,24 @@ class Smacks: def _send_ack(self, *args): ack = Node(NS_STREAM_MGMT + ' a', attrs={'h': self._in_h}) self._acked_h = self._in_h - log.debug('Send ack, h: %s', self._in_h) + self._log.debug('Send ack, h: %s', self._in_h) self._client.send_nonza(ack, now=False) def close_session(self): # We end the connection deliberately # Reset the state -> no resume - log.info('Close session') + self._log.info('Close session') self._reset_state() def _request_ack(self): request = Node(NS_STREAM_MGMT + ' r') - log.debug('Request ack') + self._log.debug('Request ack') self._client.send_nonza(request, now=False) def _on_ack(self, _stream, stanza, _properties): if not self.enabled: return - log.debug('Ack received, h: %s', stanza.getAttr('h')) + self._log.debug('Ack received, h: %s', stanza.getAttr('h')) self._validate_ack(stanza, self._uqueue) def _validate_ack(self, stanza, queue): @@ -223,26 +226,26 @@ class Smacks: """ count_server = stanza.getAttr('h') if count_server is None: - log.error('Server did not send h attribute') + self._log.error('Server did not send h attribute') return count_server = int(count_server) diff = self._out_h - count_server queue_size = len(queue) if diff < 0: - log.error('Mismatch detected, our h: %d, server h: %d, queue: %d', - self._out_h, count_server, queue_size) + self._log.error('Mismatch detected, our h: %d, server h: %d, queue: %d', + self._out_h, count_server, queue_size) # Don't accumulate all messages in this case # (they would otherwise all be resent on the next reconnect) queue = [] elif queue_size < diff: - log.error('Mismatch detected, our h: %d, server h: %d, queue: %d', - self._out_h, count_server, queue_size) + self._log.error('Mismatch detected, our h: %d, server h: %d, queue: %d', + self._out_h, count_server, queue_size) else: - log.debug('Validate ack, our h: %d, server h: %d, queue: %d', - self._out_h, count_server, queue_size) - log.debug('Removing %d stanzas from queue', queue_size - diff) + self._log.debug('Validate ack, our h: %d, server h: %d, queue: %d', + self._out_h, count_server, queue_size) + self._log.debug('Removing %d stanzas from queue', queue_size - diff) while len(queue) > diff: queue.pop(0) @@ -252,19 +255,19 @@ class Smacks: This can be called after 'enable' and 'resume' ''' - log.info('Negotiation failed') + self._log.info('Negotiation failed') error_text = stanza.getTagData('text') if error_text is not None: - log.info(error_text) + self._log.info(error_text) if stanza.getTag('item-not-found') is not None: - log.info('Session timed out, last server h: %s', - stanza.getAttr('h')) + self._log.info('Session timed out, last server h: %s', + stanza.getAttr('h')) self._validate_ack(stanza, self._old_uqueue) else: for tag in stanza.getChildren(): if tag.getName() != 'text': - log.info(tag.getName()) + self._log.info(tag.getName()) if self.resume_in_progress: # Reset state before sending Bind, because otherwise stanza diff --git a/nbxmpp/tcp.py b/nbxmpp/tcp.py index ea3e2d2..e84e073 100644 --- a/nbxmpp/tcp.py +++ b/nbxmpp/tcp.py @@ -86,9 +86,9 @@ class TCPConnection(Connection): remote_address = connection.get_remote_address() use_proxy = self._address.proxy is not None target = 'proxy' if use_proxy else self._address.domain - log.info('Connecting to %s (%s)', - target, - remote_address.to_string()) + self._log.info('Connecting to %s (%s)', + target, + remote_address.to_string()) def _check_certificate(self, _connection, certificate, errors): self._peer_certificate = certificate @@ -118,7 +118,7 @@ class TCPConnection(Connection): else: raise ValueError('Address must be a service or host') except GLib.Error as error: - log.info('Connect Error: %s', error) + self._log.info('Connect Error: %s', error) self._finalize('connection-failed') return @@ -131,9 +131,9 @@ class TCPConnection(Connection): use_proxy = self._address.proxy is not None target = 'proxy' if use_proxy else self._address.domain - log.info('Connected to %s (%s)', - target, - self._con.get_remote_address().to_string()) + self._log.info('Connected to %s (%s)', + target, + self._con.get_remote_address().to_string()) self._on_connected() @@ -151,13 +151,13 @@ class TCPConnection(Connection): self._keepalive_id = GLib.timeout_add_seconds(5, self._send_keepalive) def _send_keepalive(self): - log.info('Send keepalive') + self._log.info('Send keepalive') self._keepalive_id = None if not self._con.get_output_stream().has_pending(): self._write_all_async(' '.encode()) def start_tls_negotiation(self): - log.info('Start TLS negotiation') + self._log.info('Start TLS negotiation') self._tls_handshake_in_progress = True remote_address = self._con.get_remote_address() identity = Gio.NetworkAddress.new(self._address.domain, @@ -199,30 +199,30 @@ class TCPConnection(Connection): quark = GLib.quark_try_string('g-tls-error-quark') if error.matches(quark, Gio.TlsError.MISC): if self._tls_handshake_in_progress: - log.error('Handshake failed: %s', error) + self._log.error('Handshake failed: %s', error) self._finalize('connection-failed') return if error.matches(quark, Gio.TlsError.EOF): - log.info('Incoming stream closed: TLS EOF') + self._log.info('Incoming stream closed: TLS EOF') self._finalize('disconnected') return if error.matches(quark, Gio.TlsError.BAD_CERTIFICATE): - log.info('Certificate Error: %s', error) + self._log.info('Certificate Error: %s', error) self._finalize('disconnected') return - log.error('Read Error: %s', error) + self._log.error('Read Error: %s', error) return data = data.get_data() if not data: if self._state == TCPState.DISCONNECTING: - log.info('Reveived zero data on _read_async()') + self._log.info('Reveived zero data on _read_async()') self._finalize('disconnected') else: - log.warning('Reveived zero data on _read_async()') + self._log.warning('Reveived zero data on _read_async()') return self._renew_keepalive_timer() @@ -235,7 +235,7 @@ class TCPConnection(Connection): try: self.notify('data-received', data) except Exception: - log.exception('Error while executing data-received:') + self._log.exception('Error while executing data-received:') self._read_async() @@ -265,7 +265,7 @@ class TCPConnection(Connection): self._write_stanza_buffer = None return - log.error('Write Error: %s', error) + self._log.error('Write Error: %s', error) return self._renew_keepalive_timer() @@ -282,7 +282,7 @@ class TCPConnection(Connection): try: self.notify('data-sent', data) except Exception: - log.exception('Error while executing data-sent:') + self._log.exception('Error while executing data-sent:') if self._output_closed and not self._write_queue: self._check_for_shutdown() @@ -293,7 +293,7 @@ class TCPConnection(Connection): def send(self, stanza, now=False): if self._state in (TCPState.DISCONNECTED, TCPState.DISCONNECTING): - log.warning('send() not possible in state: %s', self._state) + self._log.warning('send() not possible in state: %s', self._state) return if now: @@ -312,7 +312,7 @@ class TCPConnection(Connection): return if self._state in (TCPState.DISCONNECTED, TCPState.DISCONNECTING): - log.warning('Called disconnect on state: %s', self._state) + self._log.warning('Called disconnect on state: %s', self._state) return self.state = TCPState.DISCONNECTING @@ -324,7 +324,7 @@ class TCPConnection(Connection): def shutdown_input(self): self._remove_keepalive_timer() - log.info('Shutdown input') + self._log.info('Shutdown input') self._input_closed = True self._read_cancellable.cancel() self._check_for_shutdown() @@ -332,7 +332,7 @@ class TCPConnection(Connection): def shutdown_output(self): self._remove_keepalive_timer() self.state = TCPState.DISCONNECTING - log.info('Shutdown output') + self._log.info('Shutdown output') self._output_closed = True def _finalize(self, signal_name): @@ -341,7 +341,7 @@ class TCPConnection(Connection): try: self._con.get_socket().shutdown(True, True) except GLib.Error as error: - log.info(error) + self._log.info(error) self.state = TCPState.DISCONNECTED self.notify(signal_name) self.destroy() diff --git a/nbxmpp/util.py b/nbxmpp/util.py index 5d463a0..10b0566 100644 --- a/nbxmpp/util.py +++ b/nbxmpp/util.py @@ -15,7 +15,6 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. -import logging import base64 import weakref import hashlib @@ -23,6 +22,8 @@ import uuid import binascii import os import re +import logging +from logging import LoggerAdapter from collections import defaultdict from functools import wraps @@ -490,3 +491,12 @@ class Observable: callbacks = self._callbacks.get(signal_name, []) for func in callbacks: func(self, signal_name, *args, **kwargs) + + +class LogAdapter(LoggerAdapter): + + def set_context(self, context): + self.extra['context'] = context + + def process(self, msg, kwargs): + return '(%s) %s' % (self.extra['context'], msg), kwargs diff --git a/nbxmpp/websocket.py b/nbxmpp/websocket.py index 983d735..43e6ef2 100644 --- a/nbxmpp/websocket.py +++ b/nbxmpp/websocket.py @@ -37,7 +37,7 @@ class WebsocketConnection(Connection): self._session = Soup.Session() self._session.props.ssl_strict = False - if log.getEffectiveLevel() == logging.INFO: + if self._log.getEffectiveLevel() == logging.INFO: self._session.add_feature( Soup.Logger.new(Soup.LoggerLogLevel.BODY, -1)) @@ -48,7 +48,7 @@ class WebsocketConnection(Connection): self._output_closed = False def connect(self): - log.info('Try to connect to %s', self._address.uri) + self._log.info('Try to connect to %s', self._address.uri) self.state = TCPState.CONNECTING @@ -72,7 +72,7 @@ class WebsocketConnection(Connection): self._finalize('disconnected') return - log.info('Connection Error: %s', error) + self._log.info('Connection Error: %s', error) self._finalize('connection-failed') return @@ -111,31 +111,31 @@ class WebsocketConnection(Connection): self._log_stanza(data) if self._input_closed: - log.warning('Received data after stream closed') + self._log.warning('Received data after stream closed') return self.notify('data-received', data) @staticmethod def _on_websocket_pong(_websocket, _message): - log.info('Pong received') + self._log.info('Pong received') def _on_websocket_closed(self, websocket): - log.info('Closed %s', get_websocket_close_string(websocket)) + self._log.info('Closed %s', get_websocket_close_string(websocket)) self._finalize('disconnected') @staticmethod def _on_websocket_closing(_websocket): - log.info('Closing') + self._log.info('Closing') def _on_websocket_error(self, _websocket, error): - log.error(error) + self._log.error(error) if self._state not in (TCPState.DISCONNECTED, TCPState.DISCONNECTING): self._finalize('disconnected') def send(self, stanza, now=False): if self._state in (TCPState.DISCONNECTED, TCPState.DISCONNECTING): - log.warning('send() not possible in state: %s', self._state) + self._log.warning('send() not possible in state: %s', self._state) return data = str(stanza) @@ -150,7 +150,7 @@ class WebsocketConnection(Connection): return if self._state in (TCPState.DISCONNECTED, TCPState.DISCONNECTING): - log.warning('Called disconnect on state: %s', self._state) + self._log.warning('Called disconnect on state: %s', self._state) return self._websocket.close(Soup.WebsocketCloseCode.NORMAL, None) @@ -161,13 +161,13 @@ class WebsocketConnection(Connection): self._websocket.close(Soup.WebsocketCloseCode.NORMAL, None) def shutdown_input(self): - log.info('Shutdown input') + self._log.info('Shutdown input') self._input_closed = True self._check_for_shutdown() def shutdown_output(self): self.state = TCPState.DISCONNECTING - log.info('Shutdown output') + self._log.info('Shutdown output') self._output_closed = True def _finalize(self, signal_name): |