ThreadPoolExecutor 日志记录?(Python)

And*_*rew 5 python multithreading threadpool python-multithreading

我有一些代码看起来像

with futures.ThreadPoolExecutor(max_workers=2) as executor:
    for function in functions:
        executor.submit(function)
Run Code Online (Sandbox Code Playgroud)

我将如何记录执行程序当前正在处理哪个函数?我可能有也可能没有能力从函数内登录 - 希望执行器本身记录类似的东西

print "handling process {i}".format(i=current_process)
Run Code Online (Sandbox Code Playgroud)

关于如何解决这个问题的任何想法?

Luc*_*rah 4

我想这有点老了,但我偶然发现了这些问题,并认为我应该给出答案。我只是使用了一个包装器,它可以在调用函数之前引用记录器的实例:

import logging
import os
import concurrent.futures


logging.basicConfig(filename=os.path.expanduser('~/Desktop/log.txt'), level=logging.INFO)
logger = logging.getLogger("MyLogger")


def logging_wrapper(func):
    def wrapped(*args, **kwargs):
        logger.info("Func name: {0}".format(func.__name__))
        func(*args, **kwargs)
    return wrapped


def a():
    print('a ran')


def b():
    print('b ran')


with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
    for func in [a, b]:
        executor.submit(logging_wrapper(func))
Run Code Online (Sandbox Code Playgroud)