Skip to content

Commit

Permalink
logger = logging.getLogger(__name__)
Browse files Browse the repository at this point in the history
  • Loading branch information
kuba committed Jun 25, 2015
1 parent 865d907 commit 4ce4e2f
Show file tree
Hide file tree
Showing 25 changed files with 207 additions and 148 deletions.
4 changes: 2 additions & 2 deletions .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ required-attributes=
bad-functions=map,filter,apply,input,file

# Good variable names which should always be accepted, separated by a comma
good-names=f,i,j,k,ex,Run,_,fd
good-names=f,i,j,k,ex,Run,_,fd,logger

# Bad variable names which should always be refused, separated by a comma
bad-names=foo,bar,baz,toto,tutu,tata
Expand Down Expand Up @@ -173,7 +173,7 @@ notes=FIXME,XXX,TODO

# Logging modules to check that the string format arguments are in logging
# function parameter format
logging-modules=logging
logging-modules=logging,logger


[VARIABLES]
Expand Down
24 changes: 13 additions & 11 deletions acme/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
from acme import messages


logger = logging.getLogger(__name__)

# https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning
requests.packages.urllib3.contrib.pyopenssl.inject_into_urllib3()

Expand Down Expand Up @@ -54,7 +56,7 @@ def _wrap_in_jws(self, obj, nonce):
"""
dumps = obj.json_dumps()
logging.debug('Serialized JSON: %s', dumps)
logger.debug('Serialized JSON: %s', dumps)
return jws.JWS.sign(
payload=dumps, key=self.key, alg=self.alg, nonce=nonce).json_dumps()

Expand All @@ -77,8 +79,8 @@ def _check_response(cls, response, content_type=None):
:raises .ClientError: In case of other networking errors.
"""
logging.debug('Received response %s (headers: %s): %r',
response, response.headers, response.content)
logger.debug('Received response %s (headers: %s): %r',
response, response.headers, response.content)

response_ct = response.headers.get('Content-Type')
try:
Expand All @@ -91,7 +93,7 @@ def _check_response(cls, response, content_type=None):
if not response.ok:
if jobj is not None:
if response_ct != cls.JSON_ERROR_CONTENT_TYPE:
logging.debug(
logger.debug(
'Ignoring wrong Content-Type (%r) for JSON Error',
response_ct)
try:
Expand All @@ -104,7 +106,7 @@ def _check_response(cls, response, content_type=None):
raise errors.ClientError(response)
else:
if jobj is not None and response_ct != cls.JSON_CONTENT_TYPE:
logging.debug(
logger.debug(
'Ignoring wrong Content-Type (%r) for JSON decodable '
'response', response_ct)

Expand All @@ -121,7 +123,7 @@ def _get(self, uri, content_type=JSON_CONTENT_TYPE, **kwargs):
:rtype: `requests.Response`
"""
logging.debug('Sending GET request to %s', uri)
logger.debug('Sending GET request to %s', uri)
kwargs.setdefault('verify', self.verify_ssl)
try:
response = requests.get(uri, **kwargs)
Expand All @@ -135,7 +137,7 @@ def _add_nonce(self, response):
nonce = response.headers[self.REPLAY_NONCE_HEADER]
error = jws.Header.validate_nonce(nonce)
if error is None:
logging.debug('Storing nonce: %r', nonce)
logger.debug('Storing nonce: %r', nonce)
self._nonces.add(nonce)
else:
raise errors.ClientError('Invalid nonce ({0}): {1}'.format(
Expand All @@ -147,7 +149,7 @@ def _add_nonce(self, response):

def _get_nonce(self, uri):
if not self._nonces:
logging.debug('Requesting fresh nonce by sending HEAD to %s', uri)
logger.debug('Requesting fresh nonce by sending HEAD to %s', uri)
self._add_nonce(requests.head(uri))
return self._nonces.pop()

Expand All @@ -164,7 +166,7 @@ def _post(self, uri, obj, content_type=JSON_CONTENT_TYPE, **kwargs):
"""
data = self._wrap_in_jws(obj, self._get_nonce(uri))
logging.debug('Sending POST data to %s: %s', uri, data)
logger.debug('Sending POST data to %s: %s', uri, data)
kwargs.setdefault('verify', self.verify_ssl)
try:
response = requests.post(uri, data=data, **kwargs)
Expand Down Expand Up @@ -394,7 +396,7 @@ def request_issuance(self, csr, authzrs):
"""
assert authzrs, "Authorizations list is empty"
logging.debug("Requesting issuance...")
logger.debug("Requesting issuance...")

# TODO: assert len(authzrs) == number of SANs
req = messages.CertificateRequest(
Expand Down Expand Up @@ -458,7 +460,7 @@ def poll_and_request_issuance(self, csr, authzrs, mintime=5):
now = datetime.datetime.now()
if when > now:
seconds = (when - now).seconds
logging.debug('Sleeping for %d seconds', seconds)
logger.debug('Sleeping for %d seconds', seconds)
time.sleep(seconds)

# Note that we poll with the latest updated Authorization
Expand Down
5 changes: 4 additions & 1 deletion acme/jose/json_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
from acme.jose import util


logger = logging.getLogger(__name__)


class Field(object):
"""JSON object field.
Expand Down Expand Up @@ -233,7 +236,7 @@ def fields_to_partial_json(self):
slot, value, error))
if omitted:
# pylint: disable=star-args
logging.debug('Omitted empty fields: %s', ', '.join(
logger.debug('Omitted empty fields: %s', ', '.join(
'{0!s}={1!r}'.format(*field) for field in omitted))
return jobj

Expand Down
5 changes: 4 additions & 1 deletion acme/other.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
from acme import jose


logger = logging.getLogger(__name__)


class Signature(jose.JSONObjectWithFields):
"""ACME signature.
Expand Down Expand Up @@ -54,7 +57,7 @@ def from_msg(cls, msg, key, nonce=None, nonce_size=None, alg=jose.RS256):

msg_with_nonce = nonce + msg
sig = alg.sign(key, nonce + msg)
logging.debug('%s signed as %s', msg_with_nonce, sig)
logger.debug('%s signed as %s', msg_with_nonce, sig)

return cls(alg=alg, sig=sig, nonce=nonce,
jwk=alg.kty(key=key.publickey()))
Expand Down
5 changes: 4 additions & 1 deletion letsencrypt/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
from letsencrypt.display import util as display_util


logger = logging.getLogger(__name__)


class Account(object):
"""ACME protocol registration.
Expand Down Expand Up @@ -226,5 +229,5 @@ def safe_email(cls, email):
if cls.EMAIL_REGEX.match(email):
return not email.startswith(".") and ".." not in email
else:
logging.warn("Invalid email address: %s.", email)
logger.warn("Invalid email address: %s.", email)
return False
14 changes: 8 additions & 6 deletions letsencrypt/augeas_configurator.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
from letsencrypt import reverter
from letsencrypt.plugins import common

logger = logging.getLogger(__name__)


class AugeasConfigurator(common.Plugin):
"""Base Augeas Configurator class.
Expand Down Expand Up @@ -52,7 +54,7 @@ def check_parsing_errors(self, lens):
lens_path = self.aug.get(path + "/lens")
# As aug.get may return null
if lens_path and lens in lens_path:
logging.error(
logger.error(
"There has been an error in parsing the file (%s): %s",
# Strip off /augeas/files and /error
path[13:len(path) - 6], self.aug.get(path + "/message"))
Expand Down Expand Up @@ -121,11 +123,11 @@ def _log_save_errors(self, ex_errs):
"""
# Check for the root of save problems
new_errs = self.aug.match("/augeas//error")
# logging.error("During Save - %s", mod_conf)
logging.error("Unable to save files: %s. Attempted Save Notes: %s",
", ".join(err[13:len(err) - 6] for err in new_errs
# Only new errors caused by recent save
if err not in ex_errs), self.save_notes)
# logger.error("During Save - %s", mod_conf)
logger.error("Unable to save files: %s. Attempted Save Notes: %s",
", ".join(err[13:len(err) - 6] for err in new_errs
# Only new errors caused by recent save
if err not in ex_errs), self.save_notes)

# Wrapper functions for Reverter class
def recovery_routine(self):
Expand Down
17 changes: 10 additions & 7 deletions letsencrypt/auth_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
from letsencrypt import interfaces


logger = logging.getLogger(__name__)


class AuthHandler(object):
"""ACME Authorization Handler for a client.
Expand Down Expand Up @@ -76,7 +79,7 @@ def get_authorizations(self, domains, best_effort=False):
# While there are still challenges remaining...
while self.dv_c or self.cont_c:
cont_resp, dv_resp = self._solve_challenges()
logging.info("Waiting for verification...")
logger.info("Waiting for verification...")

# Send all Responses - this modifies dv_c and cont_c
self._respond(cont_resp, dv_resp, best_effort)
Expand All @@ -89,7 +92,7 @@ def get_authorizations(self, domains, best_effort=False):

def _choose_challenges(self, domains):
"""Retrieve necessary challenges to satisfy server."""
logging.info("Performing the following challenges:")
logger.info("Performing the following challenges:")
for dom in domains:
path = gen_challenge_path(
self.authzr[dom].body.challenges,
Expand All @@ -112,8 +115,8 @@ def _solve_challenges(self):
dv_resp = self.dv_auth.perform(self.dv_c)
# This will catch both specific types of errors.
except errors.AuthorizationError:
logging.critical("Failure in setting up challenges.")
logging.info("Attempting to clean up outstanding challenges...")
logger.critical("Failure in setting up challenges.")
logger.info("Attempting to clean up outstanding challenges...")
self._cleanup_challenges()
raise

Expand Down Expand Up @@ -261,7 +264,7 @@ def _cleanup_challenges(self, achall_list=None):
If achall_list is not provided, cleanup all achallenges.
"""
logging.info("Cleaning up challenges")
logger.info("Cleaning up challenges")

if achall_list is None:
dv_c = self.dv_c
Expand Down Expand Up @@ -342,7 +345,7 @@ def challb_to_achall(challb, key, domain):
"""
chall = challb.chall
logging.info("%s challenge for %s", chall.typ, domain)
logger.info("%s challenge for %s", chall.typ, domain)

if isinstance(chall, challenges.DVSNI):
return achallenges.DVSNI(
Expand Down Expand Up @@ -432,7 +435,7 @@ def _find_smart_path(challbs, preferences, combinations):
if not best_combo:
msg = ("Client does not support any combination of challenges that "
"will satisfy the CA.")
logging.fatal(msg)
logger.fatal(msg)
raise errors.AuthorizationError(msg)

return best_combo
Expand Down
23 changes: 13 additions & 10 deletions letsencrypt/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@



logger = logging.getLogger(__name__)


def _account_init(args, config):
# Prepare for init of Client
if args.email is None:
Expand Down Expand Up @@ -112,7 +115,7 @@ def _init_acme(config, acc, authenticator, installer):
try:
acme.register()
except errors.LetsEncryptClientError as error:
logging.debug(error)
logger.debug(error)
sys.exit("Unable to register an account with ACME server")

return acme
Expand Down Expand Up @@ -235,27 +238,27 @@ def config_changes(unused_args, config, unused_plugins):

def plugins_cmd(args, config, plugins): # TODO: Use IDiplay rathern than print
"""List server software plugins."""
logging.debug("Expected interfaces: %s", args.ifaces)
logger.debug("Expected interfaces: %s", args.ifaces)

ifaces = [] if args.ifaces is None else args.ifaces
filtered = plugins.ifaces(ifaces)
logging.debug("Filtered plugins: %r", filtered)
logger.debug("Filtered plugins: %r", filtered)

if not args.init and not args.prepare:
print str(filtered)
return

filtered.init(config)
verified = filtered.verify(ifaces)
logging.debug("Verified plugins: %r", verified)
logger.debug("Verified plugins: %r", verified)

if not args.prepare:
print str(verified)
return

verified.prepare()
available = verified.available()
logging.debug("Prepared plugins: %s", available)
logger.debug("Prepared plugins: %s", available)
print str(available)


Expand Down Expand Up @@ -607,8 +610,8 @@ def _setup_logging(args):
root_logger.addHandler(handler)
root_logger.addHandler(file_handler)

logging.debug("Root logging level set at %d", level)
logging.info("Saving debug log to %s", log_file_name)
logger.debug("Root logging level set at %d", level)
logger.info("Saving debug log to %s", log_file_name)


def main(cli_args=sys.argv[1:]):
Expand All @@ -634,16 +637,16 @@ def main(cli_args=sys.argv[1:]):

_setup_logging(args)
# do not log `args`, as it contains sensitive data (e.g. revoke --key)!
logging.debug("Arguments: %r", cli_args)
logging.debug("Discovered plugins: %r", plugins)
logger.debug("Arguments: %r", cli_args)
logger.debug("Discovered plugins: %r", plugins)

# Reporter
report = reporter.Reporter()
zope.component.provideUtility(report)
atexit.register(report.atexit_print_messages)

if not os.geteuid() == 0:
logging.warning(
logger.warning(
"Root (sudo) is required to run most of letsencrypt functionality.")
# check must be done after arg parsing as --help should work
# w/o root; on the other hand, e.g. "letsencrypt run
Expand Down
Loading

0 comments on commit 4ce4e2f

Please sign in to comment.