Skip to content

Commit 60e9494

Browse files
committed
Add discovery of loggers
1 parent 6d6a2ec commit 60e9494

File tree

2 files changed

+50
-5
lines changed

2 files changed

+50
-5
lines changed

scfw/loggers/__init__.py

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,51 @@
11
"""
2-
Exports a set of client loggers implementing the firewall's logging protocol.
2+
Exports the currently discoverable set of client loggers implementing the
3+
firewall's logging protocol.
4+
5+
One logger ships with the supply chain firewall by default: `DDLogger`,
6+
which sends logs to Datadog. Firewall users may additionally provide
7+
custom loggers according to their own logging needs.
8+
9+
The firewall discovers loggers at runtime via the following simple protocol.
10+
The module implementing the custom logger must contain a function with the
11+
following name and signature:
12+
13+
```
14+
def load_logger() -> FirewallLogger
15+
```
16+
17+
This `load_logger` function should return an instance of the custom logger
18+
for the firewall's use. The module may then be placed in the same directory as
19+
this source file for runtime import.
320
"""
421

22+
import importlib
23+
import logging
24+
import os
25+
import pkgutil
26+
527
from scfw.logger import FirewallLogger
6-
from scfw.loggers.dd_logger import DDLogger
28+
29+
_log = logging.getLogger(__name__)
730

831

932
def get_firewall_loggers() -> list[FirewallLogger]:
1033
"""
11-
Return the current set of available client loggers.
34+
Return the currently discoverable set of client loggers.
1235
1336
Returns:
14-
A `list` of the currently available `FirewallLogger`s.
37+
A `list` of the discovered `FirewallLogger`s.
1538
"""
16-
return [DDLogger()]
39+
loggers = []
40+
41+
# TODO(ikretz): Allow the user to configure this directory
42+
for _, module, _ in pkgutil.iter_modules([os.path.dirname(__file__)]):
43+
try:
44+
logger = importlib.import_module(module).load_logger()
45+
loggers.append(logger)
46+
except ModuleNotFoundError:
47+
_log.warning(f"Failed to load module {module} while collecting loggers")
48+
except AttributeError:
49+
_log.warning(f"Module {module} does not export a logger")
50+
51+
return loggers

scfw/loggers/dd_logger.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,3 +118,13 @@ def emit(self, record):
118118
with ApiClient(configuration) as api_client:
119119
api_instance = LogsApi(api_client)
120120
api_instance.submit_log(content_encoding=ContentEncoding.DEFLATE, body=body)
121+
122+
123+
def load_logger() -> FirewallLogger:
124+
"""
125+
Export `DDLogger` for discovery by the firewall.
126+
127+
Returns:
128+
A `DDLogger` for use in a run of the supply chain firewall.
129+
"""
130+
return DDLogger()

0 commit comments

Comments
 (0)