Untitled

 avatar
unknown
plain_text
5 months ago
3.3 kB
1
Indexable
import os
from dotenv import load_dotenv
import logging
from tddatadoglogger.handler import DatadogLogHandler
from pythonjsonlogger.jsonlogger import JsonFormatter
import time
import urllib3
from urllib3.exceptions import MaxRetryError, HTTPError, ConnectionError, TimeoutError, NewConnectionError, NameResolutionError

# Understand various log levels
# DEBUG: Detailed information, typically of interest only when diagnosing problems.
# INFO: Confirmation that things are working as expected.
# WARNING: 
# ERROR: An indication that something has gone wrong.
# CRITICAL: A serious error, indicating that the program itself may be unable to continue running.


# Load the environment variables
load_dotenv()

def logger(name: str = None):

    # create a logger
    logger = logging.getLogger(name)

    
    # if logger.hasHandlers():
    #     logger.handlers.clear()

    # if not logger.handlers:
    # set the log level to the environment variable or default to DEBUG
    log_level = os.getenv("LOG_LEVEL", "INFO").upper()
    logger.setLevel(log_level)

    # create a logging format and add it to the handlers
    formatter = JsonFormatter(
        fmt="%(asctime)s %(levelname)s %(name)s %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )

    env = os.getenv("ENV", "local").lower()

    if env == "local":
        # create a console handler and set the level to debug
        # logging.basicConfig(level=logging.DEBUG)
        consoleHandler = logging.StreamHandler()
        consoleHandler.setLevel(log_level)
        # set the formatter for the console handler
        consoleHandler.setFormatter(formatter)
        # add the handlers to the logger
        logger.addHandler(consoleHandler)

    # add DataDog handler if not local
    else:
        retry_attempts = 3
        for attempt in range(retry_attempts):
            try:
                ddHandler = DatadogLogHandler()
                ddHandler.setFormatter(formatter)
                logger.addHandler(ddHandler)
                break
            except (ConnectionError, TimeoutError, MaxRetryError, NameResolutionError, NewConnectionError, urllib3.exceptions.HTTPError) as e:
                logger.error(f"Failed to connect to Datadog. Attempt {attempt + 1} of {retry_attempts}.: {e}")
                if attempt < retry_attempts - 1:
                    time.sleep(2 ** attempt) # exponential backoff (1s, 2s, 4s, 8s, 16s)
                else:
                    logger.error("Max retries reached. Logging to console only.")
            except Exception as e:
                logger.error(f"Failed to connect to Datadog. Logging to console only.: {e}", exc_info=True)
                # create a console handler and set the level to debug
                # logging.basicConfig(level=logging.DEBUG)
                consoleHandler = logging.StreamHandler()
                consoleHandler.setLevel(log_level)
                consoleHandler.setFormatter(formatter)
                logger.addHandler(consoleHandler)
                break


    return logger

# keep the name as root for the default logger to be used for multiple modules
# def get_logger(name: str = None):
#     if name:
#         return logging.getLogger(name)
#     return logging.getLogger()
Editor is loading...
Leave a Comment