Python : clear a log file
Question:
I develop a client-server application and I have log in the server, so I use the logging
module. I would like to create a command in the server to clear the file.
I have test with os.remove()
but after, the log doesn’t work.
Do you have an idea?
Thanks.
Answers:
It might be better to truncate the file instead of removing it. The easiest solution is to reopen the file for writing from your clearing function and close it:
with open('yourlog.log', 'w'):
pass
Just try to add a 'w'
as argument:
fh = logging.FileHandler('debug.log', mode='w')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logger.addHandler(fh)
This worked for me.
Building up on Steffen B’s answer: when using the logging.basicConfig
function, one can also use this to rewrite the file instead of appending to it:
logging.basicConfig(
# specify the filename
filename=<PATH TO THE FILE>,
# If filename is specified, open the file in this mode. Defaults to 'a'.
filemode="w",
)
More information can be found in the dedicated section of the ‘logging’ module’s documentation.
I develop a client-server application and I have log in the server, so I use the logging
module. I would like to create a command in the server to clear the file.
I have test with os.remove()
but after, the log doesn’t work.
Do you have an idea?
Thanks.
It might be better to truncate the file instead of removing it. The easiest solution is to reopen the file for writing from your clearing function and close it:
with open('yourlog.log', 'w'):
pass
Just try to add a 'w'
as argument:
fh = logging.FileHandler('debug.log', mode='w')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logger.addHandler(fh)
This worked for me.
Building up on Steffen B’s answer: when using the logging.basicConfig
function, one can also use this to rewrite the file instead of appending to it:
logging.basicConfig(
# specify the filename
filename=<PATH TO THE FILE>,
# If filename is specified, open the file in this mode. Defaults to 'a'.
filemode="w",
)
More information can be found in the dedicated section of the ‘logging’ module’s documentation.