Browse Source

meta(linting): Fixing flake8-logging issues (partial) (#61315)

re-submitting https://github.com/getsentry/sentry/pull/61228 with a fix
Bartek Ogryczak 1 year ago
parent
commit
e1dce4a464

+ 1 - 1
src/sentry/integrations/aws_lambda/integration.py

@@ -331,7 +331,7 @@ class AwsLambdaCloudFormationPipelineView(PipelineView):
                 # if we have a configuration error, we should blow up the pipeline
                 raise
             except Exception as e:
-                logger.error(
+                logger.exception(
                     "AwsLambdaCloudFormationPipelineView.unexpected_error",
                     extra={"error": str(e)},
                 )

+ 12 - 8
src/sentry/integrations/bitbucket/webhook.py

@@ -133,7 +133,8 @@ class BitbucketWebhookEndpoint(Endpoint):
             organization = Organization.objects.get_from_cache(id=organization_id)
         except Organization.DoesNotExist:
             logger.info(
-                f"{PROVIDER_NAME}.webhook.invalid-organization",
+                "%s.webhook.invalid-organization",
+                PROVIDER_NAME,
                 extra={"organization_id": organization_id},
             )
             return HttpResponse(status=400)
@@ -141,15 +142,17 @@ class BitbucketWebhookEndpoint(Endpoint):
         body = bytes(request.body)
         if not body:
             logger.error(
-                f"{PROVIDER_NAME}.webhook.missing-body", extra={"organization_id": organization.id}
+                "%s.webhook.missing-body", PROVIDER_NAME, extra={"organization_id": organization.id}
             )
             return HttpResponse(status=400)
 
         try:
             handler = self.get_handler(request.META["HTTP_X_EVENT_KEY"])
         except KeyError:
-            logger.error(
-                f"{PROVIDER_NAME}.webhook.missing-event", extra={"organization_id": organization.id}
+            logger.exception(
+                "%s.webhook.missing-event",
+                PROVIDER_NAME,
+                extra={"organization_id": organization.id},
             )
             return HttpResponse(status=400)
 
@@ -166,7 +169,8 @@ class BitbucketWebhookEndpoint(Endpoint):
 
         if not valid_ip and address_string not in BITBUCKET_IPS:
             logger.error(
-                f"{PROVIDER_NAME}.webhook.invalid-ip-range",
+                "%s.webhook.invalid-ip-range",
+                PROVIDER_NAME,
                 extra={"organization_id": organization.id},
             )
             return HttpResponse(status=401)
@@ -174,10 +178,10 @@ class BitbucketWebhookEndpoint(Endpoint):
         try:
             event = json.loads(body.decode("utf-8"))
         except json.JSONDecodeError:
-            logger.error(
-                f"{PROVIDER_NAME}.webhook.invalid-json",
+            logger.exception(
+                "%s.webhook.invalid-json",
+                PROVIDER_NAME,
                 extra={"organization_id": organization.id},
-                exc_info=True,
             )
             return HttpResponse(status=400)
 

+ 3 - 2
src/sentry/integrations/bitbucket_server/client.py

@@ -224,12 +224,13 @@ class BitbucketServerClient(IntegrationProxyClient):
             new_params = dict.copy(params)
             new_params["start"] = start
             logger.debug(
-                f"Loading values for paginated uri starting from {start}",
+                "Loading values for paginated uri starting from %s",
+                start,
                 extra={"uri": uri, "params": new_params},
             )
             data = self.get(uri, params=new_params)
             logger.debug(
-                f'{len(data["values"])} values loaded', extra={"uri": uri, "params": new_params}
+                "%s values loaded", len(data["values"]), extra={"uri": uri, "params": new_params}
             )
 
             values += data["values"]

+ 10 - 10
src/sentry/integrations/bitbucket_server/webhook.py

@@ -71,7 +71,6 @@ class PushEventWebhook(Webhook):
             for commit in client.get_commits(
                 project_name, repo_name, from_hash, change.get("toHash")
             ):
-
                 if IntegrationRepositoryProvider.should_ignore_commit(commit["message"]):
                     continue
 
@@ -90,7 +89,6 @@ class PushEventWebhook(Webhook):
                     author = authors[author_email]
                 try:
                     with transaction.atomic(router.db_for_write(Commit)):
-
                         Commit.objects.create(
                             repository_id=repo.id,
                             organization_id=organization.id,
@@ -124,8 +122,9 @@ class BitbucketServerWebhookEndpoint(View):
         try:
             organization = Organization.objects.get_from_cache(id=organization_id)
         except Organization.DoesNotExist:
-            logger.error(
-                f"{PROVIDER_NAME}.webhook.invalid-organization",
+            logger.exception(
+                "%s.webhook.invalid-organization",
+                PROVIDER_NAME,
                 extra={"organization_id": organization_id, "integration_id": integration_id},
             )
             return HttpResponse(status=400)
@@ -133,15 +132,16 @@ class BitbucketServerWebhookEndpoint(View):
         body = bytes(request.body)
         if not body:
             logger.error(
-                f"{PROVIDER_NAME}.webhook.missing-body", extra={"organization_id": organization.id}
+                "%s.webhook.missing-body", PROVIDER_NAME, extra={"organization_id": organization.id}
             )
             return HttpResponse(status=400)
 
         try:
             handler = self.get_handler(request.META["HTTP_X_EVENT_KEY"])
         except KeyError:
-            logger.error(
-                f"{PROVIDER_NAME}.webhook.missing-event",
+            logger.exception(
+                "%s.webhook.missing-event",
+                PROVIDER_NAME,
                 extra={"organization_id": organization.id, "integration_id": integration_id},
             )
             return HttpResponse(status=400)
@@ -152,10 +152,10 @@ class BitbucketServerWebhookEndpoint(View):
         try:
             event = json.loads(body.decode("utf-8"))
         except json.JSONDecodeError:
-            logger.error(
-                f"{PROVIDER_NAME}.webhook.invalid-json",
+            logger.exception(
+                "%s.webhook.invalid-json",
+                PROVIDER_NAME,
                 extra={"organization_id": organization.id, "integration_id": integration_id},
-                exc_info=True,
             )
             return HttpResponse(status=400)
 

+ 2 - 3
src/sentry/integrations/discord/webhooks/base.py

@@ -74,7 +74,7 @@ class DiscordInteractionsEndpoint(Endpoint):
         except DiscordRequestError as e:
             if SiloMode.get_current_mode() != SiloMode.MONOLITH:
                 sentry_sdk.capture_exception(e)
-            logger.error(
+            logger.exception(
                 "discord.request.error",
                 extra={
                     "error": str(e),
@@ -83,12 +83,11 @@ class DiscordInteractionsEndpoint(Endpoint):
             )
             return self.respond(status=e.status)
         except Exception as e:
-            logger.error(
+            logger.exception(
                 "discord.request.unexpected_error",
                 extra={
                     "error": str(e),
                 },
-                exc_info=True,
             )
             return self.respond(status=500)
 

+ 17 - 18
src/sentry/integrations/github/client.py

@@ -275,7 +275,8 @@ class GitHubClientMixin(GithubProxyClient):
         if contents.get("truncated"):
             # e.g. getsentry/DataForThePeople
             logger.warning(
-                f"The tree for {repo_full_name} has been truncated. Use different a approach for retrieving contents of tree."
+                "The tree for %s has been truncated. Use different a approach for retrieving contents of tree.",
+                repo_full_name,
             )
         tree = contents["tree"]
 
@@ -372,24 +373,24 @@ class GitHubClientMixin(GithubProxyClient):
         # TODO: Add condition for  getsentry/DataForThePeople
         # e.g. getsentry/nextjs-sentry-example
         if txt == "Git Repository is empty.":
-            logger.warning(f"The repository is empty. {msg}", extra=extra)
+            logger.warning("The repository is empty. %s", msg, extra=extra)
         elif txt == "Not Found":
-            logger.warning(f"The app does not have access to the repo. {msg}", extra=extra)
+            logger.warning("The app does not have access to the repo. %s", msg, extra=extra)
         elif txt == "Repository access blocked":
-            logger.warning(f"Github has blocked the repository. {msg}", extra=extra)
+            logger.warning("Github has blocked the repository. %s", msg, extra=extra)
         elif txt == "Server Error":
-            logger.warning(f"Github failed to respond. {msg}.", extra=extra)
+            logger.warning("Github failed to respond. %s.", msg, extra=extra)
             should_count_error = True
         elif txt == "Bad credentials":
-            logger.warning(f"No permission granted for this repo. {msg}.", extra=extra)
+            logger.warning("No permission granted for this repo. %s.", msg, extra=extra)
         elif txt == "Connection reset by peer":
-            logger.warning(f"Connection reset by GitHub. {msg}.", extra=extra)
+            logger.warning("Connection reset by GitHub. %s.", msg, extra=extra)
             should_count_error = True
         elif txt == "Connection broken: invalid chunk length":
-            logger.warning(f"Connection broken by chunk with invalid length. {msg}.", extra=extra)
+            logger.warning("Connection broken by chunk with invalid length. %s.", msg, extra=extra)
             should_count_error = True
         elif txt and txt.startswith("Unable to reach host:"):
-            logger.warning(f"Unable to reach host at the moment. {msg}.", extra=extra)
+            logger.warning("Unable to reach host at the moment. %s.", msg, extra=extra)
             should_count_error = True
         elif txt and txt.startswith("Due to U.S. trade controls law restrictions, this GitHub"):
             logger.warning("Github has blocked this org. We will not continue.", extra=extra)
@@ -398,9 +399,7 @@ class GitHubClientMixin(GithubProxyClient):
         else:
             # We do not raise the exception so we can keep iterating through the repos.
             # Nevertheless, investigate the error to determine if we should abort the processing
-            logger.exception(
-                f"Investigate if to raise error. An error happened. {msg}", extra=extra
-            )
+            logger.error("Investigate if to raise error. An error happened. %s", msg, extra=extra)
 
         return should_count_error
 
@@ -529,7 +528,7 @@ class GitHubClientMixin(GithubProxyClient):
             output = []
 
             page_number = 1
-            logger.info(f"Page {page_number}: {path}?per_page={self.page_size}")
+            logger.info("Page %s: %s?per_page=%s", page_number, path, self.page_size)
             resp = self.get(path, params={"per_page": self.page_size})
             logger.info(resp)
             output.extend(resp) if not response_key else output.extend(resp[response_key])
@@ -542,9 +541,9 @@ class GitHubClientMixin(GithubProxyClient):
                 and resp["total_count"] > 0
                 and not output
             ):
-                logger.info(f"headers: {resp.headers}")
-                logger.info(f"output: {output}")
-                logger.info(f"next_link: {next_link}")
+                logger.info("headers: %s", resp.headers)
+                logger.info("output: %s", output)
+                logger.info("next_link: %s", next_link)
                 logger.error("No list of repos even when there's some. Investigate.")
 
             # XXX: In order to speed up this function we will need to parallelize this
@@ -555,7 +554,7 @@ class GitHubClientMixin(GithubProxyClient):
                 output.extend(resp) if not response_key else output.extend(resp[response_key])
 
                 next_link = get_next_link(resp)
-                logger.info(f"Page {page_number}: {next_link}")
+                logger.info("Page %s: %s", page_number, next_link)
                 page_number += 1
             return output
 
@@ -735,7 +734,7 @@ class GitHubClientMixin(GithubProxyClient):
                     allow_text=False,
                 )
             except ValueError as e:
-                logger.exception(e, log_info)
+                logger.exception(str(e), log_info)
                 return []
             else:
                 self.set_cache(cache_key, response, 60)

+ 1 - 1
src/sentry/integrations/github/integration.py

@@ -149,7 +149,7 @@ class GitHubIntegration(IntegrationInstallation, GitHubIssueBasic, RepositoryMix
             id=self.org_integration.organization_id, user_id=None
         )
         if not organization_context:
-            logger.exception(
+            logger.error(
                 "No organization information was found. Continuing execution.", extra=extra
             )
         else:

+ 4 - 6
src/sentry/integrations/github/webhook.py

@@ -221,7 +221,7 @@ class InstallationEventWebhook(Webhook):
                         "external_id": str(external_id),
                     },
                 )
-                logger.exception("Installation is missing.")
+                logger.error("Installation is missing.")
 
     def _handle_delete(
         self,
@@ -587,7 +587,7 @@ class GitHubWebhookBase(Endpoint):
         try:
             handler = self.get_handler(request.META["HTTP_X_GITHUB_EVENT"])
         except KeyError:
-            logger.error("github.webhook.missing-event", extra=self.get_logging_data())
+            logger.exception("github.webhook.missing-event", extra=self.get_logging_data())
             logger.exception("Missing Github event in webhook.")
             return HttpResponse(status=400)
 
@@ -601,7 +601,7 @@ class GitHubWebhookBase(Endpoint):
         try:
             method, signature = request.META["HTTP_X_HUB_SIGNATURE"].split("=", 1)
         except (KeyError, IndexError):
-            logger.error("github.webhook.missing-signature", extra=self.get_logging_data())
+            logger.exception("github.webhook.missing-signature", extra=self.get_logging_data())
             logger.exception("Missing webhook secret.")
             return HttpResponse(status=400)
 
@@ -612,9 +612,7 @@ class GitHubWebhookBase(Endpoint):
         try:
             event = json.loads(body.decode("utf-8"))
         except json.JSONDecodeError:
-            logger.error(
-                "github.webhook.invalid-json", extra=self.get_logging_data(), exc_info=True
-            )
+            logger.exception("github.webhook.invalid-json", extra=self.get_logging_data())
             logger.exception("Invalid JSON.")
             return HttpResponse(status=400)
 

+ 1 - 1
src/sentry/integrations/github_enterprise/webhook.py

@@ -122,7 +122,7 @@ class GitHubEnterpriseWebhookBase(Endpoint):
             host = get_host(request=request)
             if not host:
                 logger.warning("github_enterprise.webhook.missing-enterprise-host")
-                logger.exception("Missing enterprise host.")
+                logger.error("Missing enterprise host.")
                 return HttpResponse(status=400)
 
             extra = {"host": host}

+ 2 - 2
src/sentry/integrations/gitlab/blame.py

@@ -62,7 +62,7 @@ def fetch_file_blames(
                 and rate_limit_info.remaining < (MINIMUM_REQUESTS - len(files))
             ):
                 metrics.incr("integrations.gitlab.get_blame_for_files.rate_limit")
-                logger.exception(
+                logger.error(
                     "get_blame_for_files.rate_limit_too_low",
                     extra={
                         **extra,
@@ -117,7 +117,7 @@ def _create_file_blame_info(commit: CommitInfo, file: SourceLineInfo) -> FileBla
 def _handle_file_blame_error(error: ApiError, file: SourceLineInfo, extra: Mapping[str, Any]):
     if error.code == 429:
         metrics.incr("integrations.gitlab.get_blame_for_files.rate_limit")
-    logger.exception(
+    logger.exception(  # noqa: LOG004  # this function is used in an exception handler
         "get_blame_for_files.api_error",
         extra={
             **extra,

Some files were not shown because too many files changed in this diff