日志trace

代码实现

hello代码

import requests
import sys
import time
import logging
from tracing import init_tracer
import random
from opentelemetry import trace
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
from opentelemetry.trace import SpanKind

# 一个进程只能初始化一次
tracer = init_tracer("hello")
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

def say_hello(hello_to):
    with tracer.start_as_current_span('say-hello') as span:
        # 模拟如何获取trace_id
        logger.info('----test----, traceid=%x' % span.get_span_context().trace_id)
        # 添加tag:可作为搜索关键字
        span.set_attribute("say_hello", random.randint(1, 10))
        span.add_event(sys._getframe().f_code.co_name)        
        hello_str = format_string(hello_to)
        print_hello(hello_str)
        

@tracer.start_as_current_span("format")
def format_string(hello_to):
    """
    也可以使用装饰器
    """
    hello_str = ""
    try:
        hello_str = http_get(8081, 'format', 'helloTo', hello_to)
        span = trace.get_current_span()
        span.add_event(sys._getframe().f_code.co_name + "tttt")
        span.set_attribute(sys._getframe().f_code.co_name, random.randint(1, 10))
    except Exception as e:
        print (e)
    finally:
        return hello_str

def print_hello(hello_str):
    with tracer.start_as_current_span('println', kind=SpanKind.CLIENT) as span:
        http_get(8082, 'publish', 'helloStr', hello_str)
        # span.log_kv({'event': 'println'})

def http_get(port, path, param, value):
    url = 'http://localhost:%s/%s' % (port, path)
    # 把trace 信息注入到header中,发送http请求中携带trace信息
    headers = {}
    TraceContextTextMapPropagator().inject(headers)
    r = requests.get(url, params={param: value}, headers=headers)
    assert r.status_code == 200
    return r.text

# main 
assert len(sys.argv) == 2

hello_to = sys.argv[1]
for i in range(1):
    say_hello("%s_%d" % (hello_to, i))

formater

from flask import Flask
import random
from flask import request
from tracing import init_tracer
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
from opentelemetry.trace import SpanKind

app = Flask(__name__)
tracer = init_tracer('formatter') 
 
@app.route("/format")
def format():
    # 从headers中extract trace上下文信息,作为start_as_current_span的参数
    cnt = TraceContextTextMapPropagator().extract(request.headers)
    with tracer.start_as_current_span(name="format", context=cnt, kind=SpanKind.SERVER) as span:
       hello_str = request.args.get('helloTo')
       # print (request.headers)
       hello_to = request.args.get('helloTo')
       span.set_attribute("format", hello_to)
       return 'Hello, %s!' % hello_to

if __name__ == "__main__":
    app.run(port=8081)

参考文档

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容