akibabot/akibabot/logging.py

53 lines
1.6 KiB
Python

import sys
import logging
import logging.handlers
from multiprocessing import Queue
def init_loki_logging(config: dict[str, str]):
"""Configures the logging to Loki."""
import logging_loki
queue = Queue(-1)
handler = logging.handlers.QueueHandler(queue)
handler_loki = logging_loki.LokiHandler(
url=config["loki"]["url"],
version="1",
tags={
"application": "akibabot",
},
)
formatter = logging.Formatter(
"name=%(name)s level=%(levelname)s time=%(asctime)s %(message)s",
datefmt="%Y-%m-%d-%H:%M:%S",
)
handler.setFormatter(formatter)
logging.handlers.QueueListener(queue, handler_loki)
logging.getLogger().addHandler(handler)
def init_logging(config: dict[str, str]):
"""Initialises the logging"""
# Check if we should use Loki and configure it, if enabled.
log_config = config.get("logging", {})
loki = config.get("loki", {})
if loki.get("enable", False):
init_loki_logging(config)
# Configure logging to the console, if enabled.
logger = logging.getLogger()
if log_config.get("console", True):
formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
console_handler = logging.StreamHandler(stream=sys.stdout)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
# Set the log level
level = {
"info": logging.INFO,
"debug": logging.DEBUG,
}.get(log_config.get("level", "info"))
logger.setLevel(level)