更改日志文件在执行过程中。

huangapple go评论72阅读模式
英文:

Change log file half way thru execution

问题

import logging

logging.basicConfig(
    level=logging.DEBUG,
    filename="logFilePath.log",
    format=loggingFormat,
    datefmt="%Y-%m-%d %I:%M:%S %p",
    style="%",
)

my_logger.py 类的 __init__ 中有这个代码段,我确保在模块入口的最开始初始化了 my_logger。我在多个类中使用这个 logger,它会将日志写入文件和控制台。一切正常。

但是现在我想要为脚本执行的每个 "任务" 分别记录日志文件。类似这样:

for task in ["task1", "task2", "task3"]:
    logger.info(f"this line is written to {task}.log file")

这样会生成3个不同的日志文件 - task1.logtask2.logtask3.log 等等。

但是我不太清楚如何设置这个功能。我尝试在每个 for 循环的开头只设置 logging.basicConfig(filename=task),但似乎不起作用。有任何想法吗?


<details>
<summary>英文:</summary>

Tech: Python 3.11.3

```python
import logging

logging.basicConfig(
    level=logging.DEBUG,
    filename=&quot;logFilePath.log&quot;,
    format=loggingFormat,
    datefmt=&quot;%Y-%m-%d %I:%M:%S %p&quot;,
    style=&quot;%&quot;,
)

have a my_logger.py class that has this snippet in it's __init__ and I made sure to initialize the my_logger at the very beginning of the module entry. I use this logger in several classes and it writes stuff to file and console. Life is good

But now I want to separate the log files for each "task" that the script does. Something like this

for task in [&quot;task1&quot;, &quot;task2&quot;, &quot;task3&quot;]:
    logger.info(f&quot;this line is written to {task}.log file&quot;)

so there will be 3 different log files - task1.log, task2.log, task3.log, and so on

but can't really figure out how to set this up. I tried setting just logging.basicConfig(filename=task) at the beginning of each for loop, but that doesn't seem to work. Any ideas anyone?

答案1

得分: 1

这是一个自定义格式的日志处理程序示例,可在执行过程中更改输出文件:

英文:

Here's an example of log handler with custom formatting, changing output file during execution:

&quot;&quot;&quot;Example of logging to separate files in custom format&quot;&quot;&quot;

import logging
import time

root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)


class LoggingFormatterTZISO(logging.Formatter):
    &quot;&quot;&quot;Customized logging.Formatter using ISO-8601 timestamp with tz&quot;&quot;&quot;

    default_time_format: str = &quot;%Y-%m-%dT%H:%M:%S&quot;
    default_msec_format: str = &quot;%s.%03d&quot;
    default_tz_format: str = &quot;%z&quot;

    def formatTime(self, record: logging.LogRecord, datefmt: str | None = None) -&gt; str:
        &quot;&quot;&quot;Format asctime from record.created adding ms and tz offset suffix&quot;&quot;&quot;
        if datefmt is None:
            datefmt = self.default_time_format
        converted_record = self.converter(record.created)
        timestamp_formatted = time.strftime(datefmt, converted_record)
        timezone_formatted = time.strftime(self.default_tz_format, converted_record)
        return f&quot;{self.default_msec_format}{timezone_formatted}&quot; % (
            timestamp_formatted,
            record.msecs,
        )


log_formatter = LoggingFormatterTZISO(&quot;%(asctime)s:%(name)s:%(levelname)s:%(message)s&quot;)

for task in [&quot;task1&quot;, &quot;task2&quot;, &quot;task3&quot;]:
    file_handler = logging.FileHandler(f&quot;{task}.log&quot;)
    file_handler.setFormatter(log_formatter)
    root_logger.addHandler(file_handler)
    logging.info(&quot;this line is written to %s.log file&quot;, task)
    root_logger.removeHandler(file_handler)

huangapple
  • 本文由 发表于 2023年6月1日 02:01:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76376199.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定