Python Forum
create new log file on logging? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: create new log file on logging? (/thread-36710.html)



create new log file on logging? - korenron - Mar-21-2022

Hello,
I'm using logging and I have notice that the file is not clean after reboot (program start again)
what do I need to do in order to "clean" the log file ?

this is what I have :
import logging
logging.basicConfig(filename='/home/pi/logs/App1_Log.log', level=logging.INFO, format='%(asctime)s %(message)s')
.
.
.
.

logging.info('%s:%s',  Data)
Thanks ,


RE: create new log file on logging? - deanhystad - Mar-21-2022

mode = "w" in the config command.


RE: create new log file on logging? - korenron - Mar-21-2022

Thanks

can I also do the following (is this "legal"?)
check the size of the file , and if it's more then a wanted size - save\delete it and then start the logging in mode ='w' ?


RE: create new log file on logging? - deanhystad - Mar-21-2022

A log file is a file. Do whatever you want.


RE: create new log file on logging? - bowlofred - Mar-21-2022

You can add a handler of type RotatingFileHandler. Check the documentation and make sure you don't set either maxBytes or backupCount to 0. You could modify your earlier logging setup like so:

import logging
from logging.handlers import RotatingFileHandler
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(message)s'),
    handlers=[RotatingFileHandler('/home/pi/logs/App1_log.log', maxBytes=1000000, backupCount=4),
    )



RE: create new log file on logging? - snippsat - Mar-21-2022

I would advice to use Loguru.
Usage is simpler and cleaner(no boilerplate),than the one in standard library.
from loguru import logger
import time
#logger.remove() # Only info to file
logger.add("file.log", rotation="2 day")

@logger.catch
def foo():
    return 1 / 0

foo()
[Image: kPV7uG.png]


RE: create new log file on logging? - korenron - Mar-22-2022

thank you both
I will try both ways

Thanks !