python应用日志写入ES

python应用日志写入ES

实时/准实时方案可以使用以下3种方式实现:

  • flume+kafka+spark准实时写入ES
  • logging + CMRESHandler实时写入ES
  • 利用python中的Elasticsearch库实时写入ES
  • pyinotify后台监控文件变化写入ES
    定时写入方案则有:
  • 超时重试及定时批量写入ES
import uuid
es_id = str(uuid.uuid1())

接下来我将比较这几个方案的区别,及实现定时写入ES方案。

flume+kafka+spark实时写入ES

此方案流程为:通过flume采集日志,上送到kafka,接着spark程序订阅Topic并消费日志,然后写入ES。因为消息存在一定的滞后,所以叫准实时。对于数据量超大的场景,一般采用此方案,目前公司使用的就是这样一套系统,但同样存在问题。
随着集群上应用越来越多,资源可能不够用,导致程序偶尔会挂掉,另外kafka数据消息偶尔延时以及丢失问题,让我们难以忍受(对日志有精确要求,日志语料需要标注),因此我们决定弃用本方案。

logging + CMRESHandler实时写入ES

环境安装:
pip install CMRESHandler

简易使用方式
CMRESHandler支持的参数很多,配合logging可以方便进行日志写入管理,若想配置更简单,可以安装loguru,基本用法如下:

from cmreslogging.handlers import CMRESHandler

handler = CMRESHandler(hosts=[{'host': 'localhost', 'port': 9200}],
					   auth_type=CMRESHandler.AuthType.NO_AUTH,
					   es_index_name="my-index")
log = logging.getLogger("PythonTest")
log.setLevel(logging.INFO)
log.addHandler(handler)
log.info("This is the message from logging es")

使用kibana查看写入结果:
图片1
注意:实际的索引默认以天为单位(可以修改),写入内容包括主机名,ip等信息。

原生request请求/python-es库写入ES

可以使用python中的ElasticSearch包,调用index接口写入,同样也可以自己构造request请求
elasticsearch安装方式:
pip install elasticsearch
写入用法如下:

from elasticsearch import Elasticsearch

es = Elasticsearch([{"host": "localhost", "port": 9200}])
es.index(index="my-index", doc_type="test-type", id=01, body={"msg": "This is the message from python-es"})

使用kibana查看写入结果:
图片2
可以看出,写入内容简洁很多

以上3种实时方案看起来不错,但也存在几个问题问题

  • 数据丢失问题
    若ES集群某段时间出现异常,或某个客户端节点不可用,数据存在丢失的风险
    网络异常造成访问超时,同样存在数据丢失风险

  • 并发写入性能问题
    高并发写入ES库,对ES的性能要求造成很大挑战,同时会降低应用的并发能力(若使用异步线程问题倒不大)

pyinotify后台监控文件变化写入ES

安装:
pip install pyinotify
使用方式如下:

# !/usr/bin/env python
# coding=utf-8
import pyinotify

pos = 0


def printlog():
    global pos
    try:
        fd = open("/tmp/1.log")
        if pos != 0:
            fd.seek(pos, 0)
        while True:
            line = fd.readline()
            if line.strip():
                print line.strip()
            pos = pos + len(line)
            if not line.strip():
                break
        fd.close()

    except Exception, e:
        print str(e)


class MyEventHandler(pyinotify.ProcessEvent):
    def process_IN_MODIFY(self, event):
        try:
            print(event)
            printlog()
        except Exception, e:
            print str(e)


def main():
    printlog()
    wm = pyinotify.WatchManager()
    wm.add_watch("/tmp/1.log", pyinotify.ALL_EVENTS, rec=True)
    eh = MyEventHandler()
    notifier = pyinotify.Notifier(wm, eh)
    notifier.loop()


if __name__ == "__main__":
    main()

向文件/tmp/1.log中写入内容:
echo “222” >> /tmp/1.log
程序打印:

222

程序能实时检测到文件变化,若日志并发写入要求不是很高,则可以考虑此方案,同时需要注意监控过程中程序中断问题,中断前需要存储pos位置,方便程序重启后读取,而不是从头开始再写入一次。

自定义超时重试请求及定时批量写入ES

综合业务(对实时性要求不高,允许短暂延迟)需求,和当前集群情况(一个ES集群,2个数据节点,2个客户端节点),决定采用准实时方案。实现步骤和特点如下:

  • 后台进程每隔3秒检测日志目录
  • 根据上次读取位置获取最新日志并写入
  • 获取上次重试失败日志并再次写入

后台进程每隔3秒检测日志目录

日志目录结构为:

  • logs
    • visit
      visit_20191117
      position_info
    • warn
    • bury

      其中visit为访问日志,warn为告警日志,bury为埋点日志。
      position_info存放上次读取的日志文件和位置信息,内容如下:
      {“last_day_file_name”: “visit_20191117”, “position”: 73709}

根据上次读取位置获取最新日志并写入

def upload_log(self):
	"""
	1 若上次记录的是昨天的数据,但当前时间已经是第二天,则全部读完昨天数据
	2 获取记录位置到倒数第二行的数据
	3 更新到ES,若发生错误,则记录下来,下次更新,若连续3次更新失败则告警
	4 写入最新位置信息到位置文件
	:return:
	"""
	for es_dir_name in self.es_update_dirs:
		es_update_path = os.path.join(self.log_dir, es_dir_name)
		current_day_file_name = datetime.datetime.now().strftime('{}_%Y%m%d'.format(es_dir_name))
		position_file_path = os.path.join(es_update_path, 'position.info')
		if os.path.exists(position_file_path):
			pos_info = self._get_position_info(position_file_path)
			last_day_file_name = pos_info['last_day_file_name']
			position = pos_info['position']
		else:
			last_day_file_name = current_day_file_name
			position = 0

		# 继续写入之前失败的日志,只写入最近一次失败的日志
		retry_log_file_paths = glob.glob(os.path.join(es_update_path, '*.retry'))
		if retry_log_file_paths:
			retry_log_file_path = sorted(retry_log_file_paths, reverse=True)[0]
			failed_data = self._get_failed_data(retry_log_file_path)
			self._upload(retry_log_file_path, failed_data)

		# 写入最新增量数据
		position_new, current_data = self._get_inc_data(es_update_path, last_day_file_name, position)
		file_path = os.path.join(es_update_path, last_day_file_name)
		self._upload(file_path, current_data)

		# 到第二天的时候重新发送昨天写入错误的数据
		if current_day_file_name != last_day_file_name:
			for error_log_file_path in glob.glob(os.path.join(es_update_path, '*.error')):
				failed_data = self._get_failed_data(error_log_file_path)
				self._upload(error_log_file_path, failed_data)

		# 写入本次更新位置信息
		with open(position_file_path, 'w') as f_w:
			f_w.writelines(json.dumps({'last_day_file_name': current_day_file_name, 'position': position_new}))

这里需要注意几个问题:

  • 读取日志过程中另外进程写入,会造成最后一行数据不完整的问题。因此需要做完整性校验,比如判断是不是完整的json结构。
  • 写入网络异常失败问题。写入要重试2次,若失败,则保存下来,下次再更新。
  • 写入过程中断程序(数据已发送),接收写入结果失败,下次重写数据数据重复问题。因此要写入唯一性的日志id(日志写入本地时就需要确定)

自定义重试写入代码:

def _post_data_with_retry(self, url, data):
	if not data:
		return True
	headers = {'Content-Type': 'application/json;charset=utf-8', 'Authorization': self.http_auth}
	max_try_times = 2
	while max_try_times > 0:
		try:
			req = requests.request('POST', url, data=data, timeout=3, headers=headers)
			if req.ok:
				return True
			raise Exception(req.status_code, req.content)
		except Exception as e:
			print(e)
		time.sleep(1)
		max_try_times -= 1
	return False

由于需要验证,因此在Header中加入Authorization字段,一般格式如:“Authorization: Basic jdhaHY0=”,其中Basic表示基础认证, jdhaHY0=是base64编码的"user:passwd"字符串。
同时要注意批量写入(_bulk)时,各数据行要以\n结尾。

唯一性的日志id
一般使用python自带的uuid来生成,使用方式也很简单:
import uuid
es_id = str(uuid.uuid1())

数据完整性校验
项目中日志格式为json,因此使用eval做校验,若这行出现问题,则记录上一行的位置。

@staticmethod
def _is_last_line_valid(line):
	try:
		eval(line)
		return True
	except:
		pass
	return False

完整代码见:

最后总结一下:
本文介绍了3中实时写入ES方案和定时写入ES方案,并比较了各种方案的使用场景和优缺点。并根据项目特点,最终选择并实现了定时写入方案(又造了个轮子。。。),大家可以根据项目特点来选择不同实现方案,以上供大家参考。

发布了127 篇原创文章 · 获赞 10 · 访问量 24万+

猜你喜欢

转载自blog.csdn.net/u012599545/article/details/103020349