英文:
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.log
,task2.log
,task3.log
等等。
但是我不太清楚如何设置这个功能。我尝试在每个 for 循环的开头只设置 logging.basicConfig(filename=task)
,但似乎不起作用。有任何想法吗?
<details>
<summary>英文:</summary>
Tech: Python 3.11.3
```python
import logging
logging.basicConfig(
level=logging.DEBUG,
filename="logFilePath.log",
format=loggingFormat,
datefmt="%Y-%m-%d %I:%M:%S %p",
style="%",
)
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 ["task1", "task2", "task3"]:
logger.info(f"this line is written to {task}.log file")
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:
"""Example of logging to separate files in custom format"""
import logging
import time
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)
class LoggingFormatterTZISO(logging.Formatter):
"""Customized logging.Formatter using ISO-8601 timestamp with tz"""
default_time_format: str = "%Y-%m-%dT%H:%M:%S"
default_msec_format: str = "%s.%03d"
default_tz_format: str = "%z"
def formatTime(self, record: logging.LogRecord, datefmt: str | None = None) -> str:
"""Format asctime from record.created adding ms and tz offset suffix"""
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"{self.default_msec_format}{timezone_formatted}" % (
timestamp_formatted,
record.msecs,
)
log_formatter = LoggingFormatterTZISO("%(asctime)s:%(name)s:%(levelname)s:%(message)s")
for task in ["task1", "task2", "task3"]:
file_handler = logging.FileHandler(f"{task}.log")
file_handler.setFormatter(log_formatter)
root_logger.addHandler(file_handler)
logging.info("this line is written to %s.log file", task)
root_logger.removeHandler(file_handler)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论