0

I have an Azure app service and the container has a python file. i'm using the following code to generate the log file

now = datetime.now()
timestr = now.strftime("%Y%m%d")
logfile = 'log'+timestr
logHandler = RotatingFileHandler(filename=logfile, mode='a', maxBytes=10 * 1024 * 1024, backupCount=10)
logFormatter = logging.Formatter('[%(levelname)s]\t: %(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logHandler.setFormatter( logFormatter )
logger = logging.getLogger( 'MyLogger' )
logger.addHandler( logHandler )

However when i start the app service for the first time, it gives me a log file with the current date. But the file name does not update later. what needs to be done so that a new file is created according to the date.

Nikita
  • 63
  • 7
  • what is the behavior you expect? a new log-file each day? – FObersteiner Aug 22 '20 at 16:03
  • @MrFuppes: yes a new log file each day – Nikita Aug 24 '20 at 07:29
  • my *guess* would be that the line `now = datetime.now()` is only called once, when the logger is instantiated. after that, it just keeps on logging to the initial file. you might have to update / recreate the logger if the date changes. I'm no expert on this but maybe it helps to search in that direction, like e.g. [here](https://stackoverflow.com/questions/13839554/how-to-change-filehandle-with-python-logging-on-the-fly-with-different-classes-a). – FObersteiner Aug 24 '20 at 07:50
  • @MrFuppes: Yes this is what is happening. The new file is created only when i restart the service. – Nikita Aug 24 '20 at 18:22

1 Answers1

0

If you want to create daily log file, you should use TimedRotatingFileHandler. And in you case, you would need to change the following line to TimedRotatingFileHandler('log/mylog.log', when="midnight", interval=1, encoding='utf8')

For example

import logging
from logging.handlers import TimedRotatingFileHandler
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
handler = TimedRotatingFileHandler('log/mylog.log', when="midnight", interval=1, encoding='utf8')
handler.suffix = "%Y-%m-%d"
handler.setFormatter(formatter)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(handler)

For more details, please refer to here and here

Jim Xu
  • 21,610
  • 2
  • 19
  • 39