Commit 39d35374 by Sarina Canelake

Pylint logging-format-interpolation: Convert logging calls to use %s formatting

parent 647bc967
...@@ -105,10 +105,13 @@ def update_certificate(request): ...@@ -105,10 +105,13 @@ def update_certificate(request):
key=xqueue_header['lms_key']) key=xqueue_header['lms_key'])
except GeneratedCertificate.DoesNotExist: except GeneratedCertificate.DoesNotExist:
logger.critical('Unable to lookup certificate\n' logger.critical(
'xqueue_body: {0}\n' 'Unable to lookup certificate\n'
'xqueue_header: {1}'.format( 'xqueue_body: %s\n'
xqueue_body, xqueue_header)) 'xqueue_header: %s',
xqueue_body,
xqueue_header
)
return HttpResponse(json.dumps({ return HttpResponse(json.dumps({
'return_code': 1, 'return_code': 1,
...@@ -139,8 +142,9 @@ def update_certificate(request): ...@@ -139,8 +142,9 @@ def update_certificate(request):
elif cert.status in [status.deleting]: elif cert.status in [status.deleting]:
cert.status = status.deleted cert.status = status.deleted
else: else:
logger.critical('Invalid state for cert update: {0}'.format( logger.critical(
cert.status)) 'Invalid state for cert update: %s', cert.status
)
return HttpResponse( return HttpResponse(
json.dumps({ json.dumps({
'return_code': 1, 'return_code': 1,
......
...@@ -224,14 +224,15 @@ def get_course_about_section(course, section_key): ...@@ -224,14 +224,15 @@ def get_course_about_section(course, section_key):
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
html = render_to_string('courseware/error-message.html', None) html = render_to_string('courseware/error-message.html', None)
log.exception( log.exception(
u"Error rendering course={course}, section_key={section_key}".format( u"Error rendering course=%s, section_key=%s",
course=course, section_key=section_key course, section_key
)) )
return html return html
except ItemNotFoundError: except ItemNotFoundError:
log.warning( log.warning(
u"Missing about section {key} in course {url}".format(key=section_key, url=course.location.to_deprecated_string()) u"Missing about section %s in course %s",
section_key, course.location.to_deprecated_string()
) )
return None return None
elif section_key == "title": elif section_key == "title":
...@@ -291,9 +292,9 @@ def get_course_info_section(request, course, section_key): ...@@ -291,9 +292,9 @@ def get_course_info_section(request, course, section_key):
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
html = render_to_string('courseware/error-message.html', None) html = render_to_string('courseware/error-message.html', None)
log.exception( log.exception(
u"Error rendering course={course}, section_key={section_key}".format( u"Error rendering course=%s, section_key=%s",
course=course, section_key=section_key course, section_key
)) )
return html return html
...@@ -330,7 +331,8 @@ def get_course_syllabus_section(course, section_key): ...@@ -330,7 +331,8 @@ def get_course_syllabus_section(course, section_key):
) )
except ResourceNotFoundError: except ResourceNotFoundError:
log.exception( log.exception(
u"Missing syllabus section {key} in course {url}".format(key=section_key, url=course.location.to_deprecated_string()) u"Missing syllabus section %s in course %s",
section_key, course.location.to_deprecated_string()
) )
return "! Syllabus missing !" return "! Syllabus missing !"
......
...@@ -230,14 +230,16 @@ def answer_distributions(course_key): ...@@ -230,14 +230,16 @@ def answer_distributions(course_key):
answer_counts[(url, display_name, problem_part_id)][answer] += 1 answer_counts[(url, display_name, problem_part_id)][answer] += 1
except (ItemNotFoundError, InvalidKeyError): except (ItemNotFoundError, InvalidKeyError):
msg = "Answer Distribution: Item {} referenced in StudentModule {} " + \ msg = (
"for user {} in course {} not found; " + \ "Answer Distribution: Item {} referenced in StudentModule {} " +
"This can happen if a student answered a question that " + \ "for user {} in course {} not found; " +
"was later deleted from the course. This answer will be " + \ "This can happen if a student answered a question that " +
"omitted from the answer distribution CSV." "was later deleted from the course. This answer will be " +
log.warning( "omitted from the answer distribution CSV."
msg.format(module.module_state_key, module.id, module.student_id, course_key) ).format(
module.module_state_key, module.id, module.student_id, course_key
) )
log.warning(msg)
continue continue
return answer_counts return answer_counts
......
...@@ -159,8 +159,8 @@ class Command(BaseCommand): ...@@ -159,8 +159,8 @@ class Command(BaseCommand):
save_changes = options['save_changes'] save_changes = options['save_changes']
LOG.info("Starting run: save_changes = {0}".format(save_changes)) LOG.info("Starting run: save_changes = %s", save_changes)
self.fix_studentmodules(save_changes) self.fix_studentmodules(save_changes)
LOG.info("Finished run: updating {0} of {1} modules".format(self.num_changed, self.num_visited)) LOG.info("Finished run: updating %s of %s modules", self.num_changed, self.num_visited)
...@@ -80,9 +80,12 @@ class Command(BaseCommand): ...@@ -80,9 +80,12 @@ class Command(BaseCommand):
self.remove_studentmodulehistory_input_state(hist_module, save_changes) self.remove_studentmodulehistory_input_state(hist_module, save_changes)
if self.num_visited % 1000 == 0: if self.num_visited % 1000 == 0:
LOG.info(" Progress: updated {0} of {1} student modules".format(self.num_changed, self.num_visited)) LOG.info(" Progress: updated %s of %s student modules", self.num_changed, self.num_visited)
LOG.info(" Progress: updated {0} of {1} student history modules".format(self.num_hist_changed, LOG.info(
self.num_hist_visited)) " Progress: updated %s of %s student history modules",
self.num_hist_changed,
self.num_hist_visited
)
@transaction.autocommit @transaction.autocommit
def remove_studentmodule_input_state(self, module, save_changes): def remove_studentmodule_input_state(self, module, save_changes):
...@@ -90,9 +93,11 @@ class Command(BaseCommand): ...@@ -90,9 +93,11 @@ class Command(BaseCommand):
module_state = module.state module_state = module.state
if module_state is None: if module_state is None:
# not likely, since we filter on it. But in general... # not likely, since we filter on it. But in general...
LOG.info("No state found for {type} module {id} for student {student} in course {course_id}" LOG.info(
.format(type=module.module_type, id=module.module_state_key, "No state found for %s module %s for student %s in course %s",
student=module.student.username, course_id=module.course_id)) module.module_type, module.module_state_key,
module.student.username, module.course_id
)
return return
state_dict = json.loads(module_state) state_dict = json.loads(module_state)
...@@ -116,9 +121,11 @@ class Command(BaseCommand): ...@@ -116,9 +121,11 @@ class Command(BaseCommand):
module_state = module.state module_state = module.state
if module_state is None: if module_state is None:
# not likely, since we filter on it. But in general... # not likely, since we filter on it. But in general...
LOG.info("No state found for {type} module {id} for student {student} in course {course_id}" LOG.info(
.format(type=module.module_type, id=module.module_state_key, "No state found for %s module %s for student %s in course %s",
student=module.student.username, course_id=module.course_id)) module.module_type, module.module_state_key,
module.student.username, module.course_id
)
return return
state_dict = json.loads(module_state) state_dict = json.loads(module_state)
...@@ -142,10 +149,13 @@ class Command(BaseCommand): ...@@ -142,10 +149,13 @@ class Command(BaseCommand):
raise CommandError("missing idlist file") raise CommandError("missing idlist file")
idlist_path = args[0] idlist_path = args[0]
save_changes = options['save_changes'] save_changes = options['save_changes']
LOG.info("Starting run: reading from idlist file {0}; save_changes = {1}".format(idlist_path, save_changes)) LOG.info("Starting run: reading from idlist file %s; save_changes = %s", idlist_path, save_changes)
self.fix_studentmodules_in_list(save_changes, idlist_path) self.fix_studentmodules_in_list(save_changes, idlist_path)
LOG.info("Finished run: updating {0} of {1} student modules".format(self.num_changed, self.num_visited)) LOG.info("Finished run: updating %s of %s student modules", self.num_changed, self.num_visited)
LOG.info("Finished run: updating {0} of {1} student history modules".format(self.num_hist_changed, LOG.info(
self.num_hist_visited)) "Finished run: updating %s of %s student history modules",
self.num_hist_changed,
self.num_hist_visited
)
...@@ -890,10 +890,9 @@ def get_module_by_usage_id(request, course_id, usage_id, disable_staff_debug_inf ...@@ -890,10 +890,9 @@ def get_module_by_usage_id(request, course_id, usage_id, disable_staff_debug_inf
descriptor_orig_usage_key, descriptor_orig_version = modulestore().get_block_original_usage(usage_key) descriptor_orig_usage_key, descriptor_orig_version = modulestore().get_block_original_usage(usage_key)
except ItemNotFoundError: except ItemNotFoundError:
log.warn( log.warn(
"Invalid location for course id {course_id}: {usage_key}".format( "Invalid location for course id %s: %s",
course_id=usage_key.course_key, usage_key.course_key,
usage_key=usage_key usage_key
)
) )
raise Http404 raise Http404
......
...@@ -598,14 +598,13 @@ def _index_bulk_op(request, course_key, chapter, section, position): ...@@ -598,14 +598,13 @@ def _index_bulk_op(request, course_key, chapter, section, position):
raise raise
else: else:
log.exception( log.exception(
u"Error in index view: user={user}, course={course}, chapter={chapter}" u"Error in index view: user=%s, course=%s, chapter=%s, section=%s, position=%s",
u" section={section} position={position}".format( user,
user=user, course,
course=course, chapter,
chapter=chapter, section,
section=section, position
position=position )
))
try: try:
result = render_to_response('courseware/courseware-error.html', { result = render_to_response('courseware/courseware-error.html', {
'staff_access': staff_access, 'staff_access': staff_access,
...@@ -637,9 +636,12 @@ def jump_to_id(request, course_id, module_id): ...@@ -637,9 +636,12 @@ def jump_to_id(request, course_id, module_id):
)) ))
if len(items) > 1: if len(items) > 1:
log.warning( log.warning(
u"Multiple items found with id: {0} in course_id: {1}. Referer: {2}. Using first: {3}".format( u"Multiple items found with id: %s in course_id: %s. Referer: %s. Using first: %s",
module_id, course_id, request.META.get("HTTP_REFERER", ""), items[0].location.to_deprecated_string() module_id,
)) course_id,
request.META.get("HTTP_REFERER", ""),
items[0].location.to_deprecated_string()
)
return jump_to(request, course_id, items[0].location.to_deprecated_string()) return jump_to(request, course_id, items[0].location.to_deprecated_string())
...@@ -1239,7 +1241,7 @@ def get_static_tab_contents(request, course, tab): ...@@ -1239,7 +1241,7 @@ def get_static_tab_contents(request, course, tab):
request.user, request, loc, field_data_cache, static_asset_path=course.static_asset_path, course=course request.user, request, loc, field_data_cache, static_asset_path=course.static_asset_path, course=course
) )
logging.debug('course_module = {0}'.format(tab_module)) logging.debug('course_module = %s', tab_module)
html = '' html = ''
if tab_module is not None: if tab_module is not None:
...@@ -1248,7 +1250,7 @@ def get_static_tab_contents(request, course, tab): ...@@ -1248,7 +1250,7 @@ def get_static_tab_contents(request, course, tab):
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
html = render_to_string('courseware/error-message.html', None) html = render_to_string('courseware/error-message.html', None)
log.exception( log.exception(
u"Error rendering course={course}, tab={tab_url}".format(course=course, tab_url=tab['url_slug']) u"Error rendering course=%s, tab=%s", course, tab['url_slug']
) )
return html return html
......
...@@ -59,9 +59,9 @@ def cmd_log(cmd, cwd): ...@@ -59,9 +59,9 @@ def cmd_log(cmd, cwd):
command doesn't return 0, and returns the command's output. command doesn't return 0, and returns the command's output.
""" """
output = subprocess.check_output(cmd, cwd=cwd, stderr=subprocess.STDOUT) output = subprocess.check_output(cmd, cwd=cwd, stderr=subprocess.STDOUT)
log.debug('Command was: {0!r}. '
'Working directory was: {1!r}'.format(' '.join(cmd), cwd)) log.debug(u'Command was: %r. Working directory was: %r', ' '.join(cmd), cwd)
log.debug('Command output was: {0!r}'.format(output)) log.debug(u'Command output was: %r', output)
return output return output
...@@ -152,7 +152,7 @@ def add_repo(repo, rdir_in, branch=None): ...@@ -152,7 +152,7 @@ def add_repo(repo, rdir_in, branch=None):
rdir = os.path.basename(rdir_in) rdir = os.path.basename(rdir_in)
else: else:
rdir = repo.rsplit('/', 1)[-1].rsplit('.git', 1)[0] rdir = repo.rsplit('/', 1)[-1].rsplit('.git', 1)[0]
log.debug('rdir = {0}'.format(rdir)) log.debug('rdir = %s', rdir)
rdirp = '{0}/{1}'.format(GIT_REPO_DIR, rdir) rdirp = '{0}/{1}'.format(GIT_REPO_DIR, rdir)
if os.path.exists(rdirp): if os.path.exists(rdirp):
...@@ -239,7 +239,7 @@ def add_repo(repo, rdir_in, branch=None): ...@@ -239,7 +239,7 @@ def add_repo(repo, rdir_in, branch=None):
except InvalidKeyError: except InvalidKeyError:
course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id) course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
cdir = '{0}/{1}'.format(GIT_REPO_DIR, course_key.course) cdir = '{0}/{1}'.format(GIT_REPO_DIR, course_key.course)
log.debug('Studio course dir = {0}'.format(cdir)) log.debug('Studio course dir = %s', cdir)
if os.path.exists(cdir) and not os.path.islink(cdir): if os.path.exists(cdir) and not os.path.islink(cdir):
log.debug(' -> exists, but is not symlink') log.debug(' -> exists, but is not symlink')
...@@ -251,7 +251,7 @@ def add_repo(repo, rdir_in, branch=None): ...@@ -251,7 +251,7 @@ def add_repo(repo, rdir_in, branch=None):
log.exception('Failed to remove course directory') log.exception('Failed to remove course directory')
if not os.path.exists(cdir): if not os.path.exists(cdir):
log.debug(' -> creating symlink between {0} and {1}'.format(rdirp, cdir)) log.debug(' -> creating symlink between %s and %s', rdirp, cdir)
try: try:
os.symlink(os.path.abspath(rdirp), os.path.abspath(cdir)) os.symlink(os.path.abspath(rdirp), os.path.abspath(cdir))
except OSError: except OSError:
...@@ -280,5 +280,5 @@ def add_repo(repo, rdir_in, branch=None): ...@@ -280,5 +280,5 @@ def add_repo(repo, rdir_in, branch=None):
) )
cil.save() cil.save()
log.debug('saved CourseImportLog for {0}'.format(cil.course_id)) log.debug('saved CourseImportLog for %s', cil.course_id)
mdb.disconnect() mdb.disconnect()
...@@ -387,7 +387,7 @@ class Courses(SysadminDashboardView): ...@@ -387,7 +387,7 @@ class Courses(SysadminDashboardView):
msg = u'' msg = u''
log.debug('Adding course using git repo {0}'.format(gitloc)) log.debug('Adding course using git repo %s', gitloc)
# Grab logging output for debugging imports # Grab logging output for debugging imports
output = StringIO.StringIO() output = StringIO.StringIO()
...@@ -723,7 +723,7 @@ class GitLogs(TemplateView): ...@@ -723,7 +723,7 @@ class GitLogs(TemplateView):
try: try:
course = get_course_by_id(course_id) course = get_course_by_id(course_id)
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
log.info('Cannot find course {0}'.format(course_id)) log.info('Cannot find course %s', course_id)
raise Http404 raise Http404
# Allow only course team, instructors, and staff # Allow only course team, instructors, and staff
...@@ -731,11 +731,11 @@ class GitLogs(TemplateView): ...@@ -731,11 +731,11 @@ class GitLogs(TemplateView):
CourseInstructorRole(course.id).has_user(request.user) or CourseInstructorRole(course.id).has_user(request.user) or
CourseStaffRole(course.id).has_user(request.user)): CourseStaffRole(course.id).has_user(request.user)):
raise Http404 raise Http404
log.debug('course_id={0}'.format(course_id)) log.debug('course_id=%s', course_id)
cilset = CourseImportLog.objects.filter( cilset = CourseImportLog.objects.filter(
course_id=course_id course_id=course_id
).order_by('-created') ).order_by('-created')
log.debug('cilset length={0}'.format(len(cilset))) log.debug('cilset length=%s', len(cilset))
# Paginate the query set # Paginate the query set
paginator = Paginator(cilset, page_size) paginator = Paginator(cilset, page_size)
......
...@@ -23,6 +23,7 @@ class MockCommentServiceRequestHandler(BaseHTTPRequestHandler): ...@@ -23,6 +23,7 @@ class MockCommentServiceRequestHandler(BaseHTTPRequestHandler):
post_dict = json.loads(data_string) post_dict = json.loads(data_string)
# Log the request # Log the request
# pylint: disable=logging-format-interpolation
logger.debug( logger.debug(
"Comment Service received POST request {0} to path {1}" "Comment Service received POST request {0} to path {1}"
.format(json.dumps(post_dict), self.path) .format(json.dumps(post_dict), self.path)
...@@ -60,6 +61,7 @@ class MockCommentServiceRequestHandler(BaseHTTPRequestHandler): ...@@ -60,6 +61,7 @@ class MockCommentServiceRequestHandler(BaseHTTPRequestHandler):
post_dict = json.loads(data_string) post_dict = json.loads(data_string)
# Log the request # Log the request
# pylint: disable=logging-format-interpolation
logger.debug( logger.debug(
"Comment Service received PUT request {0} to path {1}" "Comment Service received PUT request {0} to path {1}"
.format(json.dumps(post_dict), self.path) .format(json.dumps(post_dict), self.path)
......
...@@ -476,7 +476,11 @@ def extend_content(content): ...@@ -476,7 +476,11 @@ def extend_content(content):
user = User.objects.get(pk=content['user_id']) user = User.objects.get(pk=content['user_id'])
roles = dict(('name', role.name.lower()) for role in user.roles.filter(course_id=content['course_id'])) roles = dict(('name', role.name.lower()) for role in user.roles.filter(course_id=content['course_id']))
except User.DoesNotExist: except User.DoesNotExist:
log.error('User ID {0} in comment content {1} but not in our DB.'.format(content.get('user_id'), content.get('id'))) log.error(
'User ID %s in comment content %s but not in our DB.',
content.get('user_id'),
content.get('id')
)
content_info = { content_info = {
'displayed_title': content.get('highlighted_title') or content.get('title', ''), 'displayed_title': content.get('highlighted_title') or content.get('title', ''),
...@@ -547,9 +551,10 @@ def prepare_content(content, course_key, is_staff=False, course_is_cohorted=None ...@@ -547,9 +551,10 @@ def prepare_content(content, course_key, is_staff=False, course_is_cohorted=None
try: try:
endorser = User.objects.get(pk=endorsement["user_id"]) endorser = User.objects.get(pk=endorsement["user_id"])
except User.DoesNotExist: except User.DoesNotExist:
log.error("User ID {0} in endorsement for comment {1} but not in our DB.".format( log.error(
"User ID %s in endorsement for comment %s but not in our DB.",
content.get('user_id'), content.get('user_id'),
content.get('id')) content.get('id')
) )
# Only reveal endorser if requester can see author or if endorser is staff # Only reveal endorser if requester can see author or if endorser is staff
......
...@@ -3,6 +3,7 @@ Instructor Views ...@@ -3,6 +3,7 @@ Instructor Views
""" """
## NOTE: This is the code for the legacy instructor dashboard ## NOTE: This is the code for the legacy instructor dashboard
## We are no longer supporting this file or accepting changes into it. ## We are no longer supporting this file or accepting changes into it.
# pylint: disable=line-too-long, missing-docstring
from contextlib import contextmanager from contextlib import contextmanager
import csv import csv
import json import json
...@@ -155,7 +156,7 @@ def instructor_dashboard(request, course_id): ...@@ -155,7 +156,7 @@ def instructor_dashboard(request, course_id):
if settings.FEATURES['ENABLE_MANUAL_GIT_RELOAD']: if settings.FEATURES['ENABLE_MANUAL_GIT_RELOAD']:
if 'GIT pull' in action: if 'GIT pull' in action:
data_dir = course.data_dir data_dir = course.data_dir
log.debug('git pull {0}'.format(data_dir)) log.debug('git pull %s', data_dir)
gdir = settings.DATA_DIR / data_dir gdir = settings.DATA_DIR / data_dir
if not os.path.exists(gdir): if not os.path.exists(gdir):
msg += "====> ERROR in gitreload - no such directory {0}".format(gdir) msg += "====> ERROR in gitreload - no such directory {0}".format(gdir)
...@@ -166,7 +167,7 @@ def instructor_dashboard(request, course_id): ...@@ -166,7 +167,7 @@ def instructor_dashboard(request, course_id):
track.views.server_track(request, "git-pull", {"directory": data_dir}, page="idashboard") track.views.server_track(request, "git-pull", {"directory": data_dir}, page="idashboard")
if 'Reload course' in action: if 'Reload course' in action:
log.debug('reloading {0} ({1})'.format(course_key, course)) log.debug('reloading %s (%s)', course_key, course)
try: try:
data_dir = course.data_dir data_dir = course.data_dir
modulestore().try_load_course(data_dir) modulestore().try_load_course(data_dir)
...@@ -908,7 +909,7 @@ def _do_enroll_students(course, course_key, students, secure=False, overload=Fal ...@@ -908,7 +909,7 @@ def _do_enroll_students(course, course_key, students, secure=False, overload=Fal
datatable['data'] = [[x, status[x]] for x in sorted(status)] datatable['data'] = [[x, status[x]] for x in sorted(status)]
datatable['title'] = _('Enrollment of students') datatable['title'] = _('Enrollment of students')
def sf(stat): def sf(stat): # pylint: disable=invalid-name
return [x for x in status if status[x] == stat] return [x for x in status if status[x] == stat]
data = dict(added=sf('added'), rejected=sf('rejected') + sf('exists'), data = dict(added=sf('added'), rejected=sf('rejected') + sf('exists'),
......
...@@ -117,11 +117,11 @@ def enable_microsites(): ...@@ -117,11 +117,11 @@ def enable_microsites():
ms_config['template_dir'] = template_dir ms_config['template_dir'] = template_dir
ms_config['microsite_name'] = ms_name ms_config['microsite_name'] = ms_name
log.info('Loading microsite {0}'.format(ms_root)) log.info('Loading microsite %s', ms_root)
else: else:
# not sure if we have application logging at this stage of # not sure if we have application logging at this stage of
# startup # startup
log.error('Error loading microsite {0}. Directory does not exist'.format(ms_root)) log.error('Error loading microsite %s. Directory does not exist', ms_root)
# remove from our configuration as it is not valid # remove from our configuration as it is not valid
del microsite_config_dict[ms_name] del microsite_config_dict[ms_name]
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment