save nginx log to mysql

#!/usr/bin/env python

import sys
import getopt
import time

import MySQLdb

class DataHandle:
    conn = None;
    cursor = None;
    def __init__(self):
        pass
    def connect(self):
        self.conn = MySQLdb.connect(host='127.0.0.1', db='nginx_log', user='root', passwd='123456');
        self.cursor = self.conn.cursor();

    def disconnect(self):
        self.cursor.close();
        self.conn.close();
    def save_data(self, time, ip, request, status, byte, agent):
        data = (time, ip, request, status, byte, agent);
        query = "insert into `access`(time, ip, request, status, byte, agent) values(%s,%s,%s,%s,%s,%s)";
        self.cursor.execute(query, data);
        self.conn.commit();


dataHandle = DataHandle();
def split_line(line):
    log = line;
    #log='118.69.100.139 - - [20/Oct/2016:10:03:49 +0800] "POST /v1/user/register HTTP/1.1" 200 109 "-" "Dalvik/2.1.0 (Linux; U; Android 6.0; Masstel N520 Build/MRA58K)"';
    index=log.find(' ');
    ip=log[0:index];

    log=log[index+1:];
    index=log.find(' ');
    line = log[0:index];

    log=log[index+1:];
    index=log.find(' ');
    user = log[0:index];

    log=log[index+1:];
    index=log.find(']');
    user_time = log[1:index];

    ti = user_time.find(' ');
    user_time = time.strptime(user_time[0:ti], "%d/%b/%Y:%H:%M:%S");
    user_time = int(time.mktime(user_time));


    log=log[index+3:];
    index=log.find('"');
    request = log[0:index];

    ri1 = request.find(' ');
    ri2 = request.find(' ',ri1+1);
    request = request[ri1+1:ri2];

    log=log[index+2:];
    index=log.find(' ');
    status = log[0:index];

    log=log[index+1:];
    index=log.find(' ');
    byte = log[0:index];

    log=log[index+1:];
    index=log.find(' ');
    refere = log[0:index];

    log=log[index+2:];
    index=log.find('"');
    agent = log[0:index];

    print ip, ";", line, ";", user, ";", user_time, ";", request, ";", status, ";", byte, ";", refere, ";", agent;
    dataHandle.save_data(user_time, ip, request, status, byte, agent);

def read_logs(file_path):
    dataHandle.connect();
    logs = open(file_path);
    for line in logs:
        split_line(line);
    dataHandle.disconnect();

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hf:', ['help'])
    except getopt.GetoptError as err:
        print '[ERROR]:', err
        sys.exit(1)

    log_path = None;
    print opts;
    for o, a in opts:
        if o == "-f":
            log_path = a;
    if (log_path == None):
        print "need -f file_path";
        sys.exit(1);

    read_logs(log_path);

if __name__ == '__main__':
    main()

你可能感兴趣的:(save nginx log to mysql)