본문 바로가기
[ ★ ]Study/Programming

파이썬 mysql 로그 삽입

by nroses-taek 2020. 8. 25.
반응형

pymysql 을 이용한 mysql db로그 삽입하기.

import pymysql

conn = pymysql.connect(host='localhost', user='hello_mysql', password='1', db='logs', charset='utf8')
curs = conn.cursor()
sql = "insert into access_log(ip, access_time, method, uri, status)\
    values (%s,%s, %s, %s,%s)"

logfile_path = '/경로/'
logfile_fullpath = logfile_path + '파일이름'
count = 0
with open(logfile_fullpath, 'r') as f:
    for line in f:
        count += 1
        log_parse = line.split(' ')

        ip = log_parse[1]
        time = log_parse[4] + log_parse[5]
        method = log_parse[6]
        uri = log_parse[7]
        status = log_parse[9]
        status_s = int(status)
        if status_s > 200:
            continue

        curs.execute(sql, (ip, time, method, uri, int(status)))
        conn.commit()

        if count > 10:
            conn.close()
            break

f.close()
반응형

댓글