Python logging: create log if not exists or open and continue logging if it does

For anyone who was trying to create a new directory structure like logs/mylogfile.log, as @mightypile mentioned, FileHandler will not create a new directory structure for you. I used os.makedirs to ensure the directory structure.

import os
import logging

log_filename = "logs/output.log"
os.makedirs(os.path.dirname(log_filename), exist_ok=True)
file_handler = logging.FileHandler(output_filename, mode="w", encoding=None, delay=False)

The logging module's FileHandler takes care of that for you. No need for complexity.

The handler takes an optional mode parameter, to specify whether it starts writing or appending data to it.

From the docs:

class logging.FileHandler(filename, mode='a', encoding=None, delay=False)

The specified file is opened and used as the stream for logging. If mode is not specified, 'a' is used.