[英]Add File Extension in TimedRotatingFileHandler
I am trying to implement the python logging using TimedRotatingFileHandler我正在尝试使用TimedRotatingFileHandler实现 python 日志记录
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".第一次使用此代码时,我得到了预期的文件名“info.log”,但是当它翻到午夜时,我得到的文件名是“info.log.2020-05-22”,但我是什么期望是“info.2020-05-22.log”。
How i can append the handler suffix before to file extension(.log)?我如何将 append 处理程序后缀放在文件扩展名(.log)之前?
You should use a custom namer
:您应该使用自定义namer
:
handler.namer = lambda name: name + ".log"
Unfortunately, the namer function gets the processed name.不幸的是,命名器 function 获得了处理后的名称。 The name param would be like "info.log.2020-05-22"
, so you'll end up with "info.log.2020-05-22.log"
.名称参数类似于"info.log.2020-05-22"
,因此您最终会得到"info.log.2020-05-22.log"
。 If double .log
is not acceptable just remove the initial one:如果双.log
是不可接受的,只需删除最初的:
handler.namer = lambda name: name.replace(".log", "") + ".log"
Thanks RafaIS That worked great for me.谢谢 RafaIS 这对我很有用。 I just made one small change.我只是做了一个小改动。 I just removed the.log from the initial file.我刚刚从初始文件中删除了.log。
handler = TimedRotatingFileHandler(".\\Log\\info",'midnight',1)
then used the first lambda option: handler.namer = lambda name: name + ".log"
然后使用第一个 lambda 选项: handler.namer = lambda name: name + ".log"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.