22import re
33import logging
44
5- class DebugModeTokenFilter (logging .Filter ): # <-- inherent from the Filter class
5+ class DebugModeTokenFilter (logging .Filter ):
6+ """
7+ A logging filter that while in DEBUG mode can filter TOKENS dependent on configuration.
8+
9+ This filter uses an environment variable to determine its mode,
10+ which can either mask sensitive tokens in log messages, suppress logging,
11+ or default to standard logging behavior with a warning.
12+
13+ Attributes:
14+ mode (str): The mode of operation based on the environment variable
15+ 'DEBUG_MODE_TOKEN_FILTER'. Can be 'MASK', 'SUPPRESS', or 'DEFAULT'.
16+ """
617 def __init__ (self ):
18+ """
19+ Initializes the DebugModeTokenFilter with the 'DEBUG_MODE_TOKEN_FILTER'
20+ environment variable.
21+ """
722 super ().__init__ ()
8- # set the behavior/configuration of the filter by the environment variable
923 self .mode = os .getenv ('DEBUG_MODE_TOKEN_FILTER' , 'DEFAULT' ).upper ()
1024
1125 def filter (self , record ):
12- if self .mode == "MASK" :
13- # While this doesn't directly target the headers as @erlendvollset 's post originally targets
14- # this wider approach of targeting the "Bearer" key word I believe provides complete coverage.
15- # However I would still recommend some more research to see if this regex would need to be improved
16- # to provide a secure/trusted solution.
17- record .msg = re .sub (r'Bearer (\w+)' , '[MASKED]' , record .getMessage ())
18- elif self .mode == "SUPPRESS" :
19- return False
20- elif self .mode == "DEFAULT" :
21- msg = "Your logger, when in DEBUG mode, will log TOKENS"
22- raise Warning (msg )
23- return True
26+ """
27+ Filters logs of TOKENS dependent on the configured mode.
28+
29+ Args:
30+ record (logging.LogRecord): The log record to filter.
31+
32+ Returns:
33+ bool: True if the record should be logged, False otherwise.
34+ """
35+ if record .levelno == logging .DEBUG :
36+ if self .mode == "MASK" :
37+ record .msg = re .sub (r'Bearer (\w+)' , '[MASKED]' , record .getMessage ())
38+ elif self .mode == "SUPPRESS" :
39+ return False
40+ elif self .mode == "DEFAULT" :
41+ msg = "Your logger, when in DEBUG mode, will log TOKENS"
42+ raise Warning (msg )
43+ return True
0 commit comments