Last active
October 16, 2022 10:03
-
-
Save PFython/ccd8721cc47c0330da508058ecd74064 to your computer and use it in GitHub Desktop.
Create a logger for every Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Create ONE log, shared by all instances of a CLASS | |
""" | |
from log2d import Log | |
class MyAbstractClass: | |
def __init__(self, name, *args, **kwargs): | |
params = {"fmt": Log.presets["name_and_time"]} | |
self.log = Log.index.get(name) or Log(name, **params) | |
class MyClass(MyAbstractClass): | |
def __init__(self, name, *args, **kwargs): | |
super().__init__(self.__class__.__name__, *args, **kwargs) | |
self.name = name | |
def method_1(self): | |
# Do something | |
self.log(f"method_1 of {self.name} did something!") | |
x = MyClass("Instance X") | |
x.method_1() | |
y = MyClass("Instance Y") | |
y.method_1() | |
x.log(f"This message was logged by {x.name}") | |
y.log(f"And this one by {y.name}") | |
""" | |
OUTPUT: | |
MyClass|2022-10-16T08:43:31+0100|method_1 of Instance X did something! | |
MyClass|2022-10-16T08:43:45+0100|method_1 of Instance Y did something! | |
MyClass|2022-10-16T08:57:52+0100|This message was logged by Instance X | |
MyClass|2022-10-16T08:58:18+0100|And this one by Instance Y | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment