如何使用Python创建滚动记录器

时间:2019-05-18 00:34:17

标签: python logging

我正在尝试为类似于Linux自动滚动记录器的应用程序创建滚动记录器。记录器应创建一个名为logs的目录(如果不存在),并在每次运行该应用程序时创建一个新的日志文件。我希望程序的上限为10个名为log0000.loglog0010.log的日志文件。如果logs目录中的文件超过10个,它将删除最旧的日志文件,然后将所有文件移位/滚动/重命名以为当前日志腾出空间。

enter image description here

由于文件数量超过10个,因此应删除log0000.log并重命名每个日志文件,以便为新文件腾出空间。每次程序运行时,我都实现了创建日志逻辑,但是当目录中有10个以上的文件时,我很难转移日志。

import os
import time
import logging

class RollingLogger(object):
    def __init__(self):
        self.NUMBER_OF_LOGS = 10
        self.initialize_logger_settings()

    def initialize_logger_settings(self):
        """Set logger configuration settings"""

        self.initialize_log_directory()
        logging.basicConfig(filename= self.path + self.filename, 
                            filemode='w', 
                            level=logging.INFO, 
                            format='%(asctime)s.%(msecs)03d,%(message)s',
                            datefmt='%d-%b-%y,%H:%M:%S')
        logging.info('Successfully loaded logger configuration settings')

    def initialize_log_directory(self):
        """Create directory and log file"""

        self.path = 'logs/'

        if not os.path.exists(self.path):
            os.makedirs(self.path)
            self.filename = 'log0000.log'
        else:
            self.filename = self.get_next_log_file_name()

    def get_next_log_file_name(self):
        """Scans log directory for latest log file and returns a new filename"""

        def extract_digits(filename):
            s = ''
            for char in filename:
                if char.isdigit():
                    s += char
            return int(s)

        l = [extract_digits(filename) for filename in os.listdir(self.path)]
        # Directory is empty
        if not l:
            return 'log0000.log'
        # Directory has files so find latest
        else:
            latest_file_number = max(l)
            return 'log' + '{0:04d}'.format(latest_file_number + 1) + '.log'

logger = RollingLogger()

2 个答案:

答案 0 :(得分:0)

基本上,您应该这样做:

  • 检查您是否已达到最大文件数量
  • 删除最后一个文件
  • 重命名文件-8-> 9、7-> 8,依此类推
  • 创建文件号0

您的else子句应如下所示:

else:
    latest_file_number = max(l)
    if latest_file_number >= self.NUMBER_OF_LOGS - 1:
        largest_file_name = self.path + 'log' + '{0:04d}'.format(latest_file_number) + '.log'
        os.remove(largest_file_name)
        for i in range(self.NUMBER_OF_LOGS - 1, 0, -1):
            name1 = self.path + 'log' + '{0:04d}'.format(i - 1) + '.log'
            name2 = self.path + 'log' + '{0:04d}'.format(i) + '.log'
            os.rename(name1, name2)
        return 'log0000.log'
    return 'log' + '{0:04d}'.format(latest_file_number + 1) + '.log'

还请注意,如果要有10个文件,它们的编号将在0-9范围内。

答案 1 :(得分:0)

1创建logger.ini文件

[loggers]
keys = root

[handlers]
keys = rotatingFileHandler,streamHandler,errorHandler

[formatters]
keys = simpleFmt

[logger_root]
level = DEBUG
handlers = rotatingFileHandler,streamHandler,errorHandler

[handler_rotatingFileHandler]
class = handlers.TimedRotatingFileHandler
level = INFO
formatter = simpleFmt
args = (os.path.abspath(os.getenv("LOG_PATH") + "/default.log"),"midnight", 1, 6,'utf-8')


[handler_errorHandler]
class = handlers.TimedRotatingFileHandler
level = ERROR
formatter = simpleFmt
args = (os.path.abspath(os.getenv("LOG_PATH") + "/error.log"), "midnight", 1, 6,'utf-8')

[handler_streamHandler]
level = INFO
class = StreamHandler
formatter = simpleFmt
args = (sys.stdout,)

[formatter_simpleFmt]
format = %(asctime)s %(pathname)s(%(lineno)d): %(levelname)s %(message)s

2使用ini文件在my_logger.py中初始化

def get_logger(name='root'):
    import logging.config
    import os
    conf_log = os.path.abspath(os.getcwd() + "/logger.ini")
    logging.config.fileConfig(conf_log)
    return logging.getLogger(name)


LOGGER = get_logger()

3设置log_path

os.environ["LOG_PATH"] = "d:/tmp/log/viot"

4使用LOGGER记录

from my_logger import LOGGER 
LOGGER.debug("log msg")