每天如何使用Python登录到新目录?

时间:2019-08-14 22:18:53

标签: python logging python-logging

我正在建立一个读取系统,该系统从许多仪器中获取数据,并且需要将数据记录到日志文件中。该系统一次将运行数周,因此每天应有一个日志文件。由于这些工具是在这段时间内被操纵的,因此它们可能还具有与其状态相关联的日志文件。

有了这个,我有了一个目录,其中存储了所有日志,例如'C:/ logs'。由于每天都会有多个日志文件,因此我想每天自动在logs文件夹中创建一个新的子目录,因此文件的结构类似于'C:/logs/20190814' for August 14, 'C:/logs/20190815' for the 15th,依此类推。 。然后,在每个日常目录中,我将有许多日志文件,例如'data.log', 'instrument1.log', 'instrument2.log'等。

理想情况下,它们会在每天的午夜滚动。

我一直在使用Python日志记录模块来尝试创建这些日志文件。我已经能够实现TimedRotatingFileHandler,但是问题是

(1)我想根据日期更改日志文件所在的目录,但标题保持不变(例如'C:/logs/20190814/data.log', 'C:/logs/20190815/data.log'

(2)TimedRotatingFileHandler不会以扩展名'%Y%m%d.log'来保存文件,而是以'.log.%Y%m%d'来保存文件,这很不方便。我想每天创建一个新目录,并开始在新目录中写入新日志。

2 个答案:

答案 0 :(得分:0)

这里是一个例子:

import logging
import time

from logging.handlers import TimedRotatingFileHandler

#----------------------------------------------------------------------
def create_timed_rotating_log(path):
""""""
logger = logging.getLogger("Rotating Log")
logger.setLevel(logging.INFO)

handler = TimedRotatingFileHandler(path,
                                   when="m",
                                   interval=1,
                                   backupCount=5)
logger.addHandler(handler)

for i in range(6):
    logger.info("This is a test!")
    time.sleep(75)

#----------------------------------------------------------------------
if __name__ == "__main__":
log_file = "timed_test.log"
create_timed_rotating_log(log_file)

此示例将每分钟对日志进行一次轮换,备份计数为5。更现实的轮换可能是在小时上进行,因此您可以将时间间隔设置为60或将when设置为“ h”。当运行此代码时,它也会创建6个文件,但不是将整数附加到日志文件名,而是将使用strftime格式%Y-%m-%d_%H-%M-%S附加时间戳。

答案 1 :(得分:0)

使用另一个StackOverflow问题中的框架,该问题与我所需要的相似但又不完全相同,因此我能够获得想要的行为。这是用于更新日志记录TimedRotatingFileHandler类的自定义类。

class MyTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, log_title, whenTo="midnight", intervals=1):
    self.when = whenTo.upper()
    self.inter = intervals
    self.log_file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "logs"))
    if not os.path.isdir(self.log_file_path):
        os.mkdir(self.log_file_path)
    if self.when == "S":
        self.extStyle = "%Y%m%d%H%M%S"
    if self.when == "M":
        self.extStyle = "%Y%m%d%H%M"
    if self.when == "H":
        self.extStyle = "%Y%m%d%H"
    if self.when == "MIDNIGHT" or self.when == "D":
        self.extStyle = "%Y%m%d"

    self.dir_log = os.path.abspath(os.path.join(self.log_file_path, datetime.now().strftime(self.extStyle)))
    if not os.path.isdir(self.dir_log):
        os.mkdir(self.dir_log)
    self.title = log_title
    filename = os.path.join(self.dir_log, self.title)
    logging.handlers.TimedRotatingFileHandler.__init__(self, filename, when=whenTo, interval=self.inter, backupCount=0, encoding=None)
    self._header = ""
    self._log = None
    self._counter = 0

def doRollover(self):
    """
    TimedRotatingFileHandler remix - rotates logs on daily basis, and filename of current logfile is time.strftime("%m%d%Y")+".txt" always
    """
    self.stream.close()
    # get the time that this sequence started at and make it a TimeTuple
    t = self.rolloverAt - self.interval
    timeTuple = time.localtime(t)

    self.new_dir = os.path.abspath(os.path.join(self.log_file_path, datetime.now().strftime(self.extStyle)))

    if not os.path.isdir(self.new_dir):
        os.mkdir(self.new_dir)
    self.baseFilename = os.path.abspath(os.path.join(self.new_dir, self.title))
    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
相关问题