Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Module Level Logging #49

Closed
wants to merge 2 commits into from

1 participant

@jbuckner

All of the logging was using logging.warn(), calling the logging library directly. This caused the logs to be logged to the root logger, thereby making it difficult to selectively filter the logs it produced.

I added log = logging.getLogger(__name__) to each logging file and changed the logging statements to log.{LOG LEVEL}("message") so they'd log to the appropriate logger.

I also cleaned up some of the logging.

jbuckner and others added some commits
@jbuckner jbuckner closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Nov 5, 2012
  1. @jbuckner

    Merge pull request #1 from openid/master

    jbuckner authored
    Python OpenID Server Logging and Updates
Commits on Nov 6, 2012
  1. change from root-level logging to module-level logging so we can filt…

    Jason Buckner authored
    …er appropriately
This page is out of date. Refresh to see the latest.
View
13 background-associations.txt
@@ -71,21 +71,24 @@ could make the background fetcher listen for inserts into the queue.
The background fetcher needs to do something similar to the following::
+ import logging
+ log = logging.getLogger(__name__)
+
def refresh(consumer, endpoint):
if consumer.store.getAssociation(endpoint.server_url):
- logging.info("We don't need to associate with %r", endpoint.server_url)
+ log.info("We don't need to associate with %r" % endpoint.server_url)
return
- logging.info("Associating with %r", endpoint.server_url)
+ log.info("Associating with %r" % endpoint.server_url)
now = time.time()
assoc = consumer._negotiateAssociation(endpoint)
if assoc:
elapsed = time.time() - now
- logging.info('(%0.2f seconds) Associated with %r', elapsed,
- endpoint.server_url)
+ log.info('(%0.2f seconds) Associated with %r' % (elapsed,
+ endpoint.server_url))
consumer.store.storeAssociation(endpoint.server_url, assoc)
else:
- logging.error('Failed to make an association with %r',
+ log.error('Failed to make an association with %r' %
endpoint.server_url)
The code in this example logs the amount of time that the association
View
65 openid/consumer/consumer.py
@@ -213,6 +213,7 @@
'SUCCESS', 'FAILURE', 'CANCEL', 'SETUP_NEEDED',
]
+log = logging.getLogger(__name__)
def makeKVPost(request_message, server_url):
"""Make a Direct Request to an OpenID Provider and return the
@@ -663,7 +664,7 @@ def _checkReturnTo(self, message, return_to):
try:
self._verifyReturnToArgs(message.toPostArgs())
except ProtocolError, why:
- logging.exception("Verifying return_to arguments: %s" % (why[0],))
+ log.exception("Verifying return_to arguments: %s" % why[0])
return False
# Check the return_to base URL against the one in the message.
@@ -729,7 +730,7 @@ def _doIdRes(self, message, endpoint, return_to):
# Verify discovery information:
endpoint = self._verifyDiscoveryResults(message, endpoint)
- logging.info("Received id_res response from %s using association %s" %
+ log.info("Received id_res response from %s using association %s" %
(endpoint.server_url,
message.getArg(OPENID_NS, 'assoc_handle')))
@@ -923,7 +924,7 @@ def _verifyDiscoveryResultsOpenID2(self, resp_msg, endpoint):
# endpoints and responses that didn't match the original
# request.
if not endpoint:
- logging.info('No pre-discovered information supplied.')
+ log.info('No pre-discovered information supplied.')
endpoint = self._discoverAndVerify(to_match.claimed_id, [to_match])
else:
# The claimed ID matches, so we use the endpoint that we
@@ -932,10 +933,9 @@ def _verifyDiscoveryResultsOpenID2(self, resp_msg, endpoint):
try:
self._verifyDiscoverySingle(endpoint, to_match)
except ProtocolError, e:
- logging.exception(
- "Error attempting to use stored discovery information: " +
- str(e))
- logging.info("Attempting discovery to verify endpoint")
+ log.exception(
+ "Error attempting to use stored discovery information: %s" % str(e))
+ log.info("Attempting discovery to verify endpoint")
endpoint = self._discoverAndVerify(
to_match.claimed_id, [to_match])
@@ -977,9 +977,9 @@ def _verifyDiscoveryResultsOpenID1(self, resp_msg, endpoint):
except TypeURIMismatch:
self._verifyDiscoverySingle(endpoint, to_match_1_0)
except ProtocolError, e:
- logging.exception("Error attempting to use stored discovery information: " +
- str(e))
- logging.info("Attempting discovery to verify endpoint")
+ log.exception(
+ "Error attempting to use stored discovery information: %s" % str(e))
+ log.info("Attempting discovery to verify endpoint")
else:
return endpoint
@@ -1049,7 +1049,7 @@ def _discoverAndVerify(self, claimed_id, to_match_endpoints):
@raises DiscoveryFailure: when discovery fails.
"""
- logging.info('Performing discovery on %s' % (claimed_id,))
+ log.info('Performing discovery on %s' % (claimed_id,))
_, services = self._discover(claimed_id)
if not services:
raise DiscoveryFailure('No OpenID information found at %s' %
@@ -1076,10 +1076,10 @@ def _verifyDiscoveredServices(self, claimed_id, services, to_match_endpoints):
# succeeded. Return this endpoint.
return endpoint
else:
- logging.error('Discovery verification failure for %s' %
+ log.error('Discovery verification failure for %s' %
(claimed_id,))
for failure_message in failure_messages:
- logging.error(' * Endpoint mismatch: ' + failure_message)
+ log.error(' * Endpoint mismatch: %s' % failure_message)
raise DiscoveryFailure(
'No matching endpoint found after discovering %s'
@@ -1091,14 +1091,14 @@ def _checkAuth(self, message, server_url):
@returns: True if the request is valid.
@rtype: bool
"""
- logging.info('Using OpenID check_authentication')
+ log.info('Using OpenID check_authentication')
request = self._createCheckAuthRequest(message)
if request is None:
return False
try:
response = self._makeKVPost(request, server_url)
except (fetchers.HTTPFetchingError, ServerError), e:
- logging.exception('check_authentication failed: %s' % (e[0],))
+ log.exception('check_authentication failed: %s' % e[0])
return False
else:
return self._processCheckAuthResponse(response, server_url)
@@ -1110,12 +1110,12 @@ def _createCheckAuthRequest(self, message):
signed = message.getArg(OPENID_NS, 'signed')
if signed:
for k in signed.split(','):
- logging.info(k)
+ log.info(k)
val = message.getAliasedArg(k)
# Signed value is missing
if val is None:
- logging.info('Missing signed field %r' % (k,))
+ log.info('Missing signed field %r' % k)
return None
check_auth_message = message.copy()
@@ -1130,10 +1130,10 @@ def _processCheckAuthResponse(self, response, server_url):
invalidate_handle = response.getArg(OPENID_NS, 'invalidate_handle')
if invalidate_handle is not None:
- logging.info(
- 'Received "invalidate_handle" from server %s' % (server_url,))
+ log.info(
+ 'Received "invalidate_handle" from server %s' % server_url)
if self.store is None:
- logging.error('Unexpectedly got invalidate_handle without '
+ log.error('Unexpectedly got invalidate_handle without '
'a store!')
else:
self.store.removeAssociation(server_url, invalidate_handle)
@@ -1141,7 +1141,7 @@ def _processCheckAuthResponse(self, response, server_url):
if is_valid == 'true':
return True
else:
- logging.error('Server responds that checkAuth call is not valid')
+ log.error('Server responds that checkAuth call is not valid')
return False
def _getAssociation(self, endpoint):
@@ -1194,7 +1194,7 @@ def _negotiateAssociation(self, endpoint):
except ServerError, why:
# Do not keep trying, since it rejected the
# association type that it told us to use.
- logging.error('Server %s refused its suggested association '
+ log.error('Server %s refused its suggested association '
'type: session_type=%s, assoc_type=%s'
% (endpoint.server_url, session_type,
assoc_type))
@@ -1217,7 +1217,7 @@ def _extractSupportedAssociationType(self, server_error, endpoint,
# should be considered a total failure.
if server_error.error_code != 'unsupported-type' or \
server_error.message.isOpenID1():
- logging.error(
+ log.error(
'Server error when requesting an association from %r: %s'
% (endpoint.server_url, server_error.error_text))
return None
@@ -1225,7 +1225,7 @@ def _extractSupportedAssociationType(self, server_error, endpoint,
# The server didn't like the association/session type
# that we sent, and it sent us back a message that
# might tell us how to handle it.
- logging.error(
+ log.error(
'Unsupported association type %s: %s' % (assoc_type,
server_error.error_text,))
@@ -1235,13 +1235,13 @@ def _extractSupportedAssociationType(self, server_error, endpoint,
session_type = server_error.message.getArg(OPENID_NS, 'session_type')
if assoc_type is None or session_type is None:
- logging.error('Server responded with unsupported association '
+ log.error('Server responded with unsupported association '
'session but did not supply a fallback.')
return None
elif not self.negotiator.isAllowed(assoc_type, session_type):
fmt = ('Server sent unsupported session/association type: '
'session_type=%s, assoc_type=%s')
- logging.error(fmt % (session_type, assoc_type))
+ log.error(fmt % (session_type, assoc_type))
return None
else:
return assoc_type, session_type
@@ -1262,17 +1262,17 @@ def _requestAssociation(self, endpoint, assoc_type, session_type):
try:
response = self._makeKVPost(args, endpoint.server_url)
except fetchers.HTTPFetchingError, why:
- logging.exception('openid.associate request failed: %s' % (why[0],))
+ log.exception('openid.associate request failed: %s' % why[0])
return None
try:
assoc = self._extractAssociation(response, assoc_session)
except KeyError, why:
- logging.exception('Missing required parameter in response from %s: %s'
+ log.exception('Missing required parameter in response from %s: %s'
% (endpoint.server_url, why[0]))
return None
except ProtocolError, why:
- logging.exception('Protocol error parsing response from %s: %s' % (
+ log.exception('Protocol error parsing response from %s: %s' % (
endpoint.server_url, why[0]))
return None
else:
@@ -1349,8 +1349,7 @@ def _getOpenID1SessionType(self, assoc_response):
# OpenID 1, but we'll accept it anyway, while issuing a
# warning.
if session_type == 'no-encryption':
- logging.warn('OpenID server sent "no-encryption"'
- 'for OpenID 1.X')
+ log.warn('OpenID server sent "no-encryption" for OpenID 1.X')
# Missing or empty session type is the way to flag a
# 'no-encryption' response. Change the session type to
@@ -1600,7 +1599,7 @@ def getMessage(self, realm, return_to=None, immediate=False):
else:
assoc_log_msg = 'using stateless mode.'
- logging.info("Generated %s request to %s %s" %
+ log.info("Generated %s request to %s %s" %
(mode, self.endpoint.server_url, assoc_log_msg))
return message
@@ -1780,7 +1779,7 @@ def getSignedNS(self, ns_uri):
for key in msg_args.iterkeys():
if not self.isSigned(ns_uri, key):
- logging.info("SuccessResponse.getSignedNS: (%s, %s) not signed."
+ log.info("SuccessResponse.getSignedNS: (%s, %s) not signed."
% (ns_uri, key))
return None
View
4 openid/consumer/discover.py
@@ -37,6 +37,8 @@
from openid.message import OPENID1_NS as OPENID_1_0_MESSAGE_NS
from openid.message import OPENID2_NS as OPENID_2_0_MESSAGE_NS
+log = logging.getLogger(__name__)
+
class OpenIDServiceEndpoint(object):
"""Object representing an OpenID service endpoint.
@@ -426,7 +428,7 @@ def discoverXRI(iname):
for service_element in services:
endpoints.extend(flt.getServiceEndpoints(iname, service_element))
except XRDSError:
- logging.exception('xrds error on ' + iname)
+ log.exception('xrds error on %s' % iname)
for endpoint in endpoints:
# Is there a way to pass this through the filter to the endpoint
View
4 openid/extensions/sreg.py
@@ -69,6 +69,8 @@
'timezone':'Time Zone',
}
+log = logging.getLogger(__name__)
+
def checkFieldName(field_name):
"""Check to see that the given value is a valid simple
registration data field name.
@@ -95,7 +97,7 @@ def checkFieldName(field_name):
try:
registerNamespaceAlias(ns_uri_1_1, 'sreg')
except NamespaceAliasRegistrationError, e:
- logging.exception('registerNamespaceAlias(%r, %r) failed: %s' % (ns_uri_1_1,
+ log.exception('registerNamespaceAlias(%r, %r) failed: %s' % (ns_uri_1_1,
'sreg', str(e),))
def supportsSReg(endpoint):
View
6 openid/kvform.py
@@ -3,6 +3,8 @@
import types
import logging
+log = logging.getLogger(__name__)
+
class KVFormError(ValueError):
pass
@@ -21,7 +23,7 @@ def err(msg):
if strict:
raise KVFormError(formatted)
else:
- logging.warn(formatted)
+ log.warn(formatted)
lines = []
for k, v in seq:
@@ -72,7 +74,7 @@ def err(msg):
if strict:
raise KVFormError(formatted)
else:
- logging.warn(formatted)
+ log.warn(formatted)
lines = data.split('\n')
if lines[-1]:
View
15 openid/oidutil.py
@@ -8,8 +8,6 @@
__all__ = ['log', 'appendArgs', 'toBase64', 'fromBase64', 'autoSubmitHTML', 'toUnicode']
import binascii
-import sys
-import urlparse
import logging
from urllib import urlencode
@@ -22,6 +20,8 @@
'elementtree.ElementTree',
]
+log = logging.getLogger(__name__)
+
def toUnicode(value):
"""Returns the given argument as a unicode object.
@@ -73,13 +73,14 @@ def importElementTree(module_names=None):
pass
else:
# Make sure it can actually parse XML
+ xml_test = '<unused/>'
try:
- ElementTree.XML('<unused/>')
+ ElementTree.XML(xml_test)
except (SystemExit, MemoryError, AssertionError):
raise
except:
- logging.exception('Not using ElementTree library %r because it failed to '
- 'parse a trivial document: %s' % mod_name)
+ log.exception('Not using ElementTree library %r because it failed to '
+ 'parse a trivial document: %s' % (mod_name, xml_test))
else:
return ElementTree
else:
@@ -91,7 +92,7 @@ def importElementTree(module_names=None):
def log(message, level=0):
"""Handle a log message from the OpenID library.
- This is a legacy function which redirects to logging.error.
+ This is a legacy function which redirects to log.error.
The logging module should be used instead of this
@param message: A string containing a debugging message from the
@@ -106,7 +107,7 @@ def log(message, level=0):
@returns: Nothing.
"""
- logging.error("This is a legacy log message, please use the "
+ log.error("This is a legacy log message, please use the "
"logging module. Message: %s", message)
def appendArgs(url, args):
View
15 openid/server/server.py
@@ -143,6 +143,8 @@
UNUSED = None
+log = logging.getLogger(__name__)
+
class OpenIDRequest(object):
"""I represent an incoming OpenID request.
@@ -421,8 +423,8 @@ def fromMessage(klass, message, op_endpoint=UNUSED):
if message.isOpenID1():
session_type = message.getArg(OPENID_NS, 'session_type')
if session_type == 'no-encryption':
- logging.warn('Received OpenID 1 request with a no-encryption '
- 'assocaition session type. Continuing anyway.')
+ log.warn('Received OpenID 1 request with a no-encryption '
+ 'association session type. Continuing anyway.')
elif not session_type:
session_type = 'no-encryption'
else:
@@ -1171,15 +1173,14 @@ def verify(self, assoc_handle, message):
"""
assoc = self.getAssociation(assoc_handle, dumb=True)
if not assoc:
- logging.error("failed to get assoc with handle %r to verify "
- "message %r"
- % (assoc_handle, message))
+ log.error("failed to get assoc with handle %r to verify "
+ "message %r" % (assoc_handle, message))
return False
try:
valid = assoc.checkMessageSignature(message)
except ValueError, ex:
- logging.exception("Error in verifying %s with %s: %s" % (message,
+ log.exception("Error in verifying %s with %s: %s" % (message,
assoc,
ex))
return False
@@ -1286,7 +1287,7 @@ def getAssociation(self, assoc_handle, dumb, checkExpiration=True):
key = self._normal_key
assoc = self.store.getAssociation(key, assoc_handle)
if assoc is not None and assoc.expiresIn <= 0:
- logging.info("requested %sdumb key %r is expired (by %s seconds)" %
+ log.info("requested %sdumb key %r is expired (by %s seconds)" %
((not dumb) and 'not-' or '',
assoc_handle, assoc.expiresIn))
if checkExpiration:
View
6 openid/server/trustroot.py
@@ -24,6 +24,8 @@
import re
import logging
+log = logging.getLogger(__name__)
+
############################################
_protocols = ['http', 'https']
_top_level_domains = [
@@ -443,12 +445,12 @@ def verifyReturnTo(realm_str, return_to, _vrfy=getAllowedReturnURLs):
try:
allowable_urls = _vrfy(realm.buildDiscoveryURL())
except RealmVerificationRedirected, err:
- logging.exception(str(err))
+ log.exception(str(err))
return False
if returnToMatches(allowable_urls, return_to):
return True
else:
- logging.error("Failed to validate return_to %r for realm %r, was not "
+ log.error("Failed to validate return_to %r for realm %r, was not "
"in %s" % (return_to, realm_str, allowable_urls))
return False
View
4 openid/store/filestore.py
@@ -59,6 +59,8 @@ def mkstemp(dir):
else:
_isFilenameSafe = set(_filename_allowed).__contains__
+log = logging.getLogger(__name__)
+
def _safe64(s):
h64 = oidutil.toBase64(cryptutil.sha1(s))
h64 = h64.replace('+', '_')
@@ -372,7 +374,7 @@ def _allAssocs(self):
association_file = file(association_filename, 'rb')
except IOError, why:
if why.errno == ENOENT:
- logging.exception("%s disappeared during %s._allAssocs" % (
+ log.exception("%s disappeared during %s._allAssocs" % (
association_filename, self.__class__.__name__))
else:
raise
Something went wrong with that request. Please try again.