如何在回调中重置python logger

ru9i0ody  于 2023-05-08  发布在  Python
关注(0)|答案(1)|浏览(142)

你好,这里是我的promblem:我使用一个代理和一个监听它的守护进程,每次一个消息(包含一个文件)进入一个回调函数,在我的代码中触发如下:

def callback(self, ch, method, properties, body,args):
    (conn, thrds) = args
    delivery_tag = method.delivery_tag
    t = threading.Thread(target=self.do_work, args=(conn, ch, delivery_tag, body))
    t.start()
    thrds.append(t)

#callback=staticmethod(callback)
def do_work(self, conn, ch, delivery_tag, body):
    thread_id = threading.get_ident()
    logging.basicConfig(filename=self.dict_config["filelog"]+"exchange_hashed" +'_'+str(thread_id)+'_' + str(datetime.now().strftime('%Y%m%d%H%M%S%f')) + '.log',level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    logger = logging.getLogger('exchange_hashed'+str(thread_id))

    logger.info('Thread id: %s Delivery tag: %s', thread_id,delivery_tag)
    payload = body.decode("utf-8")
    payload = json.loads(payload)
    file_content = payload["values"]
    file_path = file_content["header"]["meta_data"]["file_name"]
    filename=file_path.split("/")[-1]
    logger.info(f"Data received for {filename}")

在函数do_work()中,我初始化了我的日志记录器,并用它的线程id命名它,但它并没有为每个线程创建一个新的日志文件,而是继续写入第一个线程。
我查了日志文件,他们说:多次调用同名的getLogger()将始终返回对同一Logger对象的引用。
所以这正是我不做的
我不明白我错过了什么。

lnlaulya

lnlaulya1#

为了为每个线程实现单独的日志文件,我在do_work方法中为每个线程手动创建和配置了一个新的日志记录器。下面是我的代码的更新版本,它应该为每个线程创建单独的日志文件:

import logging
import threading
from datetime import datetime

def callback(self, ch, method, properties, body, args):
    (conn, thrds) = args
    delivery_tag = method.delivery_tag
    t = threading.Thread(target=self.do_work, args=(conn, ch, delivery_tag, body))
    t.start()
    thrds.append(t)

def do_work(self, conn, ch, delivery_tag, body):
    thread_id = threading.get_ident()

    # Create a new logger for each thread
    logger = logging.getLogger('exchange_hashed.' + str(thread_id))
    logger.setLevel(logging.INFO)

    # Create a new file handler for each thread
    filename = self.dict_config["filelog"] + "exchange_hashed_" + str(thread_id) + '_' + str(datetime.now().strftime('%Y%m%d%H%M%S%f')) + '.log'
    file_handler = logging.FileHandler(filename)
    file_handler.setLevel(logging.INFO)

    # Configure the log format
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file_handler.setFormatter(formatter)

    # Add the file handler to the logger
    logger.addHandler(file_handler)

    logger.info('Thread id: %s Delivery tag: %s', thread_id, delivery_tag)
    payload = body.decode("utf-8")
    payload = json.loads(payload)
    file_content = payload["values"]
    file_path = file_content["header"]["meta_data"]["file_name"]
    filename = file_path.split("/")[-1]
    logger.info(f"Data received for {filename}")

相关问题