3

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!")
2
  • 1
    I tried your code, works fine for me, it does overwrite the log file when filemode = "w" Commented Apr 25, 2020 at 9:25
  • 1
    I tried it again and again after a day but nothing new happened. It keeps appending. Finally I threw the logging section away! Commented Apr 26, 2020 at 7:20

2 Answers 2

7

Use the below code and try -

filemode = "w+"

Example

logging.basicConfig(filename = "sample.log",
                    level = logging.INFO,
                    filemode = "w+" )
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. You can also add a bounty to draw more attention to this question once you have enough reputation. - From Review
Fixed, I hope now the message will be useful in finding a solution to the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.