老闆有一個要求,說要看到一個url每日的訪問量,然而系統在開發的時候並沒有做這樣的計數,於是我就想到,由於前段負載使用nginx做的,有access日誌,嘗試了一下從access日誌中將結果分析出來,最終的效果是實現了,也許效率不是那麼高,邏輯不是那麼合理,起碼效果達到了,本人菜鳥一個,如有不對,請不要噴,交流而已,對則對,不對交流。
腳本內容奉上:
#!/usr/bin/python # _*_coding:utf-8 _*_ import os import shutil import sys import re import random import time from xlrd.formula import nop #初始化系統 reload(sys) sys.setdefaultencoding('utf-8') #邏輯爲: #1、將目標文件拷貝到臨時目錄 #2、分析目標臨時文件,先找到裏面包含哪些日期 #3、根據日期創建每個日期的訪問日誌記錄文件 #4、用匹配出來的日期,拼接匹配訪問url的正則表達式 #5、逐行分析臨時文件,將對應日期,符合表達式的放到對應日期的日誌記錄裏 #6、分析完成之後對各文件數行,然後寫入總記錄文件 #7、可以實現:根據日期統計每日url訪問量,每條訪問的access日誌詳情 #################################### #搜索結果保存路徑 save_result="/Users/liuli/Desktop/access" log_file_source="/Users/liuli/Desktop/test.log" #################################### #拷貝文件 def copyFiles(sourceFile, targetFile): open(targetFile, "wb").write(open(sourceFile, "rb").read()) if os.path.exists(save_result): shutil.rmtree(save_result) os.makedirs(save_result) else: os.makedirs(save_result) #數文件行數 def count_lines(file): try: fp = open(file, "r") return str(len(fp.readlines())) except Exception,e: return print e sys.exit(0) finally: fp.close() #正則匹配 def iscontain(regrex, strings): try: pattern = re.compile(regrex, re.S) item = pattern.search(strings).group() return item except Exception, e: return print e sys.exit(0) #獲取今天對應的月份 def get_today_month3(): ISOTIMEFORMAT = '%B' return str(time.strftime(ISOTIMEFORMAT, time.localtime())[0:3]) #獲取今天對應的日期 def get_today_day(): ISOTIMEFORMAT = '%d' return str(time.strftime(ISOTIMEFORMAT, time.localtime())) #往文件中寫內容 def write_to_file(file,strings): if os.path.isfile(file): try: file_object = open(file, "a") file_object.write(strings) except Exception, e: print e finally: file_object.close() else: try: file_object = open(file, "w") file_object.write(strings) except Exception, e: print e finally: file_object.close() #將nginx的日誌格式寫入到日誌文件中! write_to_file(save_result + "/log_format.txt",'$remote_addr - $remote_user [$time_local] \"$request\" ' '$status $body_bytes_sent \"$http_referer\" ' '\"$http_user_agent\" $http_x_forwarded_for \"$upstream_addr\" \"$upstream_status\" \"$upstream_response_time\" \"$request_time\"') #初始化 num = random.randrange(10086, 1008611) log_file = "/tmp/nginx_counter_tmp_" + str(num) + ".log" #不在源文件上分析,將源文件拷貝到臨時目錄 copyFiles(log_file_source, log_file) days=[] all_regrex=[] forword_regrex="^[0-9].([0-9]{1,3}\.){3}[0-9]{1,3}\ -\ -\ " day_regrex="(\[)([0-3]{1})([0-9]{1})(\/)(\w{3})(\/)(\d{4})" conn_regrex="([\s\S]*)" count_regrex="((GET)|(POST))(\ )(\/)(tserv)(\ )(HTTP)([\s\S]*)" #獲取日期列表days f=open(log_file,"r") line = f.readline() i=0 while line: pattern = re.compile(day_regrex, re.S) if pattern.search(line) is None : day111 = '1' else: item=pattern.search(line).group() regrexs = forword_regrex+"\\" + item + conn_regrex + count_regrex pattern1 = re.compile(regrexs, re.S) if pattern1.search(line) is None : day111 = '1' else: item1 = pattern1.search(line).group() write_to_file(save_result+"/" + str(item).replace("[", "").replace("/", "_").replace("]", "").replace(":","_") + ".txt",str(item1)) line = f.readline() #記錄結果格式化日誌: f.close() os.remove(log_file) #匹配內容並寫入分體文件 #創建記錄文件並將每個文件對應的行數【訪問量】寫入文件 for file in os.listdir(save_result): write_to_file(save_result+"/count_save.txt",file+" lines "+count_lines(save_result+"/"+file)+"\n")