Skip to content

Commit dd269ac

Browse files
committed
Remove secrets from logs
(closes #274)
1 parent 657bca9 commit dd269ac

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

datadog/__init__.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
from datadog.threadstats import ThreadStats, datadog_lambda_wrapper, lambda_metric # noqa
2222
from datadog.util.compat import iteritems, NullHandler, text
2323
from datadog.util.config import get_version
24+
from datadog.util.format import SecretFormatter
2425
from datadog.util.hostname import get_hostname
2526

2627

@@ -98,6 +99,13 @@ def initialize(api_key=None, app_key=None, host_name=None, api_host=None,
9899
api._host_name = host_name or api._host_name or get_hostname(hostname_from_config)
99100
api._api_host = api_host or api._api_host or os.environ.get('DATADOG_HOST', 'https://api.datadoghq.com')
100101

102+
# Remove secrets from all root loggers
103+
secrets=[api._api_key, api._application_key]
104+
for h in logging.root.handlers:
105+
if isinstance(h.formatter, SecretFormatter) and h.formatter.secrets == secrets:
106+
continue
107+
h.setFormatter(SecretFormatter(h.formatter, secrets=secrets))
108+
101109
# Statsd configuration
102110
# ...overrides the default `statsd` instance attributes
103111
if statsd_socket_path:

datadog/util/format.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,21 @@ def force_to_epoch_seconds(epoch_sec_or_dt):
2727

2828
def normalize_tags(tag_list):
2929
return [tag.replace(',', '_') for tag in tag_list]
30+
31+
32+
class SecretFormatter(object):
33+
"""Remove secrets from logs."""
34+
35+
def __init__(self, formatter, secrets, replace="[SECRET]"):
36+
self.formatter = formatter
37+
self.secrets = secrets
38+
self.replace = replace
39+
40+
def format(self, record):
41+
msg = self.formatter.format(record)
42+
for secret in self.secrets:
43+
msg = msg.replace(secret, self.replace)
44+
return msg
45+
46+
def __getattr__(self, attr):
47+
return getattr(self.formatter, attr)

0 commit comments

Comments
 (0)