Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds logger filter for TOKENS when logging in DEBUG MODE #539

Draft
wants to merge 9 commits into
base: master
Choose a base branch
from
Prev Previous commit
Next Next commit
updates env var name, improve SUPRESSED scope implementation, black f…
…ormatting
  • Loading branch information
Jacques Troussard committed Apr 21, 2024
commit 33d5bb5c0e99c41f92fdb75fede9242315ff8cbf
12 changes: 9 additions & 3 deletions requests_oauthlib/log_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import re
import logging


class DebugModeTokenFilter(logging.Filter):
"""
A logging filter that while in DEBUG mode can filter TOKENS dependent on configuration.
Expand All @@ -14,13 +15,15 @@ class DebugModeTokenFilter(logging.Filter):
mode (str): The mode of operation based on the environment variable
'DEBUG_MODE_TOKEN_FILTER'. Can be 'MASK', 'SUPPRESS', or 'DEFAULT'.
"""

def __init__(self):
"""
Initializes the DebugModeTokenFilter with the 'DEBUG_MODE_TOKEN_FILTER'
environment variable.
"""
super().__init__()
self.mode = os.getenv('DEBUG_MODE_TOKEN_FILTER', 'DEFAULT').upper()
self.mode = os.getenv(
'REQUESTS_OAUTHLIB_DEBUG_MODE_TOKEN_FILTER', 'DEFAULT').upper()

def filter(self, record):
"""
Expand All @@ -34,7 +37,10 @@ def filter(self, record):
"""
if record.levelno == logging.DEBUG:
if self.mode == "MASK":
record.msg = re.sub(r'Bearer\s+([A-Za-z0-9\-._~+\/]+)', '[MASKED]', record.getMessage())
record.msg = re.sub(
r'Bearer\s+([A-Za-z0-9\-._~+\/]+)', '[MASKED]', record.getMessage())
elif self.mode == "SUPPRESS":
record.msg = " "
else:
return False

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe only suppress log messages which match the above regex? Otherwise this equivalent to disabling the logger entirely.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am hoping a single space would suffice as a replacement? Or maybe just pass None to the msg?

return True # if mode is not MASKED then DEFAULT is implied
return True # if mode is not MASKED then DEFAULT is implied
Loading