'Setting log file and report HTML file locations

Below references to questions that have helped me get this far (there's been many more but I didn't save the links unfortunately):

I want to specify the file name and location of both the .log file and the .html report file.

Below is my latest attempt at it.

Function to "create" the fileHandler logger:

def define_file_logger(log_level, formatter, file_location):
    # create directory
    os.makedirs(os.path.dirname(file_location), exist_ok=True)

    # create file handler for logging to file
    file_handler = logging.FileHandler(filename=Path(file_location) / 'log.log')
    file_handler.setLevel(log_level)

    # apply formatter to file handler logger
    file_handler.setFormatter(formatter)

    # request logger
    final_logger = logging.getLogger(__name__)

    # prevent double logs in console
    if final_logger.hasHandlers():
        final_logger.handlers.clear()

    final_logger.propagate = False

    # add handler
    final_logger.addHandler(file_handler)

    # return
    return final_logger

My config.py file (in the root directory):

@pytest.hookimpl(tryfirst=True)
def pytest_load_initial_conftests(args, early_config, parser):
    os.environ['reports_dir'] = str(Path('Reports', f'{datetime.now().strftime("%d.%m.%Y")}', f'{datetime.now().strftime("%H.%M")}'))

My conftest.py file (in the root directory):

@pytest.hookimpl(tryfirst=True)
def pytest_configure(config):
    # set custom options only if none are provided from command line
    if not config.option.htmlpath:
        # set path and file name
        config.option.htmlpath = Path(os.environ['reports_dir']) / 'report.html'
        config.option.self_contained_html = True

When I run this, I get the error:

No such file or directory

I can get it so that the log file is generated in the root directory and the html report in the reports directory if I make this change to the define_file_logger function:

Before:

# create file handler for logging to file
file_handler = logging.FileHandler(filename=Path(file_location) / 'log.log')

After:

# create file handler for logging to file
file_handler = logging.FileHandler(filename='log.log')


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source