python - 将 header 写入 python 日志文件,但前提是记录被写入

标签 python logging

fh = logging.FileHandler('example.log',delay = True)
fh.setLevel(logging.INFO)

由于 delay 为 True,除非记录某些内容,否则永远不会写入文件。 此时,文件中的第一行是第一条记录,它将包含 asctime、levelname 等元素

使用 python 2.7.10,是否有一种明智的方法可以在第一次写入不包含这些元素的记录时添加一行(或两行)?

我可以在使用它进行日志记录之前写入文件,但如果我这样做,我最终得到的日志是空的,但标题是空的。

所需的输出可能如下所示:

Using test.fil with option 7
2015-11-01 13:57:58,045 :log_example: INFO     fn:main result:process 4 complete --7 knights said ni
2015-11-01 13:57:58,045 :log_example: INFO     fn:main result:process 3 complete --3 bunnies attacked

谢谢,

最佳答案

子类 FileHandler 以创建您自己的自定义 FileHandleWithHeader,如下所示:

import os
import logging

# Create a class that extends the FileHandler class from logging.FileHandler
class FileHandlerWithHeader(logging.FileHandler):

    # Pass the file name and header string to the constructor.
    def __init__(self, filename, header,  mode='a', encoding=None, delay=0):
        # Store the header information.
        self.header = header

        # Determine if the file pre-exists
        self.file_pre_exists = os.path.exists(filename)

        # Call the parent __init__
        logging.FileHandler.__init__(self, filename, mode, encoding, delay)

        # Write the header if delay is False and a file stream was created.
        if not delay and self.stream is not None:
            self.stream.write('%s\n' % header)

    def emit(self, record):
        # Create the file stream if not already created.
        if self.stream is None:
            self.stream = self._open()

            # If the file pre_exists, it should already have a header.
            # Else write the header to the file so that it is the first line.
            if not self.file_pre_exists:
                self.stream.write('%s\n' % self.header)

        # Call the parent class emit function.
        logging.FileHandler.emit(self, record)

# Create a logger and set the logging level.
logger = logging.getLogger("example")
logger.setLevel(logging.INFO)

# Create a file handler from our new FileHandlerWith Header class and set the
# logging level.
fh = FileHandlerWithHeader('example.log', 'This is my header',  delay=True)
fh.setLevel(logging.INFO)

# Add formatter to the file handler.
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
fh.setFormatter(formatter)

# Add the handler to the logger.
logger.addHandler(fh)

# Since the constructor of the FileHandlerWithHeader was passed delay=True
# the file should not exist until the first log as long as the log file did
# not pre-exist.
print "Ready to write to the the example.log file."
raw_input("Press Enter to continue...")

# Send 3 logs to the logger.
logger.info("First line in the file")
logger.info("Second line in the file")
logger.info("Third line in the file")

# The log file should now be created and only have a header at the begining of
# the file.
print "The example.log file should exist and have a header."

这个脚本应该像在 Python 2.7 中一样运行。如果“example.log”文件已经存在,则不会重新创建 header 。

此解决方案需要了解已找到的日志记录源代码 here 和发现的 python 日志包的一般使用 here .

关于python - 将 header 写入 python 日志文件,但前提是记录被写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33468174/

相关文章:

java - Wildfly 8日志记录,如何从左侧截断记录器名称?

debugging - 如何跟踪 XAML 加载期间发生的情况?

logging - 尝试使用 DynamicProxy 为 StructureMap 制作日志拦截器

python scipy.stats.powerlaw 负指数

python - boto3 说表不存在,但我可以在 AWS CLI 中查询它

python - 从 plotly 保存图像

python - 如何在 postgresql 中使用 datetime 实例作为时间戳?

python - 使用 scikit 处理多标签数据的问题

Git 变更日志 : how to get all changes up to a specific tag?

使用 flogs 的 Flutter 日志 - 它将保存在哪里