python log tool 封装
import logging
from io import StringIO
from datetime import datetime
import os
class Log:
stringIo = StringIO()
fileNameLogging = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) + "/c_log/testLogging.log"
fileNameIO = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) + "/c_log/testLogIO.log"
fileNameFile = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) + "/c_log/testLogFile.log"
@classmethod
def log(cls):
logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(filename)s [line: %(lineno)d] - %(levelname)s: %(message)s')
file_handler = logging.FileHandler(filename=cls.fileNameLogging, mode='a', encoding='utf-8')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
return logger
@classmethod
def logIO(cls, msg):
message = str(datetime.now()) + " msg: " + str(msg) + "\n"
cls.stringIo.write(message)
cls.stringIo.flush()
@classmethod
def logWrite(cls):
cls.stringIo.seek(0, 0)
for line in cls.stringIo.readlines():
with open(cls.fileNameIO, mode="a", encoding="utf-8") as f:
f.write(line)
f.flush()
@classmethod
def logfile(cls, msg):
message = str(datetime.now()) + " msg: " + str(msg) + "\n"
with open(cls.fileNameFile, mode="a", encoding="utf-8") as f:
f.write(message)
f.flush()
if __name__ == '__main__':
Log.log().info("aaa")
Log.logIO("write the string io============cccccc=============================")
Log.logIO("write the string io============aaaaaaaaaaa========================")
Log.logWrite()