Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add File Extension in TimedRotatingFileHandler

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)?

like image 741
Vinayak Avatar asked Jun 16 '26 02:06

Vinayak


2 Answers

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"
like image 192
RafalS Avatar answered Jun 18 '26 15:06

RafalS


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"

like image 21
MRxParkour Avatar answered Jun 18 '26 16:06

MRxParkour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!