日志或文本文件读写开发
创建全局变量配置代码com.zxy.common.Com_Para.py全局变量根据需要后续补充。
#! python3
# -*- coding: utf-8 -
'''
Created on 2023年08月28日
@author: zxyong 13738196011
'''
#监测数据采集物联网应用--全局变量
import threading
#程序运行路径
ApplicationPath = ""
#操作系统识别 windows linux
devsys = "linux"
#编码格式
U_CODE = "UTF-8"
#文件夹路径根据windows操作系统或linux操作系统自动区分
zxyPath = "/"
新建日志或文本读写代码com.zxy.adminlog.UsAdmin_Log.py,日志文件命名格式参考“zxyong_20230824_1.log”其中日志文件大小超过1M自动新建日志文件。
#! python3
# -*- coding: utf-8 -
'''
Created on 2023年08月28日
@author: zxyong 13738196011
'''
import os
from com.zxy.common import Com_Para
from com.zxy.common.Com_Fun import Com_Fun
class UsAdmin_Log():
attContent = ''
attFolder = ''
attTFileName = ''
attENCODE = ''
def __init__(self,*args):
self.attENCODE = Com_Para.U_CODE
if len(args) == 2:
self.attFolder = args[0] + Com_Para.zxyPath + "log"
self.attContent = args[1]
elif len(args) == 3:
self.attFolder = args[0] + '/log'
self.attContent = args[1]
self.attTFileName = args[2]
elif len(args) == 4:
self.attFolder = args[0] + Com_Para.zxyPath + "data"
self.attContent = args[1]
def WriteData(self,inputDelay_code):
self.HadForder()
self.SaveFileData(inputDelay_code)
# 编写默认log信息
def WriteLog(self):
self.HadForder()
self.SaveFileDay()
# 编写默认log信息
def WriteExceptionLog(self,temClassName,temFunName):
temIndexS = temClassName.rindex("\\")
temIndexE = temClassName.rindex(".")
temClass = temClassName[temIndexS+1:temIndexE]
self.attContent = "==>"+temClass+"."+temFunName+"|\r"+self.attContent
self.HadForder()
self.SaveFileDay()
# 编写日志,含内容
def WriteLogAll(self, inputTContent):
self.HadForder()
self.SaveFileDayAll(inputTContent)
# 编写带sub日志,含子文件夹
def WriteLogSub(self, inputSubFile):
self.HadForder()
self.SaveFileDay(inputSubFile)
# 编写DEC日志
def WriteLogSubDEC(self):
self.WriteLogSub()
self.WriteLogAll('DEC_SEC_')
def InitWriteData(self,inputDelay_code):
self.HadForder()
self.InitSaveFileData(inputDelay_code)
def InitSaveFileData(self,inputDelay_code):
temStrTFileName = self.attFolder + Com_Para.zxyPath + inputDelay_code + ".dat"
temFile = None
try:
if os.path.exists(temStrTFileName) == False :
temFile = open(temStrTFileName, 'w',encoding=self.attENCODE)
temFile.write(self.attContent + "\r\n")
temFile.close()
else:
pass
except Exception as e:
print(repr(e)+"=>"+str(e.__traceback__.tb_lineno))
finally:
if temFile != None:
temFile.close()
def InitAppendFileData(self,inputDelay_code):
temStrTFileName = self.attFolder + Com_Para.zxyPath + inputDelay_code + ".dat"
temFile = None
try:
if os.path.exists(temStrTFileName) == False :
temFile = open(temStrTFileName, 'w',encoding=self.attENCODE)
temFile.write(self.attContent + "\r\n")
temFile.close()
else:
temFile = open(temStrTFileName, 'a',encoding=self.attENCODE)
temFile.write(self.attContent + "\r\n")
temFile.close()
except Exception as e:
print(repr(e)+"=>"+str(e.__traceback__.tb_lineno))
finally:
if temFile != None:
temFile.close()
# 判断文件夹是否存在,
def HadForder(self):
if os.path.exists(self.attFolder) == False:
os.mkdir(self.attFolder)
#读取文件内容
def ReadFileToJson(self,inputFileName):
temResult = []
temFile = None
try:
if os.path.exists(inputFileName) == False :
temResult = []
else:
temFile = open(inputFileName, 'r',encoding=self.attENCODE)
while True:
temLines = temFile.readline()
if len(temLines) > 0:
if temLines[0:1] != ",":
temResult.append(temLines)
else:
temResult.append(temLines[1:len(temLines)])
if not temLines:
break
pass
except Exception as e:
temResult = []
print(repr(e)+"=>"+str(e.__traceback__.tb_lineno))
finally:
if temFile != None:
temFile.close()
return temResult
#读取文件内容
def ReadFile(self,inputFileName):
temStrResult = ''
temFile = None
try:
if os.path.exists(inputFileName) == False :
temStrResult = ""
else:
temFile = open(inputFileName, 'r',encoding=self.attENCODE)
while True:
temLines = temFile.readline()
#整行读取数据
temStrResult += temLines
if not temLines:
break
pass
except Exception as e:
temStrResult = ""
print(repr(e)+"=>"+str(e.__traceback__.tb_lineno))
finally:
if temFile != None:
temFile.close()
return temStrResult
# 按日保存带内容日志文件
def SaveFileDayAll(self, inputTContent):
temStrLogName = ""
if self.attTFileName == "":
temStrLogName = self.attFolder + '/zxyong_' + Com_Fun.GetTime('%Y%m%d') + '_1.log'
else:
temStrLogName = self.attFolder + '/' + self.attTFileName + '.log'
temFile = None
try:
if os.path.exists(temStrLogName) == False :
temFile = open(temStrLogName, 'a',encoding=self.attENCODE)
temFile.write("*********" + Com_Fun.GetTime('%Y-%m-%d %H:%M:%S') + "*********" + "\r\n")
temFile.write(inputTContent + "\r\n")
temFile.close()
else:
temLgSize = os.path.getsize(temStrLogName)
i = 2
while 1 == 1:
if temLgSize > 1024 * 1024 :
if self.attTFileName == "":
temStrLogName = self.attFolder + "/zxyong_" + Com_Fun.GetTime('%Y%m%d') + "_" + str(i) + ".log"
else:
temStrLogName = self.attFolder + "/" + self.attTFileName + Com_Fun.GetTime('%Y%m%d') + "_" + str(i) + ".log"
if os.path.exists(temStrLogName) == False :
temFile = open(temStrLogName, 'a',encoding=self.attENCODE)
temFile.write("*********" + Com_Fun.GetTime('%Y-%m-%d %H:%M:%S') + "*********" + "\r\n")
temFile.write(inputTContent + "\r\n")
temFile.close()
break
else:
temLgSize = os.path.getsize(temStrLogName)
else:
temFile = open(temStrLogName, 'a',encoding=self.attENCODE)
temFile.write("*********" + Com_Fun.GetTime('%Y-%m-%d %H:%M:%S') + "*********" + "\r\n")
temFile.write(inputTContent + "\r\n")
temFile.close()
break
i = i + 1
except Exception as e:
print(repr(e)+"=>"+str(e.__traceback__.tb_lineno))
finally:
if temFile != None:
temFile.close()
# 按日保存带文件名日志文件,按日文件夹存储
def SaveFileDaySub2(self, inputSub):
temPath = self.attFolder +"/"+Com_Fun.GetTime("%Y-%m-%d")
if os.path.exists(temPath) == False:
os.mkdir(temPath)
temStrLogName = temPath + '/zxyong_' + inputSub+"_" + Com_Fun.GetTime('%Y%m%d') + '_1.log'
temFile = None
try:
if os.path.exists(temStrLogName) == False :
temFile = open(temStrLogName, 'a',encoding=self.attENCODE)
temFile.write("*********" + Com_Fun.GetTime('%Y-%m-%d %H:%M:%S') + "*********" + "\r\n")
temFile.write(self.attContent + "\r\n")
temFile.close()
else:
temLgSize = os.path.getsize(temStrLogName)
i = 2
while 1 == 1:
if temLgSize > 1024 * 1024 :
temStrLogName = self.attFolder + '/zxyong_' + inputSub+"_" + Com_Fun.GetTime('%Y%m%d') + "_" + str(i) + ".log"
if os.path.exists(temStrLogName) == False :
temFile = open(temStrLogName, 'a',encoding=self.attENCODE)
temFile.write("*********" + Com_Fun.GetTime('%Y-%m-%d %H:%M:%S') + "*********" + "\r\n")
temFile.write(self.attContent + "\r\n")
temFile.close()
break
else:
temLgSize = os.path.getsize(temStrLogName)
else:
temFile = open(temStrLogName, 'a',encoding=self.attENCODE)
temFile.write("*********" + Com_Fun.GetTime('%Y-%m-%d %H:%M:%S') + "*********" + "\r\n")
temFile.write(self.attContent + "\r\n")
temFile.close()
break
i = i + 1
except Exception as e:
print(repr(e)+"=>"+str(e.__traceback__.tb_lineno))
finally:
if temFile != None:
temFile.close()
# 按日保存带文件名日志文件
def SaveFileDaySub(self, inputSub):
temStrLogName = self.attFolder + '/zxyong_' + inputSub+"_" + Com_Fun.GetTime('%Y%m%d') + '_1.log'
temFile = None
try:
if os.path.exists(temStrLogName) == False :
temFile = open(temStrLogName, 'a',encoding=self.attENCODE)
temFile.write("*********" + Com_Fun.GetTime('%Y-%m-%d %H:%M:%S') + "*********" + "\r\n")
temFile.write(self.attContent + "\r\n")
temFile.close()
else:
temLgSize = os.path.getsize(temStrLogName)
i = 2
while 1 == 1:
if temLgSize > 1024 * 1024 :
temStrLogName = self.attFolder + '/zxyong_' + inputSub+"_" + Com_Fun.GetTime('%Y%m%d') + "_" + str(i) + ".log"
if os.path.exists(temStrLogName) == False :
temFile = open(temStrLogName, 'a',encoding=self.attENCODE)
temFile.write("*********" + Com_Fun.GetTime('%Y-%m-%d %H:%M:%S') + "*********" + "\r\n")
temFile.write(self.attContent + "\r\n")
temFile.close()
break
else:
temLgSize = os.path.getsize(temStrLogName)
else:
temFile = open(temStrLogName, 'a',encoding=self.attENCODE)
temFile.write("*********" + Com_Fun.GetTime('%Y-%m-%d %H:%M:%S') + "*********" + "\r\n")
temFile.write(self.attContent + "\r\n")
temFile.close()
break
i = i + 1
except Exception as e:
print(repr(e)+"=>"+str(e.__traceback__.tb_lineno))
finally:
if temFile != None:
temFile.close()
# 按日保存日志文件
def SaveFileDay(self):
temStrLogName = ""
if self.attTFileName == "":
temStrLogName = self.attFolder + '/zxyong_' + Com_Fun.GetTime('%Y%m%d') + '_1.log'
else:
temStrLogName = self.attFolder + '/' + self.attTFileName+Com_Fun.GetTime('%Y%m%d') + '_1.log'
temFile = None
try:
if os.path.exists(temStrLogName) == False :
temFile = open(temStrLogName, 'a',encoding=self.attENCODE)
temFile.write("*********" + Com_Fun.GetTime('%Y-%m-%d %H:%M:%S') + "*********" + "\r")
temFile.write(self.attContent + "\r")
temFile.close()
else:
temLgSize = os.path.getsize(temStrLogName)
i = 2
while 1 == 1:
if temLgSize > 1024 * 1024 :
if self.attTFileName == "":
temStrLogName = self.attFolder + "/zxyong_" + Com_Fun.GetTime('%Y%m%d') + "_" + str(i) + ".log"
else:
temStrLogName = self.attFolder + "/" + self.attTFileName + Com_Fun.GetTime('%Y%m%d') + "_" + str(i) + ".log"
if os.path.exists(temStrLogName) == False :
temFile = open(temStrLogName, 'a',encoding=self.attENCODE)
temFile.write("*********" + Com_Fun.GetTime('%Y-%m-%d %H:%M:%S') + "*********" + "\r")
temFile.write(self.attContent + "\r")
temFile.close()
break
else:
temLgSize = os.path.getsize(temStrLogName)
else:
temFile = open(temStrLogName, 'a',encoding=self.attENCODE)
temFile.write("*********" + Com_Fun.GetTime('%Y-%m-%d %H:%M:%S') + "*********" + "\r")
temFile.write(self.attContent + "\r")
temFile.close()
break
i = i + 1
except Exception as e:
print(repr(e)+"=>"+str(e.__traceback__.tb_lineno))
finally:
if temFile != None:
temFile.close()
日志调用代码MonitorDataCmd.py主文件中编写:
from com.zxy.adminlog.UsAdmin_Log import UsAdmin_Log
if __name__ == '__main__':下编写
#全局变量参数设置
Com_Para.ApplicationPath = os.path.abspath(os.path.dirname(__file__))
if Com_Para.ApplicationPath[len(Com_Para.ApplicationPath) - 1 :len(Com_Para.ApplicationPath)] == "\\" or Com_Para.ApplicationPath[len(Com_Para.ApplicationPath) - 1 :len(Com_Para.ApplicationPath)] == "/":
Com_Para.ApplicationPath = Com_Para.ApplicationPath[0 :len(Com_Para.ApplicationPath) - 1]
sysstr = platform.system()
if sysstr.lower() == "windows":
Com_Para.devsys = "windows"
Com_Para.zxyPath = "\\"
elif sysstr.lower() == "linux":
Com_Para.devsys = "linux"
Com_Para.zxyPath = "/"
temLog = "测试日志,默认日志"+Com_Fun.GetTimeDef()
temInitLog = ""
for i in range(1,20):
temInitLog = temLog
temLog = temLog +" " +Com_Fun.GetTimeDef()+";\r" + temInitLog
uL = UsAdmin_Log(Com_Para.ApplicationPath, temLog)
uL.WriteLog()
print("默认日志文件成功,多次执行看看")
temLog = "测试日志,含文件名日志"+Com_Fun.GetTimeDef()
temInitLog = ""
for i in range(1,20):
temInitLog = temLog
temLog = temLog +" " +Com_Fun.GetTimeDef()+";\r" + temInitLog
uL = UsAdmin_Log(Com_Para.ApplicationPath, temLog)
uL.SaveFileDaySub("exception")
print("含文件名日志文件成功,多次执行看看")
日志文件效果如图: