python分析nginx日誌

來源:互聯網
上載者:User

標籤:python分析nginx日誌

利用python指令碼分析nginx日誌內容,預設統計ip、訪問url、狀態,可以通過修改指令碼統計分析其他欄位。

一、指令碼運行方式

python count_log.py -f med.ihbedu.com.access.log

二、指令碼內容

#!/usr/bin/python# -*- coding: utf-8 -*-"""1.分析日誌,每行日誌按空格切分,取出需要統計的相應欄位,作為字典的key,遍曆相加2.使用到字典的get方法,通過定義預設值,避免miss key的錯誤3.使用列表解析運算式4.使用sorted函數排序列表5.使用argparse傳入參數6.nginx日誌格式:log_format         access_log    ‘$remote_addr - $remote_user [$time_local] $request ‘    ‘"$status" $body_bytes_sent "$http_referer" ‘    ‘"$http_user_agent"  "$request_time"‘ ‘"$upstream_addr"‘ ‘"$upstream_response_time"‘;7.日誌內容:222.xx.xxx.15 - - [07/Dec/2016:00:03:27 +0800] GET /app/xxx/xxx.apk HTTP/1.0 "304" 0 "-" "Mozilla/5.0 Gecko/20100115 Firefox/3.6"  "0.055""-""-"8.指令碼運行結果:(‘106.xx.xx.46‘, ‘/gateway/xxx/user/mxxxxx/submitSelfTestOfSingleQuestion‘, ‘"200"‘, 299)(‘182.1xx.xx.83‘, ‘/‘, ‘"200"‘, 185)(‘222.xx.1xx.15‘, ‘/‘, ‘"200"‘, 152)(‘125.xx.2xx.58‘, ‘/‘, ‘"200"‘, 145)"""import argparsedef count_log(filename, num):    try:        with open(filename) as f:            dic = {}            for l in f:                if not l == ‘\n‘:  # 判斷空白行                    arr = l.split(‘ ‘)                    ip = arr[0]                    url = arr[6]                    status = arr[8]                    # 字典的key是有多個元素構成的元組                    # 字典的get方法,對取的key的值加1,第一次迴圈時由於字典為空白指定的key不存在返回預設值0,因此讀第一行日誌時,統計結果為1                    dic[(ip, url, status)] = dic.get((ip, url, status), 0) + 1        # 從字典中取出key和value,存在列表中,由於字典的key比較特殊是有多個元素構成的元組,通過索引k[#]的方式取出key的每個元素        dic_list = [(k[0], k[1], k[2], v) for k, v in dic.items()]        for k in sorted(dic_list, key=lambda x: x[3], reverse=True)[:num]:            print(k)    except Exception as e:        print("open file error:", e)if __name__ == ‘__main__‘:    parser = argparse.ArgumentParser(description="傳入記錄檔")    # 定義必須傳入記錄檔,使用格式-f filename    parser.add_argument(‘-f‘, action=‘store‘, dest=‘filename‘, required=True)    # 通過-n傳入數值,取出最多的幾行,預設取出前10    parser.add_argument(‘-n‘, action=‘store‘, dest=‘num‘, type=int, required=False, default=10)    given_args = parser.parse_args()    filename = given_args.filename    num = given_args.num    count_log(filename, num)


本文出自 “linux之路” 部落格,請務必保留此出處http://hnr520.blog.51cto.com/4484939/1880663

python分析nginx日誌

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.