Answer the question
In order to leave comments, you need to log in
How to shorten the spelling for calling a class method in Python?
I may have a noob and incorrect question, but I want to make a beautiful method call.
there is a Logger class, logging happens like this: log_error.log("blah blah blah")
and I would like it like this: log_error("blah blah blah")
and also so that you can make settings log_error.to_file = False
and fasten the logger like this:
from logger import log_error
the logger itself:
import datetime, os
class Logger(object):
def __init__(self):
self.to_screen = False
self.sql_log = ""
self.format_str = "{0}: {1}" # формат строки 0-дата, 1-сообщение
self.format_date_time = '%d %B %Y %H:%M:%S' # формат даты и времени для сообщений
self.format_date = '%d %B %Y' # формат имени файла, по дате для имени файла
self.not_print_datetime = False
self.file_name_log = ""
self.to_file = False
self.folder_log = ""
def _write_to_file(self, file):
try:
f = open(file, "a")
f.write(self.message + "\n")
f.close()
except:
# создаем папку лог
os.mkdir(self.folder_log)
f = open(file, "a")
f.write(self.message + "\n")
f.close()
def log(self, message):
time_now = datetime.datetime.now().strftime(self.format_date_time)
date_now = datetime.datetime.now().strftime(self.format_date)
self.message = self.format_str.format(time_now, message)
if self.not_print_datetime: self.message = message
if self.to_screen:
print(self.message)
if self.to_file:
self._write_to_file(self.folder_log + date_now + ".txt")
log_error = Logger()
log_error.to_screen = True
log_info.to_file = True
log_info.folder_log = "logs_error/"
Answer the question
In order to leave comments, you need to log in
but I would like this: log_error("blah blah blah")
class Logger(object):
__call__ = log
and attach the logger like this:
from logger import log_error
log_error = Logger()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question