This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
"""
|
||||
Structured logging helper for Netdata.
|
||||
|
||||
Netdata does not expose a generic "push a log line" API reachable with
|
||||
just a room token from outside an Agent (see credentials.py). Until a
|
||||
real push mechanism (StatsD or an OpenTelemetry log receiver) is
|
||||
confirmed enabled on the agent, the supported path is the standard one:
|
||||
emit structured JSON lines to stdout, which Netdata's log collectors
|
||||
(systemd-journal / generic log source) are built to tail and parse.
|
||||
"""
|
||||
import logging
|
||||
import sys
|
||||
|
||||
from pythonjsonlogger import jsonlogger
|
||||
|
||||
from .credentials import netdata
|
||||
|
||||
_LOGGER_NAME = "netdata"
|
||||
|
||||
|
||||
def get_netdata_logger() -> logging.Logger:
|
||||
logger = logging.getLogger(_LOGGER_NAME)
|
||||
|
||||
if not logger.handlers:
|
||||
handler = logging.StreamHandler(stream=sys.stdout)
|
||||
handler.setFormatter(
|
||||
jsonlogger.JsonFormatter("%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||
)
|
||||
logger.addHandler(handler)
|
||||
logger.setLevel(logging.INFO)
|
||||
logger.propagate = False
|
||||
|
||||
return logger
|
||||
|
||||
|
||||
def log_event(message, level="info", **fields):
|
||||
"""Log a structured event intended to be picked up by Netdata.
|
||||
|
||||
Extra keyword arguments are attached as structured fields on the JSON
|
||||
log line, e.g. log_event("hello world", source="netdata_logging.hello").
|
||||
"""
|
||||
logger = get_netdata_logger()
|
||||
log_fn = getattr(logger, level.lower(), logger.info)
|
||||
log_fn(message, extra={"netdata_agent_host": netdata.agent_host, **fields})
|
||||
Reference in New Issue
Block a user