Skip to content

Instantly share code, notes, and snippets.

@PFython
Last active October 16, 2022 10:03
Show Gist options
  • Save PFython/ccd8721cc47c0330da508058ecd74064 to your computer and use it in GitHub Desktop.
Save PFython/ccd8721cc47c0330da508058ecd74064 to your computer and use it in GitHub Desktop.
Create a logger for every Class
"""
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