1. 程式人生 > >[django]自定義handlers寫入Mysql

[django]自定義handlers寫入Mysql

django:V2.1

python:3.6 

#!/user/bin/python
# -*- coding:utf-8 -*-

"""
File: handlers.py
Author: wendell
E-mail: [email protected]
Last modified: 2018-11-10 18:30
Description:
"""

from alarm.util.db_utils import MysqlDB
from decouple import config
import datetime
import logging
import re

class DatabaseHandler(logging.Handler):

	def __init__(self,db_host,db_user,db_pass,db):
		logging.Handler.__init__(self)
		self.conn = MysqlDB(host=db_host,user=db_user,password=db_pass,db=db)

	def getRemoteIP(self,param):
		res = str(param.__enter__()).split(',')[-2][9:-1]
		return res

	def build_table(self,db):
		sql = """CREATE TABLE log (
			id  INT  AUTO_INCREMENT PRIMARY KEY,
			level  CHAR(4),
			content  VARCHAR(64),
			ip  CHAR(16),
			time datetime)"""
		db.insert(sql)

	def insert2db(self,db,record):
		request = record.request
		level = record.levelname
		msg = record.getMessage()
		_ip = self.getRemoteIP(request)
		_time = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
		sql = "INSERT INTO log (level,content,ip,time) VALUES ('%s','%s','%s','%s')"%(level,msg,_ip,_time)
		db.insert(sql)

	def emit(self,record):
		try:
			db = self.conn
			self.insert2db(db,record)
		except:
			try:
				self.build_table(db)
				self.insert2db(db,record)
			except:
				pass

	def close(self):
		self.conn.close()
#!/usr/bin/python
# -*- coding:utf-8 -*-

"""
File: db_utils.py
Author: wendell
E-mail: [email protected]
Last modified: 2018-11-10 18:30
Description:
"""

import pymysql as ps
import datetime

class MysqlDB(object):

	def __init__(self,host,user,password,db):
		self.conn = ps.connect(host=host,user=user,password=password,db=db,charset='UTF8')
		self.cursor = self.conn.cursor()

	def getItemsByParam(self,sql,param):
		rows = self.cursor.execute(sql%param)
		if rows != 0:
			res = self.cursor.fetchall()
			return res
		return None

	def getOneByParam(self,sql,param):
		row = self.cursor.execute(sql%param)
		if row != 0:
			res = self.cursor.fetchone()
			return res
		return None

	def getByParams(self,sql,params):
		in_p=', '.join(list(map(lambda x:'%s',params)))
		sql = sql%in_p
		row = self.cursor.execute(sql,params)
		if row != 0:
			res = list(self.cursor.fetchall())
			return res
		return None

	def insert(self,sql):
		row = self.cursor.execute(sql)
		self.conn.commit()

	def close(self):
		self.cursor.close()
		self.conn.close()