在Python中,将单独的日志记录器分配给每个类实例,作为该实例的属性。

huangapple go评论55阅读模式
英文:

Assigning separate logger to each class instance in Python as the instance's attribute

问题

我正在编写一个用于模拟特定分布式进程的库,在这个进程中,我们区分一个中央实体和相应的分散客户端。每个客户端都表示为一个名为 client 的通用类的实例,该类用作其模板。在模拟过程中,每个实例都独立保存在内存中,并具有存储其模拟数据的相关属性。我试图实现如何区分中央实体和客户端类的每个相应实例的不同记录器。

目前,我的解决方法如下:中央实体客户端类保存在不同的模块中。在每个模块的顶部,我从我的自定义工厂类中导入不同的记录器以在每个模块的开头进行初始化。

class Loggers:
    @staticmethod
    def central_logger():
        central_logger = logging.getLogger("central_logger")
        central_logger.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        ch.setFormatter(formatter)
        central_logger.addHandler(ch)
        central_logger.propagate = False
        return central_logger
    
    @staticmethod
    def client_logger():
        # 创建节点的头记录器
        client_logger = logging.getLogger("node_logger")
        client_logger.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        zh = logging.StreamHandler()
        zh.setLevel(logging.DEBUG)
        zh.setFormatter(formatter)
        client_logger.addHandler(zh)
        client_logger.propagate = False
        return client_logger

这样,我能够区分中央记录器客户端记录器。然而,我尝试将记录器的实例初始化为类的属性。例如:

class Client:
    def __init__(self) -> None:
        self.logger = Loggers.client_logger(*在这里我们可以传递参数以个性化特定客户端的记录器*)

然而,这并没有返回令人满意的结果,因为每个客户端在最后都会重置为默认的通用记录器。

在上述描述的情况下,有没有一种巧妙的方法可以将记录器初始化为类的属性?

英文:

I am writing a library for simulating a certain distributed process, where we distinguish between one central entity and corresponding decentralised clients. Each client is represented as an instance of a general class client that serves as a boilerplate for it. During the simulation, each instance is independently kept in memory and has associated attributes that store its simulation data. I am trying to implement how to differentiate between different loggers for the central entity and each corresponding instance of a client class.

For now, my workaround is as follows: the Central Entity and Client Class are kept in different modules. On the top of each module, I import different loggers from my custom factory class to initialize at the beginning of each module.

class Loggers:
    @staticmethod
    def central_logger():
        central_logger = logging.getLogger("central_logger")
        central_logger.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        ch.setFormatter(formatter)
        central_logger.addHandler(ch)
        central_logger.propagate = False
        return central_logger
    @staticmethod
    def client_logger():
        # Creating a head logger for the nodes
        client_logger = logging.getLogger("node_logger")
        client_logger.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        zh = logging.StreamHandler()
        zh.setLevel(logging.DEBUG)
        zh.setFormatter(formatter)
        client_logger.addHandler(zh)
        client_logger.propagate = False
        return client_logger

This way, I am able to differentiate between central logger and client_logger. However, I tried to initialize an instance of the logger as an attribute of a class. For example:

class Client:
    def __init__(self) -> None:
        self.logger = Loggers.client_logger(*here we could pass arguments to individualise the logger for a particular client*)

This, however - does not return a satisfactory result, as each client is resetting to a default general logger by the end.

Is there a smart way to initialize a logger as an attribute of a class in the scenario described above?

答案1

得分: 1

以下是翻译好的部分:

# 初始化日志记录器
Loggers.client_logger()

class Client:
    def __init__(self):
        self.logger = logging.getLogger("node_logger").getChild(str(id(self)))
英文:

Keeping your logger class as is here's how you could only initialise the logger once and have a child logger for each Client instance.

# Initialise logger
Loggers.client_logger()

class Client:
    def __init__():
        self.logger = logging.getLogger("node_logger").get_child(str(id(self)))

huangapple
  • 本文由 发表于 2023年7月13日 19:43:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76679007.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定