Add File Extension in TimedRotatingFileHandler
Asked Answered
W

2

6

I am trying to implement the python logging using TimedRotatingFileHandler

i'm getting the problem in adding the file extension in log filename

here is my code

Path(".\\Log").mkdir(parents=True, exist_ok=True)
LOGGING_MSG_FORMAT  = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
LOGGING_DATE_FORMAT = '%m-%d %H:%M:%S'
formatter = logging.Formatter(LOGGING_MSG_FORMAT, LOGGING_DATE_FORMAT)
handler = TimedRotatingFileHandler(".\\Log\\info.log",'midnight',1)
handler.setFormatter(formatter)
handler.setLevel(logging.INFO)
root_logger = logging.getLogger()
root_logger.addHandler(handler)

using this code very first time i'm getting the fileName "info.log" as expected, but when it rolls over to midnight the fileName i'm getting is "info.log.2020-05-22" but what i'm expecting is "info.2020-05-22.log".

How i can append the handler suffix before to file extension(.log)?

Wellfound answered 22/5, 2020 at 6:12 Comment(0)
O
7

You should use a custom namer:

handler.namer = lambda name: name + ".log"

Unfortunately, the namer function gets the processed name. The name param would be like "info.log.2020-05-22", so you'll end up with "info.log.2020-05-22.log". If double .log is not acceptable just remove the initial one:

handler.namer = lambda name: name.replace(".log", "") + ".log"
Oscaroscillate answered 22/5, 2020 at 6:51 Comment(0)
H
2

Thanks RafaIS That worked great for me. I just made one small change. I just removed the .log from the initial file.

handler = TimedRotatingFileHandler(".\\Log\\info",'midnight',1)

then used the first lambda option: handler.namer = lambda name: name + ".log"

Heiskell answered 27/10, 2020 at 15:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.