python - 在Python中使用concurrent.futures.ProcessPoolExecutor时为每个进程创建一个单独的记录器

标签 python python-3.x logging concurrent.futures

我正在清理大量 CSV 数据转储。我最初使用 unix SE Query 使用 gawk 将单个大文件拆分为较小的文件。如下流程:

     BIG CSV file -> use gawk script + bash -> Small CSV files based on columns

我有大约 12 个分割的 csv 文件,这些文件是使用上述流程创建的,每个文件都有约 170K 行。

我在 Windows 10 计算机上使用 python3.7.7

代码


def convert_raw_data(incoming_line, f_name, line_counter):
     # do some decoding magic
     # catch exception and try to log it into the a logger file under `f_name.log`


def convert_files(dir_name, f_name, dest_dir_name):
    # Open the CSV file
    # Open the Destination CSV file to store decoded data
    line_counter = 1
    for line in csv_reader:
       # convert raw HEX to Floating point values using `convert_raw_data` function call
       line_counter = line_counter + 1
       status = convert_raw_data(csv)
       if status:
          return f'All good for {f_name}.'
       else:
          return f'Failed for {f_name}'

def main():

    # Parse Arguments Logic here

    # get CSV Files and their respective paths
    csv_files = get_data_files_list(args.datasets)

    # decode raw data from each split csv file as an individual process
    with concurrent.futures.ProcessPoolExecutor() as executor:
        results = [ executor.submit(convert_files, dir_name, f_name, dest_dir) for dir_name, f_name in csv_files ]

        for f in concurrent.futures.as_completed(results):
            print(f.result())

要求

我希望在由 ProcessPoolExecutor 生成的每个进程中设置一个名为 f_name.loglogging 记录器,并希望存储日志以及相应的解析文件名。我不确定是否应该使用类似的东西:


def convert_raw_data(...., logger):
    logger.exception(raw_data_here)


def convert_files(....):
    logger = logging.basicConfig(filename=f_name, level=logging.EXCEPTION)

或者在多处理环境中使用日志模块是否有注意事项?

最佳答案

找到了完成此任务的简单方法:

import logging

def create_log_handler(fname):
    logger = logging.getLogger(name=fname)
    logger.setLevel(logging.ERROR)

    fileHandler = logging.FileHandler(fname + ".log")
    fileHandler.setLevel(logging.ERROR)

    logger.addHandler(fileHandler)

    formatter = logging.Formatter('%(name)s %(levelname)s: %(message)s')

    fileHandler.setFormatter(formatter)

    return logger

我在 convert_files(.....) 函数中调用了 create_log_handler ,然后使用了 logger.info 和 logger.error`相应地。

通过将logger作为参数传递给convert_raw_data,我什至能够在每个进程的每个csv文件中记录错误的数据点。

关于python - 在Python中使用concurrent.futures.ProcessPoolExecutor时为每个进程创建一个单独的记录器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62835466/

相关文章:

python - scipy.interpolate.lagrange 在某些数据上失败

python - 你能解释一下这个 python 对方括号的使用吗?

unit-testing - 如何使用最小起订量来验证企业库日志记录?

python - 将列表拆分为均匀大小的重叠 block n-max

c# - 您可以在代码中配置 log4net 而不是使用配置文件吗?

scala - 如何在 Play 2.4 中正确记录应用程序 DEBUG 和 INFO 消息?

python - 当 pip 中的链接断开时如何在 virtualenv 中安装库

python - multiprocess.apply_async 如何包装 *args 和 **kwargs?

python - 验证多个变量的值

python - 无法使用正则表达式获得自定义结果