python 将nginx日志写得mysql

#/usr/bin/env python

#-*-coding:UTF-8 -*-

from  datetime  import  datetime

import   pymysql

connect=pymysql.connect(

   host='127.0.0.1',

   port=3306,

   user='root',

   password='',

   database='nginxlog',

   charset="utf8"

 

)

cur = connect.cursor()

sql= "insert into nginxlog(ip,time,methods,source,protocol,status) values(%s,%s,%s,%s,%s,%s)"

 

with open("D:/tools/nginx-1.17.9/logs\host.access.log","r")  as  ngfile:

   for line in ngfile:

      _nodes = line.split()

      IP= _nodes[0]

      Time= _nodes[3][1:-1].replace(":"," ",1) #将时间转换为17/Jun/2017 12:43:4格式

      Time = datetime.strptime(Time,"%d/%b/%Y %H:%M:%S")#将时间格式化为2017-06-17 12:43:04

      Methods = _nodes[5][1:]

      Source = _nodes[6]

      Protocol = _nodes[7][:-1]

      Status = _nodes[8]

      print(IP,Time,Methods,Source,Protocol,Status)

      cur.execute(sql,(IP,Time,Methods,Source,Protocol,Status))

      connect.commit()

   connect.close()

本文章由javascript技术分享原创和收集

如若转载请注明原文及出处:https://www.dsiab.com/post/371903f7-a27e-4ad8-9ce5-662b25d3c5a4
本站文章由javascript技术分享原创和收集,内容如有问题,请联系站长删除。