[英]How to install Tensorflow via conda for Python 3.10.*?
[英]Python 3.10. TimedRotatingFileHandler writes in different file
我正在嘗試使用 python 3.10 中的日志記錄模塊來創建每日日志文件。 這是我的處理方式:
測試.py
cwd = os.path.dirname(os.path.realpath(__file__))
# configure logger
logging.config.fileConfig(Path(cwd, "logging.ini"))
logger = logging.getLogger("test")
for i in range(10):
logger.log(logging.INFO, "bonjour")
time.sleep(1)
類CustomLogging.py
class CustomTimedRotatingFileHandler(logging.handlers.
TimedRotatingFileHandler):
def __init__(self, prefix, when, backupCount):
cwd = os.path.dirname(os.path.realpath(__file__))
self.dir_log = Path(cwd, "Logs")
file_path = Path(self.dir_log, f"{prefix}.log")
log_files = Path(self.dir_log).glob("**/*.log")
logging.handlers\
.TimedRotatingFileHandler.__init__(self,
file_path,
when=when,
backupCount=backupCount)
和 logging.ini
[loggers]
keys=root, test
[handlers]
keys=customLogging_info, consoleHandler
[formatters]
keys=main
[handler_consoleHandler]
class=StreamHandler
level=CRITICAL
formatter=main
args=(sys.stdout,)
[logger_test]
level=DEBUG
handlers=customLogging_info
qualname=test
[logger_root]
handlers=consoleHandler
[handler_customLogging_info]
level=DEBUG
class=classCustomLogging.CustomTimedRotatingFileHandler
formatter=main
args = ("Debug","S", 2)
[formatter_main]
class=classCustomLogging.CustomFormatter
在測試時,我除了只有 2 個文件每秒鍾旋轉一次之外,但我得到了:
Debug.log
Debug.log.2022-02-11_17-46-08
Debug.log.2022-02-11_17-46-09
在 Debug.log 中,每秒鍾都會寫入一個新行但不會附加,就像無論發生什么日志也將寫入此文件一樣。 帶時間戳的文件中的日志似乎很正確。 這是正常行為嗎? 或者錯誤在哪里?
希望我足夠清楚。
我找到了一種方法來實現我的目標,方法是根據這個答案重新實現一些方法
class CustomTimedRotatingFileHandler(logging.handlers.
TimedRotatingFileHandler):
def __init__(self, prefix, when, backupCount):
"""
:param prefix: string, prefix for log file
:param when: frequency of rotation
:param backUpCount: int, number o file to keep
"""
if when == "S":
suffix = "%Y-%m-%d_%H-%M-%S"
elif when == "M":
suffix = "%Y-%m-%d_%H-%M"
elif when == "H":
suffix = "%Y-%m-%d_%H"
elif when == "D" or when == "MIDNIGHT":
suffix = "%Y-%m-%d"
elif when.startswith("W"):
suffix = "%Y-%m-%d"
else:
raise ValueError("Invalid rollover interval specified: %s"
% self.when)
cwd = os.path.dirname(os.path.realpath(__file__))
self.dir_log = Path(cwd, "Logs")
self.prefix = prefix
self.ext = ".log"
filename = Path(self.dir_log, f"{self.prefix}{time.strftime(suffix)}{self.ext}")
log_files =self.dir_log.rglob("*.log")
logging.handlers\
.TimedRotatingFileHandler.__init__(self,
filename,
when=when,
backupCount=backupCount)
def getFilesToDelete(self):
"""
Re-implement base method
"""
fileNames = os.listdir(self.dir_log)
result = []
plen = len(self.prefix)
for fileName in fileNames:
extlen = len(self.ext)
if fileName[:plen] == self.prefix:
suffix = fileName[plen:-extlen]
if self.extMatch.match(suffix):
result.append(os.path.join(self.dir_log, fileName))
result.sort()
if len(result) < self.backupCount:
result = []
else:
result = result[:len(result) - self.backupCount]
return result
def doRollover(self):
"""
Re-implement base method
"""
self.stream.close()
# get the time that this sequence started at and make it a TimeTuple
t = self.rolloverAt - self.interval
self.baseFilename = Path(self.dir_log, f"{self.prefix}{time.strftime(self.suffix)}{self.ext}")
if self.encoding:
self.stream = codecs.open(self.baseFilename, "w", self.encoding)
else:
self.stream = open(self.baseFilename, "w")
self.rolloverAt = self.rolloverAt + self.interval
if self.backupCount > 0:
for s in self.getFilesToDelete():
os.remove(s)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.