NicoCaldo
NicoCaldo

Reputation: 1577

How the logging module in Python manages saving files

I'm using the Python logging module to log what's going on in my application on both on a file and into the terminal.

My code is:

import logging
logging.basicConfig(level=logging.DEBUG, handlers=[  # stream=sys.stdout,
                            logging.FileHandler("debug.log", 'a'),
                            logging.StreamHandler()
                        ], format='%(asctime)s %(levelname)s %(message)s', )

logging.info("This is a LOG INFO message")

Now, as soon as the program runs, it saves the log on a file.

I would like to know how the logging method save this info on the file. Does it opens -> write -> close the file evry time a logging line is called? Do keep the file open until the program ends?

I'm asking because if my software crash for some reasons or the PC reboot, the already written log file is safe or it could be corrupted?

Upvotes: 1

Views: 57

Answers (1)

YoshiMbele
YoshiMbele

Reputation: 999

As the names suggests the handlers you have set here, stream their log messages to the specified sinks. Logging Handler Documentation states that it:

"[...] sends logging output to streams such as sys.stdout, sys.stderr or any file-like object (or, more precisely, any object which supports write() and flush() methods)."

Looking at the Source Code and considering this GitHub Gist since you apparently could use a logging instance with a context manager if you really wanted to, I would make the assumption that your intuition was exactly correct (regarding open > write > close).

Upvotes: 4

Related Questions