1.效果如下:
2.代码如下:
import logging
import threading
import os
import sys
sys.path.append(os.getcwd())
class Mylog(object):
_instance_lock = threading.Lock()
def __init__(self):#,path = "log.txt"):
# 配置日志输出格式
path = os.path.join(os.getcwd(),'applog.log')
# formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(pathname)s - %(message)s')
formatter = logging.Formatter("%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s")
self.logger = logging.getLogger()
self.logger.setLevel(logging.DEBUG)
# 创建文件处理器并设置日志级别为DEBUG
file_handler = logging.FileHandler(path,mode='a',encoding='utf-8')# 输出到log文件的handler 'w'覆盖 'a'添加
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
# 输出到控制台
# file_handler = logging.StreamHandler()
# file_handler.setLevel(logging.INFO)
# 将文件处理器添加到日志记录器中
self.logger.addHandler(file_handler)
@classmethod
def instance(cls, *args, **kwargs):
if not hasattr(Mylog, "_instance"):
with Mylog._instance_lock:
if not hasattr(Mylog, "_instance"):
Mylog._instance = Mylog(*args, **kwargs)
return Mylog._instance
def testlog():
mylog = Mylog.instance()
mylog.logger.debug("This is a debug message")
mylog.logger.info("This is a info message")
Mylog.instance().logger.debug("This is another debug message")
Mylog.instance().logger.error("This is an 错误信息")
if __name__ == '__main__':
testlog()