Python函数调用追踪实现代码


Posted in Python onNovember 27, 2020

对于分布式追踪,主要有以下的几个概念:

  • 追踪 Trace:就是由分布的微服务协作所支撑的一个事务。一个追踪,包含为该事务提供服务的各个服务请求。
  • 跨度 Span:Span是事务中的一个工作流,一个Span包含了时间戳,日志和标签信息。Span之间包含父子关系,或者主从(Followup)关系。
  • 跨度上下文 Span Context:跨度上下文是支撑分布式追踪的关键,它可以在调用的服务之间传递,上下文的内容包括诸如:从一个服务传递到另一个服务的时间,追踪的ID,Span的ID还有其它需要从上游服务传递到下游服务的信息。

我实现了一种简单的调用追踪。

import uuid
import os
import time
l = []
class Recorder(object):
  def __init__(self,servername,root_span = None):
    if root_span == None:
      self.__span = Span(servername)
    else:
      self.__span = Span(servername,root_span)
  #上下文管理器
  def __enter__(self):
    return self.__span

  # 退出方法中,用来实现善后处理工作
  def __exit__(self, exc_type, exc_val, exc_tb):
    self.__span.record()
    self.__span.record_save(self.__span.span)
class Span(object):
  def __init__(self,servername,root_span = None):
    self.servername = servername
    self.span = self.newspan()
    if root_span != None:
      root_span.dic['child_span'] = self.span
      self.span["root_span_flag"] = False
  def newspan(self):
    self.dic = {
      "spanid": uuid.uuid4().int,
      "servername": self.servername,
      "location": "",
      "ip": "",
      "durationtime": 0,
      "starttime": time.time(),
      "endtime":0,
      "tag": "",
      "log": "",
      "root_span_flag":True,
      "child_span": ""
    }
    return self.dic

  def record_save(self, span):
    currenttracer = {"id": span["spanid"], "data": span}
    print(currenttracer)
    l.append(currenttracer)

  def record(self):
    self.span["servername"] = self.servername
    self.span["location"] = os.getcwd() + "." + self.servername
    self.span["endtime"] = time.time()
    self.span["durationtime"] = self.span["endtime"] - self.span["starttime"]

  def setspantag(self,tag):
    self.span["tag"] = tag

  def setspanlog(self,log):
    self.span["log"] = log

# 连续调用
with Recorder('server1') as span:
  time.sleep(1)
  span.setspantag("test")
  #调用server1方法
  print("server1")
  with Recorder('server2',span) as span1:
    time.sleep(2)
    # 调用server2方法
    print("server2")
    with Recorder('server3',span1) as span2:
      time.sleep(0.5)
      # 调用server3方法
      print("server3")
#单独调用记录
with Recorder('server4') as span_test1:
  time.sleep(1.5)
  print("server4")

with Recorder('server5') as span_test2:
  time.sleep(2)
  print("server5")

运行结果:

server1
server2
server3
{'id': 224716339449765695394515303164364012192, 'data': {'spanid': 224716339449765695394515303164364012192, 'servername': 'server3', 'location': 'D:\\python_protest\\protest\\trace\\trace_main.server3', 'ip': '', 'durationtime': 0.5004403591156006, 'starttime': 1598947338.0551107, 'endtime': 1598947338.555551, 'tag': '', 'log': '', 'root_span_flag': False, 'child_span': None}}
{'id': 254736847532758359233387151739984206570, 'data': {'spanid': 254736847532758359233387151739984206570, 'servername': 'server2', 'location': 'D:\\python_protest\\protest\\trace\\trace_main.server2', 'ip': '', 'durationtime': 2.501264810562134, 'starttime': 1598947336.0542862, 'endtime': 1598947338.555551, 'tag': '', 'log': '', 'root_span_flag': False, 'child_span': {'spanid': 224716339449765695394515303164364012192, 'servername': 'server3', 'location': 'D:\\python_protest\\protest\\trace\\trace_main.server3', 'ip': '', 'durationtime': 0.5004403591156006, 'starttime': 1598947338.0551107, 'endtime': 1598947338.555551, 'tag': '', 'log': '', 'root_span_flag': False, 'child_span': None}}}
{'id': 91028031631192607088457781914309166266, 'data': {'spanid': 91028031631192607088457781914309166266, 'servername': 'server1', 'location': 'D:\\python_protest\\protest\\trace\\trace_main.server1', 'ip': '', 'durationtime': 3.5021069049835205, 'starttime': 1598947335.0534441, 'endtime': 1598947338.555551, 'tag': 'test', 'log': '', 'root_span_flag': True, 'child_span': {'spanid': 254736847532758359233387151739984206570, 'servername': 'server2', 'location': 'D:\\python_protest\\protest\\trace\\trace_main.server2', 'ip': '', 'durationtime': 2.501264810562134, 'starttime': 1598947336.0542862, 'endtime': 1598947338.555551, 'tag': '', 'log': '', 'root_span_flag': False, 'child_span': {'spanid': 224716339449765695394515303164364012192, 'servername': 'server3', 'location': 'D:\\python_protest\\protest\\trace\\trace_main.server3', 'ip': '', 'durationtime': 0.5004403591156006, 'starttime': 1598947338.0551107, 'endtime': 1598947338.555551, 'tag': '', 'log': '', 'root_span_flag': False, 'child_span': None}}}}
server4
{'id': 103171729522922437998918618387133480096, 'data': {'spanid': 103171729522922437998918618387133480096, 'servername': 'server4', 'location': 'D:\\python_protest\\protest\\trace\\trace_main.server4', 'ip': '', 'durationtime': 1.5001769065856934, 'starttime': 1598947338.555551, 'endtime': 1598947340.055728, 'tag': '', 'log': '', 'root_span_flag': True, 'child_span': None}}
server5
{'id': 320091321623887285825256878422834254741, 'data': {'spanid': 320091321623887285825256878422834254741, 'servername': 'server5', 'location': 'D:\\python_protest\\protest\\trace\\trace_main.server5', 'ip': '', 'durationtime': 2.0005736351013184, 'starttime': 1598947340.055728, 'endtime': 1598947342.0563016, 'tag': '', 'log': '', 'root_span_flag': True, 'child_span': None}}

关于下一步,会使用redis存储其结果,并进行相应的输出分析。

修过不能追踪同级调用的问题

import uuid
import os
import time


l = []
class Recorder(object):
  def __init__(self,servername,root_span = None):
    if root_span == None:
      self.__span = Span(servername)
    else:
      self.__span = Span(servername,root_span)

  #上下文管理器
  def __enter__(self):
    return self.__span

  # 退出方法中,用来实现善后处理工作
  def __exit__(self, exc_type, exc_val, exc_tb):
    self.__span.record()
    self.__span.record_save(self.__span.span)


class Span(object):
  def __init__(self,servername,root_span = None):
    self.servername = servername
    self.span = self.newspan()
    if root_span != None:
      root_span.dic['child_span'].append(self.span)
      self.span["root_span_flag"] = False

  def newspan(self):
    self.dic = {
      "spanid": uuid.uuid4().int,
      "servername": self.servername,
      "location": "",
      "ip": "",
      "durationtime": 0,
      "starttime": time.time(),
      "endtime":0,
      "tag": "",
      "log": "",
      "root_span_flag":True,
      "child_span": []
    }
    return self.dic

  def record_save(self, span):
    currenttracer = {"id": span["spanid"], "data": span}
    print(currenttracer)
    l.append(currenttracer)

  def record(self):
    self.span["servername"] = self.servername
    self.span["location"] = os.getcwd() + "." + self.servername
    self.span["endtime"] = time.time()
    self.span["durationtime"] = self.span["endtime"] - self.span["starttime"]

  def setspantag(self,tag):
    self.span["tag"] = tag

  def setspanlog(self,log):
    self.span["log"] = log



# 连续调用
with Recorder('server1') as span:
  time.sleep(1)
  span.setspantag("test")
  #调用server1方法
  print("server1")
  with Recorder('server2',span) as span1:
    time.sleep(2)
    # 调用server2方法
    print("server2")
    with Recorder('server3',span1) as span2:
      time.sleep(0.5)
      # 调用server3方法
      print("server3")


# 并级连续调用
# with Recorder('server1') as span1:
#   time.sleep(1)
#   span1.setspantag("test")
#   #调用server1方法
#   print("server1")
#   with Recorder('server2',span1) as span2:
#     time.sleep(2)
#     # 调用server2方法
#     print("server2")
#   with Recorder('server3',span1) as span3:
#     time.sleep(0.5)
#     # 调用server3方法
#     print("server3")

# #单独调用记录
# with Recorder('server4') as span_test1:
#   time.sleep(1.5)
#   print("server4")
#
# with Recorder('server5') as span_test2:
#   time.sleep(2)
#   print("server5")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
用Python写一个无界面的2048小游戏
May 24 Python
Python进程间通信之共享内存详解
Oct 30 Python
Python实现1-9数组形成的结果为100的所有运算式的示例
Nov 03 Python
Python弹出输入框并获取输入值的实例
Jun 18 Python
Django配置文件代码说明
Dec 04 Python
浅谈keras的深度模型训练过程及结果记录方式
Jan 24 Python
浅谈Python中range与Numpy中arange的比较
Mar 11 Python
Python爬虫实现vip电影下载的示例代码
Apr 20 Python
使用python修改文件并立即写回到原始位置操作(inplace读写)
Jun 28 Python
Java byte数组操纵方式代码实例解析
Jul 22 Python
Java Unsafe类实现原理及测试代码
Sep 15 Python
Python办公自动化之Excel(中)
May 24 Python
Numpy中np.max的用法及np.maximum区别
Nov 27 #Python
python 实现aes256加密
Nov 27 #Python
pandas使用函数批量处理数据(map、apply、applymap)
Nov 27 #Python
python3.7中安装paddleocr及paddlepaddle包的多种方法
Nov 27 #Python
Python基于template实现字符串替换
Nov 27 #Python
使用Python画了一棵圣诞树的实例代码
Nov 27 #Python
python 用opencv实现霍夫线变换
Nov 27 #Python
You might like
用php和MySql来与ODBC数据连接
2006/10/09 PHP
整合了前面的PHP数据库连接类~~做成一个分页类!
2006/11/25 PHP
解析PHP中一些可能会被忽略的问题
2013/06/21 PHP
php查找指定目录下指定大小文件的方法
2014/11/28 PHP
PHP的Yii框架的基本使用示例
2015/08/21 PHP
IE/FireFox具备兼容性的拖动代码
2007/08/13 Javascript
Extjs学习笔记之九 数据模型(上)
2010/01/11 Javascript
中文字符串截取的js函数代码
2013/04/17 Javascript
使用Nodejs开发微信公众号后台服务实例
2014/09/03 NodeJs
基于JavaScript FileReader上传图片显示本地链接
2016/05/27 Javascript
jQuery插件DataTable使用方法详解(.Net平台)
2016/12/22 Javascript
vue.js利用defineProperty实现数据的双向绑定
2017/04/28 Javascript
解决webpack无法通过IP地址访问localhost的问题
2018/02/22 Javascript
Vue 项目代理设置的优化
2018/04/17 Javascript
小程序scroll-view组件实现滚动的示例代码
2018/09/20 Javascript
React实现全局组件的Toast轻提示效果
2018/09/21 Javascript
vue中通过使用$attrs实现组件之间的数据传递功能
2019/09/01 Javascript
对Layer弹窗使用及返回数据接收的实例详解
2019/09/26 Javascript
Vue 实现输入框新增搜索历史记录功能
2019/10/15 Javascript
为什么选择python编程语言入门黑客攻防 给你几个理由!
2018/02/02 Python
Python在图片中插入大量文字并且自动换行
2019/01/02 Python
pow在python中的含义及用法
2019/07/11 Python
基于python3的socket聊天编程
2020/02/17 Python
python输出数学符号实例
2020/05/11 Python
tensorflow dataset.shuffle、dataset.batch、dataset.repeat顺序区别详解
2020/06/03 Python
Python 抓取数据存储到Redis中的操作
2020/07/16 Python
html5使用window.postMessage进行跨域实现数据交互的一次实战
2021/02/24 HTML / CSS
安全检查与奖惩制度
2014/01/23 职场文书
单位授权委托书范文
2014/08/02 职场文书
作风建设剖析材料
2014/10/06 职场文书
优秀护士事迹材料
2014/12/25 职场文书
2015年大学生党员承诺书
2015/04/27 职场文书
会计实训总结范文
2015/08/03 职场文书
SpringBoot生成License的实现示例
2021/06/16 Java/Android
MySQL的索引你了解吗
2022/03/13 MySQL
Java完整实现记事本代码
2022/06/16 Java/Android