1
0
mirror of https://github.com/checktheroads/hyperglass synced 2024-05-11 05:55:08 +00:00
Files
checktheroads-hyperglass/hyperglass/log.py

223 lines
6.3 KiB
Python
Raw Normal View History

2020-04-14 10:24:20 -07:00
"""Logging instance setup & configuration."""
# Standard Library
2021-01-12 00:16:34 -07:00
import sys
2021-09-15 18:25:37 -07:00
import typing as t
2020-09-28 14:43:17 -07:00
import logging
2020-04-14 10:24:20 -07:00
from datetime import datetime
# Third Party
from loguru import logger as _loguru_logger
2021-09-26 16:50:25 -07:00
from rich.logging import RichHandler
from gunicorn.glogging import Logger as GunicornLogger # type: ignore
# Local
from .constants import __version__
if t.TYPE_CHECKING:
# Standard Library
from pathlib import Path
# Third Party
from loguru import Logger as LoguruLogger
from pydantic import ByteSize
# Project
from hyperglass.models.fields import LogFormat
2020-04-14 10:24:20 -07:00
2021-01-12 00:16:34 -07:00
_FMT = (
2020-04-14 10:24:20 -07:00
"<lvl><b>[{level}]</b> {time:YYYYMMDD} {time:HH:mm:ss} <lw>|</lw> {name}<lw>:</lw>"
"<b>{line}</b> <lw>|</lw> {function}</lvl> <lvl><b>→</b></lvl> {message}"
)
2021-09-26 16:50:25 -07:00
_FMT_FILE = "[{time:YYYYMMDD} {time:HH:mm:ss}] {message}"
2020-09-28 14:43:17 -07:00
_DATE_FMT = "%Y%m%d %H:%M:%S"
_FMT_BASIC = "{message}"
2020-04-14 10:24:20 -07:00
_LOG_LEVELS = [
2021-04-24 10:44:40 -07:00
{"name": "TRACE", "color": "<m>"},
{"name": "DEBUG", "color": "<c>"},
{"name": "INFO", "color": "<le>"},
{"name": "SUCCESS", "color": "<g>"},
{"name": "WARNING", "color": "<y>"},
{"name": "ERROR", "color": "<y>"},
{"name": "CRITICAL", "color": "<r>"},
2020-04-14 10:24:20 -07:00
]
2021-09-15 18:25:37 -07:00
class LibIntercentHandler(logging.Handler):
"""Custom log handler for integrating third party library logging with hyperglass's logger."""
def emit(self, record):
"""Emit log record.
See: https://github.com/Delgan/loguru (Readme)
"""
# Get corresponding Loguru level if it exists
try:
level = _loguru_logger.level(record.levelname).name
except ValueError:
level = record.levelno
# Find caller from where originated the logged message
frame, depth = logging.currentframe(), 2
while frame.f_code.co_filename == logging.__file__:
frame = frame.f_back
depth += 1
_loguru_logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())
2021-09-26 16:50:25 -07:00
class CustomGunicornLogger(GunicornLogger):
2021-09-15 18:25:37 -07:00
"""Custom logger to direct Gunicorn/Uvicorn logs to Loguru.
See: https://pawamoy.github.io/posts/unify-logging-for-a-gunicorn-uvicorn-app/
"""
def setup(self, cfg: t.Any) -> None:
"""Override Gunicorn setup."""
handler = logging.NullHandler()
self.error_logger = logging.getLogger("gunicorn.error")
self.error_logger.addHandler(handler)
self.access_logger = logging.getLogger("gunicorn.access")
self.access_logger.addHandler(handler)
self.error_logger.setLevel(cfg.loglevel)
self.access_logger.setLevel(cfg.loglevel)
def setup_lib_logging(log_level: str) -> None:
"""Override the logging handlers for dependency libraries.
See: https://pawamoy.github.io/posts/unify-logging-for-a-gunicorn-uvicorn-app/
"""
intercept_handler = LibIntercentHandler()
seen = set()
for name in [
*logging.root.manager.loggerDict.keys(),
2020-10-11 15:39:15 -07:00
"gunicorn",
"gunicorn.access",
"gunicorn.error",
"uvicorn",
"uvicorn.access",
"uvicorn.error",
"uvicorn.asgi",
"netmiko",
2021-09-15 18:25:37 -07:00
"paramiko",
2020-10-11 15:39:15 -07:00
"scrapli",
"httpx",
2021-09-15 18:25:37 -07:00
]:
if name not in seen:
seen.add(name.split(".")[0])
logging.getLogger(name).handlers = [intercept_handler]
2020-10-11 15:39:15 -07:00
def _log_patcher(record):
"""Patch for exception handling in logger.
See: https://github.com/Delgan/loguru/issues/504
"""
exception = record["exception"]
if exception is not None:
fixed = Exception(str(exception.value))
record["exception"] = exception._replace(value=fixed)
2021-09-26 16:50:25 -07:00
def init_logger(level: str = "INFO"):
2020-04-14 10:24:20 -07:00
"""Initialize hyperglass logging instance."""
2021-09-26 16:50:25 -07:00
# Reset built-in Loguru configurations.
2020-04-14 10:24:20 -07:00
_loguru_logger.remove()
2021-09-26 16:50:25 -07:00
if sys.stdout.isatty():
# Use Rich for logging if hyperglass started from a TTY.
_loguru_logger.add(
sink=RichHandler(
rich_tracebacks=True,
level=level,
tracebacks_show_locals=True,
log_time_format="[%Y%m%d %H:%M:%S]",
),
format=_FMT_BASIC,
level=level,
enqueue=True,
)
else:
# Otherwise, use regular format.
_loguru_logger.add(sys.stdout, format=_FMT, level=level, enqueue=True)
_loguru_logger.configure(levels=_LOG_LEVELS, patcher=_log_patcher)
2021-09-26 16:50:25 -07:00
2020-04-14 10:24:20 -07:00
return _loguru_logger
2021-09-26 16:50:25 -07:00
log = init_logger()
2020-04-14 10:24:20 -07:00
2020-09-28 14:43:17 -07:00
logging.addLevelName(25, "SUCCESS")
2021-09-26 16:50:25 -07:00
def _log_success(self: "LoguruLogger", message: str, *a: t.Any, **kw: t.Any) -> None:
2020-09-28 14:43:17 -07:00
"""Add custom builtin logging handler for the success level."""
if self.isEnabledFor(25):
self._log(25, message, a, **kw)
logging.Logger.success = _log_success
2020-04-14 10:24:20 -07:00
2021-09-26 16:50:25 -07:00
def enable_file_logging(
log_directory: "Path", log_format: "LogFormat", log_max_size: "ByteSize", debug: bool
) -> None:
2020-04-14 10:24:20 -07:00
"""Set up file-based logging from configuration parameters."""
2021-09-26 16:50:25 -07:00
log_level = "DEBUG" if debug else "INFO"
2020-04-14 10:24:20 -07:00
if log_format == "json":
2020-04-15 11:17:03 -07:00
log_file_name = "hyperglass.log.json"
2020-04-14 10:24:20 -07:00
structured = True
else:
2020-04-15 11:17:03 -07:00
log_file_name = "hyperglass.log"
2020-04-14 10:24:20 -07:00
structured = False
log_file = log_directory / log_file_name
if log_format == "text":
2021-09-26 16:50:25 -07:00
now_str = datetime.utcnow().strftime("%B %d, %Y beginning at %H:%M:%S UTC")
header_lines = (
f"# {line}"
for line in (
f"hyperglass {__version__}",
f"Logs for {now_str}",
f"Log Level: {log_level}",
)
2020-04-14 10:24:20 -07:00
)
2021-09-26 16:50:25 -07:00
header = "\n" + "\n".join(header_lines) + "\n"
2020-04-14 10:24:20 -07:00
with log_file.open("a+") as lf:
2021-09-26 16:50:25 -07:00
lf.write(header)
_loguru_logger.add(
enqueue=True,
sink=log_file,
format=_FMT_FILE,
serialize=structured,
level=log_level,
encoding="utf8",
rotation=log_max_size.human_readable(),
2020-09-28 14:43:17 -07:00
)
2021-09-26 16:50:25 -07:00
log.debug("Logging to file {!s}", log_file)
2020-04-14 10:24:20 -07:00
2021-09-26 16:50:25 -07:00
def enable_syslog_logging(syslog_host: str, syslog_port: int) -> None:
2020-04-14 10:24:20 -07:00
"""Set up syslog logging from configuration parameters."""
2020-09-28 14:43:17 -07:00
# Standard Library
2020-04-14 10:24:20 -07:00
from logging.handlers import SysLogHandler
2021-09-26 16:50:25 -07:00
_loguru_logger.add(
2021-09-12 15:09:24 -07:00
SysLogHandler(address=(str(syslog_host), syslog_port)), format=_FMT_BASIC, enqueue=True,
2020-04-14 10:24:20 -07:00
)
2021-09-26 16:50:25 -07:00
log.debug(
2020-09-28 14:43:17 -07:00
"Logging to syslog target {}:{} enabled", str(syslog_host), str(syslog_port),
2020-04-14 10:24:20 -07:00
)