https://apppukyptrl1086.h5.xiaoeknow.com/ import logging import os import sys # 2023-03-22 10:03:18,402 demo-app[Info][demo.py-34]: python log demo test def log_config(name): # log 打印级别 logging.addLevelName(logging.DEBUG, 'DEBUG') logging.addLevelName(logging.ERROR, 'ERROR') logging.addLevelName(logging.INFO, 'INFO') logging.addLevelName(logging.WARNING, 'WARN') logging.addLevelName(logging.WARN, 'WARN') logger = logging.getLogger(name) # 管理日志级别 logger.setLevel(logging.DEBUG) # 日志格式打印 formatter = logging.Formatter("%(asctime)s %(name)s[%(levelname)s]: %(message)s") file_formatter = logging.Formatter("%(asctime)s %(name)s[%(levelname)s][%(filename)s-%(lineno)d]: %(message)s") # 控制台只打印 INFO 级别日志 handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) handler.setLevel(logging.INFO) logger.addHandler(handler) # 记录到 log 日志文件里面的日志级别 dir_path = os.sep.join(os.path.realpath(__file__).split(os.sep)[:-2]) log_file = os.path.join(dir_path, "demo.log") log_path_handler = logging.FileHandler(log_file) log_path_handler.setFormatter(file_formatter) log_path_handler.setLevel(logging.DEBUG) logger.addHandler(log_path_handler) return logger # 获取一个日志打印对象 customlogger = log_config("demo-app") customlogger.info("python log demo test") customlogger.debug("python log demo test") customlogger.warning("python log demo test")
执行测试
控制台:
2023-03-22 10:16:08,136 demo-app[INFO]: python log demo test
2023-03-22 10:16:08,137 demo-app[WARN]: python log demo test
日志文件 demo.log:
2023-03-22 10:16:08,136 demo-app[INFO][log_config.py-33]: python log demo test 2023-03-22 10:16:08,137 demo-app[DEBUG][log_config.py-34]: python log demo test 2023-03-22 10:16:08,137 demo-app[WARN][log_config.py-35]: python log demo test