My custom Logger
class works just fine. However, the class is not intended for making instances of. Because there is really no reason to make instances of my class, or so I think.
Any constructive criticism? Is this considered good "design"?
I have a feeling that I shouldn't open and close my file for each method call, is that bad? Is the way I open/write/close files in my Logger
class bad?
from Time import Time
from datetime import datetime
temp = datetime.now().today()
YEAR, MONTH, DAY = temp.year, temp.month, temp.day
class Logger:
"""If a log file for today already exist, open it in append mode.
Else, create a new log file for today, and open it in append mode.
"""
DEBUG = False
PADDING = 9 # right-padding for type names in the log
filename = f"logs/log{DAY}-{MONTH}-{YEAR}.txt"
file = open(filename, "a").close()
"""Clears the log file"""
@staticmethod
def clear():
with open(Logger.filename, "r+") as file:
file.truncate(0)
"""Log info"""
@staticmethod
def log(msg):
with open(Logger.filename, "a") as file:
type = "INFO".ljust(Logger.PADDING)
file.write(f"|{type}|{Time.getHour()}:{Time.getMinute()}| {msg}\n")
"Used to log whenever a state is updated"
@staticmethod
def update(msg):
with open(Logger.filename, "a") as file:
type = "UPDATE".ljust(Logger.PADDING)
file.write(f"|{type}|{Time.getHour()}:{Time.getMinute()}| {msg}\n")
"Only logs if the static variable {DEBUG} is set to True."
@staticmethod
def debug(msg):
if not Logger.DEBUG: return # Only log if DEBUG is set to True
with open(Logger.filename, "a") as file:
type = "DEBUG".ljust(Logger.PADDING)
file.write(f"|{type}|{Time.getHour()}:{Time.getMinute()}| {msg}\n")
"""Intended for use on objects. They usually have a lot of information;
therefor, we enclose the information with lines to make the log more readable."""
@staticmethod
def object(object):
with open(Logger.filename, "a") as file:
file.write(f"----------------------- object log\n")
file.write(object)
file.write(f"\n-----------------------\n")
@staticmethod
def exception(msg):
with open(Logger.filename, "a") as file:
type = "EXCEPTION".ljust(Logger.PADDING)
file.write(f"|{type}|{Time.getHour()}:{Time.getMinute()}| {msg}\n")
if __name__ == "__main__":
Logger.log("This is a test")
Logger.log("running something")
Logger.debug("Some debugging details")
Logger.exception("Critical error!")
Logger.debug("Some more debugging details")
Output example:
|INFO |10:35| This is a test
|INFO |10:35| running something
|DEBUG |10:35| Some debugging details
|EXCEPTION|10:35| Critical error!
|DEBUG |10:35| Some more debugging details