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

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


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.


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 osimport logginglog_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)


When you run

LOG = logging.getLogger('log_filename')

for the first time a global variable is created.Hence, you could also add the following code to the script above:

global LOGif LOG is not None:    print("found logger !")else:    ("no global variable logger found")