python logger 日志记录
python logger 日志记录
import logging import os import logging.handlers import time from server_config import server_config log_level = {"info": logging.INFO, "debug": logging.DEBUG, "warning": logging.WARNING, "error": logging.ERROR} class Logger: _loggers = {} def __init__(self, filename="log"): self.filename = filename def set_logger(self, level=None): if self.filename in Logger._loggers: return Logger._loggers[self.filename] file_path = os.path.abspath(os.path.join(server_config.get('BASE_DIR'), '../logs', '%s.log' % self.filename)) file_dir_path = os.path.dirname(file_path) if not os.path.exists(file_dir_path): os.makedirs(file_dir_path) my_logger = logging.getLogger(self.filename) my_handler = logging.handlers.TimedRotatingFileHandler( file_path, when="midnight" ) log_format = logging.Formatter('%(asctime)s %(levelname)s %(filename)s[line:%(lineno)d] %(message)s') my_handler.setFormatter(log_format) my_logger.addHandler(my_handler) if level is None: my_logger.setLevel(logging.DEBUG) elif level not in log_level.keys(): my_logger.setLevel(logging.INFO) else: my_logger.setLevel(log_level[level]) Logger._loggers[self.filename] = my_logger return my_logger if __name__ == "__main__": logger = Logger("log").set_logger() logger.info("info{}".format(2121212)) logger.warning("warning fdsfsdf11") logger.error("error fdsfsdf11") logger.debug("debug fdsfsdf11")