練習了一個小程式,
版本是 python 2.6.6
Log 刪除程式.
直接放著紀錄下.
Config
{
"ShowInfo": true,
"LogRemainDays": 60,
"LogPath": [
"E:\\Tool\\Tomcat6.0\\logs\\"
,"E:\\Tool\\Tomcat6.0\\logs1\\"
,"E:\\Tool\\Tomcat6.0\\logs2\\"
]
}
LogRemainDays : Log 保留天
LogPath 裡面是log存放的路徑.
Code
import os
import sys
import subprocess
import urllib2
import urllib
import json
import StringIO
import shutil
import time
from datetime import datetime, timedelta
INFO = True
ERROR = True
SAVEFILE_INFO = False
CONFIG_FILE = 'log_killer.conf'
Output_Path = 'output'
Log_Dir = os.path.join(Output_Path, 'log')
Log_Dir_Temp = os.path.join(Output_Path, 'log\\temp')
Report_Dir = os.path.join(Output_Path, 'report')
Err_Dir = os.path.join(Output_Path, 'err')
#RecordFMS_Dir = os.path.join(Output_Path, 'RecordFMS')
DATETIME_NOW = datetime.now()
ErrLogFile = '%s\\err_rec_remove_%s.log' % (Err_Dir, DATETIME_NOW.strftime('%Y%m%dT%H%M'))
#CheckUnfinishLogFile = '%s\\err_check_unfinish_%s.log' % (Err_Dir, DATETIME_NOW.strftime('%Y%m%dT%H%M'))
RecordFMSErrLogFile = '%s\\err_record_fms_%s.log' % (Err_Dir, DATETIME_NOW.strftime('%Y%m%dT%H%M'))
'''
print msg
'''
def printMsg(mode, msg):
if mode:
print msg
'''
read config file
'''
def readConfig(filename, argv=None):
printMsg(INFO, "[Read Config File]")
errLogFile = 'err_rec_remove_%s.log' % DATETIME_NOW.strftime('%Y%m%dT%H%M')
config = None
try:
#printMsg(INFO, "[filename]"+filename)
f = open(filename, 'r')
body = f.read()
f.close()
except Exception as e:
errMsg = '\n!!! ERROR: open config file: %s\n' % filename
errMsg += '\ne = %s\n' % e
printMsg(ERROR, errMsg)
#saveFile(ErrLogFile, errMsg, mode='a')
return None
try:
config = json.loads(body)
print "config=[",config,"]"
#print "config['UpdateSessionRecordAPI']=["+config['UpdateSessionRecordAPI']+"]"
except Exception as e:
errMsg = '\n!!! ERROR: json loads body: %s\n' % body
errMsg += '\ne = %s\n' % e
printMsg(ERROR, errMsg)
#saveFile(ErrLogFile, errMsg, mode='a')
return None
#
printMsg(INFO, " - read config file done.")
return config
def getFileStat(file_path):
statinfo = os.stat(file_path)
return {
'size' : statinfo.st_size,
'atime' : statinfo.st_atime,
'mtime' : statinfo.st_mtime,
'ctime' : statinfo.st_ctime
}
'''
return Days = (fstDate - secDate)
'''
def getDayDiff(fstDate,secDate):
delta = fstDate - secDate
return delta.days
def validateDate(date_text,dateFormat):
try:
datetime.strptime(date_text, dateFormat)
except ValueError:
#raise ValueError("Incorrect data format, should be YYYY-MM-DD")
return False
return True
def mainRemoveLogFile():
print "mainRemoveLogFile"
LOG_PATHS = _CONFIG['LogPath']
LOG_REMAIN_DAYS = _CONFIG['LogRemainDays']
print "LOG_PATH=",type(LOG_PATHS) ,"\nLOG_REMAIN_DAYS=",LOG_REMAIN_DAYS
for log_path in LOG_PATHS:
for dirname, dirnames, filenames in os.walk(log_path):
for filename in filenames:
filePath = os.path.join(dirname, filename)
fileStat = getFileStat(filePath)
mtime=datetime.fromtimestamp(fileStat['mtime'])
dayDiff = getDayDiff(DATETIME_NOW,mtime)
if dayDiff>LOG_REMAIN_DAYS:
os.remove(filePath)
_FUNC_MAP = {
'default' : mainRemoveLogFile
}
_FUNC_NAME_MAP = {
'default' : 'killLog'
}
_ERROR_LOG_MAP = {
'default' : ErrLogFile
}
def main(action, argv=None):
printMsg(INFO, '')
printMsg(INFO, '-*' * 50)
printMsg(INFO, ' Run Script Time: ' + str(DATETIME_NOW) + ', Version: 1.7.8')
printMsg(INFO, '-*' * 50)
printMsg(INFO, '')
printMsg(INFO, ' Action: %s' % _FUNC_NAME_MAP[action])
printMsg(INFO, '')
#createLogFolder(Output_Path)
_FUNC_MAP[action]()
printMsg(INFO, '')
printMsg(INFO, '-*' * 50)
printMsg(INFO, ' Run Script End Time: ' + str(DATETIME_NOW))
printMsg(INFO, '-*' * 50)
printMsg(INFO, '')
return 1
if __name__ == "__main__":
action = 'default'
if len(sys.argv) > 1:
action = sys.argv[1].lower()
if action not in _FUNC_MAP:
action = 'default'
ErrLogFile = _ERROR_LOG_MAP[action]
### init. - read config
_CONFIG = readConfig(CONFIG_FILE, sys.argv)
#print "_CONFIG=[",_CONFIG,"]"
if _CONFIG is not None:
INFO = _CONFIG['ShowInfo']
print "INFO=[",INFO,"]"
#main(action, sys.argv)
sys.exit(main(action, sys.argv))
errMsg = '\n!!! ERROR: read config failed! \n'
printMsg(ERROR, errMsg)
完成.
隨手寫的.
練習用. 做個紀錄.