1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Logs not being written of parent directory included in filename

Discussão em 'Python' iniciado por Stack, Setembro 12, 2024.

  1. Stack

    Stack Membro Participativo

    I have a function that creates a logger that prints and exports logs to a file:

    # logger.py

    import os
    import pathlib
    import logging
    from dates import get_current_date


    def get_logger(name=__name__, level=logging.DEBUG):
    logger = logging.getLogger(name)
    logger.setLevel(level)

    # Get current date to append to file name
    formatted_date = get_current_date()
    logfile = f"{name}_{formatted_date}.log"
    logfile_output = f"./{os.path.join('Logs', logfile)}"
    os.makedirs(os.path.dirname(logfile_output), exist_ok=True)

    # Create a file handler with detailed formatting for log output
    file_handler = logging.FileHandler(logfile_output , mode="a")
    fformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s : %(message)s')
    file_handler.setFormatter(fformatter)

    # Create a stream handler with simple formatting for cell output
    stream_handler = logging.StreamHandler()
    sformatter = logging.Formatter('%(message)s')
    stream_handler.setFormatter(sformatter)

    # Add the handlers to the logger
    logger.addHandler(file_handler)
    logger.addHandler(stream_handler)

    logger.info('Logger initiated. Logs will be written to %s', logfile_output)

    return logger


    # notebook
    from logger import get_logger

    name = 'dev'
    logger = get_logger(name)

    logger.info('this is a log')

    %sh
    ls Logs # returns nothing
    ls Logs/ # returns nothing


    The idea was to either write the .log files to a Logs folder in the root project directory or same directory as the notebook. The issue is it won't write anything if I include the Logs/ in the logfile_output, but works if I just write it as logfile with a directory (eg logfile.log). I've tried different paths and ways of writing the a Logs folder but nothing happens.

    [​IMG]

    Continue reading...

Compartilhe esta Página