我正在尝试使用TimedRotatingFileHandler将每日日志保存在单独的日志文件中。 旋转按预期完美地工作,但我不喜欢它的工作方式是命名文件。
如果我将日志文件设置为my_log_file.log,那么这将是“今天”的日志文件,当它在午夜更改时,它将被重命名为my_log_file.log.2014-07-08
,最后没有.log扩展名,并且将为新的一天创建新的my_log_file.log
。
我想要的是将旧文件重命名为my_log_file.2014-07-08.log
甚至my_log_file-2014-07-08.log
,主要是最后的.log,而不是中间。
此外,我希望“今天的”日志文件已经以今天的日期命名,就像旧日期一样。
有没有办法这样做?
我发现我可以使用以下内容对后缀进行个性化设置:
handler.suffix =“%Y-%m-%d”
但是我没有办法删除内部.log部分并强制当前日志文件添加后缀。
答案 0 :(得分:5)
我创建了一个ParallelTimedRotatingFileHandler类,主要目的是允许多个进程并行写入日志文件。 这个类解决了并行进程的问题:
Service
,日志记录不会转到例如Service.log
,但今天是Service.2014-08-18.log
,明天是Service.2014-08-19.log
。 a
(追加)模式而不是w
打开文件以允许并行写入。logging
模块没有预见到并行进程,我应该使用SocketHandler,但至少在我的环境中,这是可行的。代码只是标准Python handlers.py模块中代码的一个细微变化。当然版权所有者的版权。
以下是代码:
import logging
import logging.handlers
import os
import time
import re
class ParallelTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, postfix = ".log"):
self.origFileName = filename
self.when = when.upper()
self.interval = interval
self.backupCount = backupCount
self.utc = utc
self.postfix = postfix
if self.when == 'S':
self.interval = 1 # one second
self.suffix = "%Y-%m-%d_%H-%M-%S"
self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$"
elif self.when == 'M':
self.interval = 60 # one minute
self.suffix = "%Y-%m-%d_%H-%M"
self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}$"
elif self.when == 'H':
self.interval = 60 * 60 # one hour
self.suffix = "%Y-%m-%d_%H"
self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}$"
elif self.when == 'D' or self.when == 'MIDNIGHT':
self.interval = 60 * 60 * 24 # one day
self.suffix = "%Y-%m-%d"
self.extMatch = r"^\d{4}-\d{2}-\d{2}$"
elif self.when.startswith('W'):
self.interval = 60 * 60 * 24 * 7 # one week
if len(self.when) != 2:
raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when)
if self.when[1] < '0' or self.when[1] > '6':
raise ValueError("Invalid day specified for weekly rollover: %s" % self.when)
self.dayOfWeek = int(self.when[1])
self.suffix = "%Y-%m-%d"
self.extMatch = r"^\d{4}-\d{2}-\d{2}$"
else:
raise ValueError("Invalid rollover interval specified: %s" % self.when)
currenttime = int(time.time())
logging.handlers.BaseRotatingHandler.__init__(self, self.calculateFileName(currenttime), 'a', encoding, delay)
self.extMatch = re.compile(self.extMatch)
self.interval = self.interval * interval # multiply by units requested
self.rolloverAt = self.computeRollover(currenttime)
def calculateFileName(self, currenttime):
if self.utc:
timeTuple = time.gmtime(currenttime)
else:
timeTuple = time.localtime(currenttime)
return self.origFileName + "." + time.strftime(self.suffix, timeTuple) + self.postfix
def getFilesToDelete(self, newFileName):
dirName, fName = os.path.split(self.origFileName)
dName, newFileName = os.path.split(newFileName)
fileNames = os.listdir(dirName)
result = []
prefix = fName + "."
postfix = self.postfix
prelen = len(prefix)
postlen = len(postfix)
for fileName in fileNames:
if fileName[:prelen] == prefix and fileName[-postlen:] == postfix and len(fileName)-postlen > prelen and fileName != newFileName:
suffix = fileName[prelen:len(fileName)-postlen]
if self.extMatch.match(suffix):
result.append(os.path.join(dirName, fileName))
result.sort()
if len(result) < self.backupCount:
result = []
else:
result = result[:len(result) - self.backupCount]
return result
def doRollover(self):
if self.stream:
self.stream.close()
self.stream = None
currentTime = self.rolloverAt
newFileName = self.calculateFileName(currentTime)
newBaseFileName = os.path.abspath(newFileName)
self.baseFilename = newBaseFileName
self.mode = 'a'
self.stream = self._open()
if self.backupCount > 0:
for s in self.getFilesToDelete(newFileName):
try:
os.remove(s)
except:
pass
newRolloverAt = self.computeRollover(currentTime)
while newRolloverAt <= currentTime:
newRolloverAt = newRolloverAt + self.interval
#If DST changes and midnight or weekly rollover, adjust for this.
if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc:
dstNow = time.localtime(currentTime)[-1]
dstAtRollover = time.localtime(newRolloverAt)[-1]
if dstNow != dstAtRollover:
if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
newRolloverAt = newRolloverAt - 3600
else: # DST bows out before next rollover, so we need to add an hour
newRolloverAt = newRolloverAt + 3600
self.rolloverAt = newRolloverAt
答案 1 :(得分:4)
据我所知,没有办法直接实现这一点。
您可以尝试的一种解决方案是覆盖默认行为。
TimedRotatingFileHandler class
并覆盖doRollover() function.
<PythonInstallDir>/Lib/logging/handlers.py
这样的事情:
class MyTimedRotatingFileHandler(TimedRotatingFileHandler):
def __init__(self, **kwargs):
TimedRotatingFileHandler.__init__(self, **kwargs)
def doRollover(self):
# Do your stuff, rename the file as you want
答案 2 :(得分:0)
我在Python 3.7中使用了解决方案https://stackoverflow.com/a/25387192/6619512,这是一个很好的解决方案。
但是对于'午夜' when 参数和 when 以'W'开头的参数,由于引入了 atTime 参数,因此该参数不起作用并在TimedRotatingFileHandler类中使用。
要使用此解决方案,请使用以下__init__行:
def __init__(self, filename, when='h', interval=1, backupCount=0,
encoding=None, delay=False, utc=False, atTime=None, postfix = ".log"):
还要在__init__声明的内容中添加以下内容:
self.postfix = postfix
答案 3 :(得分:0)
这是一个简单的解决方案:向处理程序添加自定义命名函数。日志实用程序将调用您的 namer 函数来创建滚动文件的名称,就像 Jester 最初在 6 年前(!)前用 filename.log.YYYYMMDD 指出的那样,因此我们需要将 .log 部分“移动”到最后:
def namer(name):
return name.replace(".log", "") + ".log"
然后在您设置处理程序后,只需将您的函数分配给它的 namer 属性:
handler.namer = namer
这是我的完整日志初始化脚本,我是 Python 新手,欢迎批评/建议:
import os
import logging
from logging.handlers import TimedRotatingFileHandler
from config import constants
def namer(name):
return name.replace(".log", "") + ".log"
def init(baseFilename):
logPath = constants.LOGGING_DIR
envSuffix = '-prod' if constants.ENV == 'prod' else '-dev'
logFilename = os.path.join(logPath, baseFilename + envSuffix + '.log')
print(f"Logging to {logFilename}")
handler = TimedRotatingFileHandler(logFilename,
when = "midnight",
backupCount = 30,
encoding = 'utf8')
handler.setLevel(logging.DEBUG)
handler.suffix = "%Y%m%d"
handler.namer = namer # <-- Here's where I assign the custom namer.
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s [%(module)s:%(lineno)d]')
handler.setFormatter(formatter)
logging.basicConfig(
handlers = [handler],
format = '%(asctime)s %(levelname)s %(message)s [%(module)s:%(lineno)d]',
level = logging.DEBUG,
datefmt = '%Y-%m-%d %H:%M:%S')
if __name__ == '__main__':
init('testing')
logging.error("ohai")
logging.debug("ohai debug")
logging.getLogger().handlers[0].doRollover()
logging.error("ohai next day")
logging.debug("ohai debug next day")