【发布时间】:2022-01-17 11:49:09
【问题描述】:
使用多处理时无法在 python 中按分钟创建日志文件
import multiprocessing
import logging.handlers
import time
import logging.handlers
import multiprocessing
log_file_name = "test1.log"
logging_level = logging.DEBUG
formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
handler = logging.handlers.TimedRotatingFileHandler(log_file_name, when='M', interval=1)
handler.suffix = "%Y-%m-%d"
handler.setFormatter(formatter)
logger = logging.getLogger(log_file_name)
logger.addHandler(handler)
logger.setLevel(logging_level)
def main_1():
print("main 1")
logger.info("A Sample Log Statement main_1 ")
time.sleep(2)
logger.info("A Sample Log Statement main_1 ")
def main_2():
print("main 2")
logger.info("A Sample Log Statement main_2 ")
time.sleep(2)
logger.info("A Sample Log Statement main_2 ")
def isReady():
while (True):
p1 = multiprocessing.Process(target=main_1)
p2 = multiprocessing.Process(target=main_2)
p1.start()
p2.start()
p1.join()
p2.join()
if __name__ == "__main__":
isReady()
**Error:**
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'D:\\user2\\WorkSapace\\MULTI\\FileTransfer_dec_06\\test1.log' -> 'D:\\venkatareddy.m\\WorkSapace\\Uniper\\FileTransfer_dec_06\\test1.log.2021-12-13'
Call stack:
File "<string>", line 1, in <module>
File "C:\Program Files\Python39\lib\multiprocessing\spawn.py", line 116, in spawn_main
exitcode = _main(fd, parent_sentinel)
File "C:\Program Files\Python39\lib\multiprocessing\spawn.py", line 129, in _main
return self._bootstrap(parent_sentinel)
File "C:\Program Files\Python39\lib\multiprocessing\process.py", line 315, in _bootstrap
self.run()
File "C:\Program Files\Python39\lib\multiprocessing\process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "D:\user2\WorkSapace\MULTI\FileTransfer_dec_06\logging_2_new.py", line 27, in main_2
logger.info("A Sample Log Statement main_2 ")
Message: 'A Sample Log Statement main_2 '
Arguments: ()
--- Logging error ---
Traceback (most recent call last):
【问题讨论】:
标签: python logging multiprocessing