Mojtaba Abdi Khassevan
Mojtaba Abdi Khassevan

Reputation: 539

python logging.basicConfig doesn't overwrite the existing log file

I'm using Python logging.basicConfig method, passing it some arguments including filemode = "w". If it's not specified, it defaults to "a", appending. However, despite specifying it to overwrite the existing log file, it's yet appending.

import logging
# add filemode "w" to overwrite
logging.basicConfig(filename = "sample.log", level = logging.INFO,filemode = "w")
logging.debug("This is a debug message")
logging.info("Informational message")
logging.error("An error has happened!")

Upvotes: 3

Views: 4008

Answers (2)

Pulakesh Dev Das
Pulakesh Dev Das

Reputation: 63

Use the below code and try -

filemode = "w+"

Example

logging.basicConfig(filename = "sample.log",
                    level = logging.INFO,
                    filemode = "w+" )

Upvotes: 6

Andrey Martynov
Andrey Martynov

Reputation: 11

In my case: same trouble in Google Colab: logging.basicConfig(filename="log_file", filemode='w', level=logging.DEBUG) Code does append the log_file, not overwrite...

I apologize in advance for the big message - I try to clarify all the points of the situation. I will make a reservation right away that this effect is not observed when the script is run in PyCharm. I suppose that the problem lies in the fact that in Anaconda (similar to Google Colab, where I encountered the same problem), the code is not executed anew, but using the results of previous executions. The logging process according to the ideology is constantly ready for use from the moment the program is launched. This is probably why there is a rule: (PEP: 282, part "Loggers") *"... Otherwise, if a logger with that name exists, it is returned. If not, a new logger is initialized and returned ... "*In our case, we need to restart the Kernel to clear the contents of the file that stores the logs. For the sake of curiosity, I will try to reset the storage of logs without restarting the Kernel, but this is already an abnormal mode.

https://github.com/python/peps/blob/master/pep-0282.txt#L220

Upvotes: 1

Related Questions