简单的日志记录对象

发布于 2024-12-15 14:42:11 字数 2126 浏览 2 评论 0原文

我有一些 python 模块,它有一个 ModuleClass 类,我无法修改该类。

现在,我希望能够代理方法调用并添加某些日志记录功能。我认为这应该通过转发对象和相应的代理(遵循Effective Java,第16项)来完成。

我想出的 python 伪代码如下。

(抱歉,我真的不太擅长 python,如果您能的话,我将不胜感激在这里指出错误)。

# This is what I've got in my module and this code cannot be changed.
class ModuleClass(object):
    def method1(self):
        # Some implementation
        pass()
    def method2(self):
        # Some implementation
        pass()

# Simple forwarding proxy to avoid the situation described in Effective Java, I16

# However, in Java this class would usually be extending the interface, not
# inheriting 'ModuleClass' (I'm confused and don't know how to do the same
# in python).

class ForwardingModuleClass(ModuleClass):
    # 'proxifiedObject' is 
    def __init__(self, proxifiedObject):
        self.proxifiedObject = proxifiedObject

    # Overriding the first method
    def method1(self):
        return self.proxifiedObject.method1()

    # Same for method2...

class LoggingModuleClass(ForwardingModuleClass):
    # 'classThatActuallyDoesStuff' should be an instance of 'ModuleClass'.
    def __init__(self, classThatActuallyDoesStuff):
        # Sorry for my bad knowledge of python syntax, but
        # I assume I can initialize the superclass here using
        # the supplied 'ModuleClass' instance.
        super(classThatActuallyDoesStuff)

    # Overriding the first method.
    def method1(self):
        print("Yay! This 'method1' really logs something!")
        return super.method1()

    # Overriding the second method.
    def method2(self):
        print("Yay!!!! This 'method2' also does something cool!")
        return super.method2()

现在,我想,如果编写得当,这会起作用,并且我将为我的初始 ModuleClass 提供日志记录代理。

如果有错误或者这不是Python风格,请指出。

另外,我怀疑这可以使用装饰器轻松完成,但是,不幸的是,我无法找到适当的方法,并且我不知道如果 ModuleClass 已经有一些方法装饰器会发生什么。

你也能帮我一下吗?

I have some python module, which has a class ModuleClass and I can't modify that class.

Now, I want to be able to proxify the method calls and add certain logging features. I assume this should be done via forwarding object and the corresponding proxy (following Effective Java, Item 16).

The python pseudocode I came up with follows.

(Sorry, I'm really bad at python and I would appreciate if you could point out errors here).

# This is what I've got in my module and this code cannot be changed.
class ModuleClass(object):
    def method1(self):
        # Some implementation
        pass()
    def method2(self):
        # Some implementation
        pass()

# Simple forwarding proxy to avoid the situation described in Effective Java, I16

# However, in Java this class would usually be extending the interface, not
# inheriting 'ModuleClass' (I'm confused and don't know how to do the same
# in python).

class ForwardingModuleClass(ModuleClass):
    # 'proxifiedObject' is 
    def __init__(self, proxifiedObject):
        self.proxifiedObject = proxifiedObject

    # Overriding the first method
    def method1(self):
        return self.proxifiedObject.method1()

    # Same for method2...

class LoggingModuleClass(ForwardingModuleClass):
    # 'classThatActuallyDoesStuff' should be an instance of 'ModuleClass'.
    def __init__(self, classThatActuallyDoesStuff):
        # Sorry for my bad knowledge of python syntax, but
        # I assume I can initialize the superclass here using
        # the supplied 'ModuleClass' instance.
        super(classThatActuallyDoesStuff)

    # Overriding the first method.
    def method1(self):
        print("Yay! This 'method1' really logs something!")
        return super.method1()

    # Overriding the second method.
    def method2(self):
        print("Yay!!!! This 'method2' also does something cool!")
        return super.method2()

Now, I guess, properly written, this would work and I would have the logging proxy for my initial ModuleClass.

If there are errors or if this is not pythonish, please point it out.

Also, I suspect this can easily be done using decorators, but, unfortunately, I can't figure the appropriate way and I have no idea what might happen if ModuleClass already has some method decorators.

Could you help me here too?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

心如荒岛 2024-12-22 14:42:11

如果您确实想要一个包装器,那么只需编写它即可,无需子类化和中间类。

class LoggingFoo(object):
    def __init__(self, *args, **kwargs):
        self.obj = Foo(*args, **kwargs)

    def method1(self):
        # ...
        return self.obj.method1()

    def method2(self):
        # ...
        return self.obj.method2()

If you really want a wrapper, then just write it, with no subclassing and intermediate classes.

class LoggingFoo(object):
    def __init__(self, *args, **kwargs):
        self.obj = Foo(*args, **kwargs)

    def method1(self):
        # ...
        return self.obj.method1()

    def method2(self):
        # ...
        return self.obj.method2()
不回头走下去 2024-12-22 14:42:11

直接子类化 ModuleClass 怎么样:(

import logging

logger=logging.getLogger(__name__)

class LoggingModuleClass(ModuleClass):
    def method1(self):
        logger.info("Yay! This 'method1' really logs something!")
        return super(LoggingModuleClass,self).method1()
    def method2(self):
        logger.info("Yay! This 'method2' also does something cool!")
        return super(LoggingModuleClass,self).method2()

logging.basicConfig(level=logging.DEBUG)

我添加了代码来显示 logging< /a> Python 方式)。

How about just subclass ModuleClass directly:

import logging

logger=logging.getLogger(__name__)

class LoggingModuleClass(ModuleClass):
    def method1(self):
        logger.info("Yay! This 'method1' really logs something!")
        return super(LoggingModuleClass,self).method1()
    def method2(self):
        logger.info("Yay! This 'method2' also does something cool!")
        return super(LoggingModuleClass,self).method2()

logging.basicConfig(level=logging.DEBUG)

(I added code to show a basic setup for logging the Python way).

人生百味 2024-12-22 14:42:11

如果您正在寻找装饰器解决方案,那么您应该查看这篇文章的答案:Python 装饰器使函数忘记它属于一个类

您表示您希望避免“不需要的消息”(以防 method1 调用 method2),那么我建议你到选择了 Cat Plus Plus 提供的解决方案,否则我会选择运营商。

If you are looking for a decorator solution then you should have a look to the answer of this post: Python decorator makes function forget that it belongs to a class

You indicated that you want to avoid "unwanted messages" (in case method1 calls method2), then I'd suggest you to chose the solution provided by Cat Plus Plus, else I'd go for operators.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文