Use the same logging.Handler in different main files

Cheers!

I am developping a Django Projekt and I want to display my backend loggings to the forntend. Thats why i created a central logging Handler that pushes logs into a buffer. Every 20 sec my frontend sends a request to flush the buffer and display the log events.

Central Loging Class (log.py):

import logging

class BufferedLogHandler(logging.Handler):
    def __init__(self):
        super().__init__()
        self.log_buffer = []  # Lokaler Puffer für Logs

    def emit(self, record):
        log_entry = self.format(record)  # Format den Log-Eintrag
        self.log_buffer.append(log_entry)
    
    def create_external_log(self, level=None, timestamp=None, message=None):
        asctime = timestamp
        msg = message
        record = logging.LogRecord(
                        level=level,   
                        msg=msg, 
                        asctime=asctime,
                        lineno=0,
                        exc_info=None,
                        args=None,
                        name= None,
                        pathname="frontend",
                    )
        self.emit(record=record)
        return BufferedLogHandler.create_empty_response()

    def flush_buffer(self):
        logs_to_send = self.log_buffer[:]
        print(f'logs_to_send:{logs_to_send}')
        print("---------------------")
        self.log_buffer = []
        return logs_to_send
    
    @staticmethod
    def create_empty_response():
        response = {'message':""}
        return response
    
buffered_handler = BufferedLogHandler()


def setup_logger(bufferedHandler):
    # Den Logger holen (Root-Logger oder benannten Logger)
    logger = logging.getLogger()  # Du kannst auch den Root-Logger verwenden

    # Setze das Log-Level (z.B. DEBUG, INFO)
    logger.setLevel(logging.DEBUG)

    # Erstelle einen Handler (z.B. für Konsole oder Datei)
    file_handler = logging.FileHandler('myapp.log')  # Für eine Log-Datei

    # Erstelle ein Format für die Log-Nachrichten
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(filename)s - %(lineno)d - %(message)s')

    # Setze das Format für beide Handler
    bufferedHandler.setFormatter(formatter)
    file_handler.setFormatter(formatter)

    # Füge beide Handler dem Logger hinzu
    logger.addHandler(buffered_handler)
    logger.addHandler(file_handler)

    return logger

My first main class is the manage.py:

from mypath import log
logger = log.setup_logger(log.buffered_handler)
...
logger.info("Logs have been sent to the frontend.")

My second main class is the generate_pictures.py (management/commands/generate_picutres.py)

from another_relative_path import log
logger = log.setup_logger(log.buffered_handler)
...
logger.info("Picture has been created!")

I cannot seem to get both main files to interact with the same buffer in the logging.handler object. When checking the IDs of each imported object log.buffered_handler they dont match.

What have I missed? How can i access the same buffer from both files?

If you want to have a share logger in all your modules, you should create it in a single place.

I would make that place your log.py file. At the end of it, create the logger:

logger = setup_logger(buffered_handler)

and then in your other modules import it with

from mypath.log import logger

which you can use directly.

Вернуться на верх