Skip to content

Commit 104f5cd

Browse files
committed
Replaced jaeger with lightstep in code
1 parent 2d5cc29 commit 104f5cd

File tree

4 files changed

+63
-41
lines changed

4 files changed

+63
-41
lines changed

pyms/flask/app/__init__.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,16 @@
44

55
import connexion
66
from flask import Flask
7-
from flask_opentracing import FlaskTracer
7+
from flask_opentracing import FlaskTracing
88

99
from pyms.config.conf import get_conf
10+
from pyms.constants import LOGGER_NAME
1011
from pyms.flask.healthcheck import healthcheck_blueprint
1112
from pyms.flask.services.driver import ServicesManager
1213
from pyms.logger import CustomJsonFormatter
13-
from pyms.tracer.main import init_jaeger_tracer
14+
from pyms.tracer.main import init_lightstep_tracer
15+
16+
logger = logging.getLogger(LOGGER_NAME)
1417

1518

1619
class Microservice:
@@ -32,15 +35,18 @@ def init_libs(self):
3235
return self.application
3336

3437
def init_tracer(self):
35-
self.application.tracer = FlaskTracer(init_jaeger_tracer(), True, self.application)
38+
self.application.opentracing_tracer = init_lightstep_tracer(self.application.config["APP_NAME"])
39+
self.application.tracer = FlaskTracing(self.application.opentracing_tracer, True, self.application)
3640

3741
def init_logger(self):
42+
self.application.logger = logger
43+
os.environ['WERKZEUG_RUN_MAIN'] = "true"
44+
3845
formatter = CustomJsonFormatter('(timestamp) (level) (name) (module) (funcName) (lineno) (message)')
3946
formatter.add_service_name(self.application.config["APP_NAME"])
40-
if getattr(self.application, "tracer", False):
41-
formatter.add_trace_span(self.application.tracer)
4247
log_handler = logging.StreamHandler()
4348
log_handler.setFormatter(formatter)
49+
4450
self.application.logger.addHandler(log_handler)
4551
self.application.logger.propagate = False
4652
self.application.logger.setLevel(logging.INFO)
@@ -78,8 +84,7 @@ def create_app(self):
7884
self.init_libs()
7985
self.add_error_handlers()
8086

81-
if not self.application.config["TESTING"]:
82-
self.init_tracer()
87+
self.init_tracer()
8388

8489
self.init_logger()
8590

pyms/flask/services/requests.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
"""Encapsulate common rest operations between business services propagating trace headers if configured.
22
"""
3+
import logging
4+
35
import opentracing
46
import requests
5-
from flask import current_app
7+
from flask import current_app, request
68

9+
from pyms.constants import LOGGER_NAME
710
from pyms.flask.services.driver import DriverService
811

12+
logger = logging.getLogger(LOGGER_NAME)
13+
914

1015
class Service(DriverService):
1116
service = "requests"
@@ -27,10 +32,10 @@ def insert_trace_headers(self, headers):
2732

2833
try:
2934
# FLASK https://github.com/opentracing-contrib/python-flask
30-
span = self._tracer.get_span()
31-
self._tracer._tracer.inject(span, opentracing.Format.HTTP_HEADERS, headers)
35+
span = self._tracer.get_span(request)
36+
self._tracer.tracer.inject(span.context, opentracing.Format.HTTP_HEADERS, headers)
3237
except Exception as ex:
33-
current_app.logger.warning("Tracer error {}".format(ex))
38+
logger.debug("Tracer error {}".format(ex))
3439
return headers
3540

3641
def _get_headers(self, headers):
@@ -87,7 +92,7 @@ def get(self, url, path_params=None, params=None, headers=None, **kwargs):
8792
:param params: (optional) Dictionary, list of tuples or bytes to send in the body of the :class:`Request` (as query
8893
string parameters)
8994
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
90-
:param \*\*kwargs: Optional arguments that ``request`` takes.
95+
:param kwargs: Optional arguments that ``request`` takes.
9196
:return: :class:`Response <Response>` object
9297
:rtype: requests.Response
9398
"""
@@ -109,7 +114,7 @@ def get_for_object(self, url, path_params=None, params=None, headers=None, **kwa
109114
:param params: (optional) Dictionary, list of tuples or bytes to send in the body of the :class:`Request` (as query
110115
string parameters)
111116
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
112-
:param \*\*kwargs: Optional arguments that ``request`` takes.
117+
:param kwargs: Optional arguments that ``request`` takes.
113118
:return: :class:`Response <Response>` object
114119
:rtype: requests.Response
115120
"""
@@ -126,7 +131,7 @@ def post(self, url, path_params=None, data=None, json=None, headers=None, **kwar
126131
:class:`Request`.
127132
:param json: (optional) json data to send in the body of the :class:`Request`.
128133
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
129-
:param \*\*kwargs: Optional arguments that ``request`` takes.
134+
:param kwargs: Optional arguments that ``request`` takes.
130135
:return: :class:`Response <Response>` object
131136
:rtype: requests.Response
132137
"""
@@ -149,7 +154,7 @@ def post_for_object(self, url, path_params=None, data=None, json=None, headers=N
149154
:class:`Request`.
150155
:param json: (optional) json data to send in the body of the :class:`Request`.
151156
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
152-
:param \*\*kwargs: Optional arguments that ``request`` takes.
157+
:param kwargs: Optional arguments that ``request`` takes.
153158
:return: :class:`Response <Response>` object
154159
:rtype: requests.Response
155160
"""
@@ -166,7 +171,7 @@ def put(self, url, path_params=None, data=None, headers=None, **kwargs):
166171
object to send in the body of the :class:`Request`.
167172
:param json: (optional) json data to send in the body of the :class:`Request`.
168173
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
169-
:param \*\*kwargs: Optional arguments that ``request`` takes.
174+
:param kwargs: Optional arguments that ``request`` takes.
170175
:return: :class:`Response <Response>` object
171176
:rtype: requests.Response
172177
"""
@@ -189,7 +194,7 @@ def put_for_object(self, url, path_params=None, data=None, headers=None, **kwarg
189194
object to send in the body of the :class:`Request`.
190195
:param json: (optional) json data to send in the body of the :class:`Request`.
191196
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
192-
:param \*\*kwargs: Optional arguments that ``request`` takes.
197+
:param kwargs: Optional arguments that ``request`` takes.
193198
:return: :class:`Response <Response>` object
194199
:rtype: requests.Response
195200
"""
@@ -203,7 +208,7 @@ def delete(self, url, path_params=None, headers=None, **kwargs):
203208
:param url: URL for the new :class:`Request` object. Could contain path parameters
204209
:param path_params: (optional) Dictionary, list of tuples with path parameters values to compose url
205210
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
206-
:param \*\*kwargs: Optional arguments that ``request`` takes.
211+
:param kwargs: Optional arguments that ``request`` takes.
207212
:return: :class:`Response <Response>` object
208213
:rtype: requests.Response
209214
"""

pyms/logger/logger.py

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
"""Return a JSON as log to insert, i.e, elasticsearch
22
"""
33
import datetime
4+
import logging
45

56
import opentracing
7+
from flask import request, current_app
68
from pythonjsonlogger import jsonlogger
79

10+
from pyms.constants import LOGGER_NAME
11+
12+
logger = logging.getLogger(LOGGER_NAME)
13+
814

915
class CustomJsonFormatter(jsonlogger.JsonFormatter):
1016
service_name = ""
@@ -21,18 +27,18 @@ def add_fields(self, log_record, record, message_dict):
2127
else:
2228
log_record['severity'] = record.levelname
2329
log_record["service"] = self.service_name
24-
25-
# Add traces
26-
if self.tracer:
27-
span = self.tracer.get_span()
30+
try:
31+
# FLASK https://github.com/opentracing-contrib/python-flask
32+
self.tracer = current_app.tracer
33+
# Add traces
34+
span = self.tracer.get_span(request=request)
2835
headers = {}
29-
self.tracer._tracer.inject(span, opentracing.Format.HTTP_HEADERS, headers)
30-
log_record["trace"] = headers['X-B3-TraceId']
31-
log_record["span"] = headers['X-B3-SpanId']
32-
log_record["parent"] = headers.get('X-B3-ParentSpanId', '')
36+
self.tracer.tracer.inject(span.context, opentracing.Format.HTTP_HEADERS, headers)
37+
log_record["trace"] = headers['ot-tracer-traceid']
38+
log_record["span"] = headers['ot-tracer-spanid']
39+
log_record["parent"] = headers.get('ot-tracer-parentspanid', '')
40+
except Exception as ex:
41+
logger.debug("Tracer error {}".format(ex))
3342

3443
def add_service_name(self, project_name):
3544
self.service_name = project_name.lower()
36-
37-
def add_trace_span(self, tracer):
38-
self.tracer = tracer

pyms/tracer/main.py

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,22 @@
11
"""Creación del tracer para progagar las trazas entre micros y servicios
22
"""
3-
from jaeger_client import Config
3+
# from jaeger_client import Config
4+
import lightstep
45

56

6-
def init_jaeger_tracer():
7-
"""This scaffold is configured whith `Jeager <https://github.com/jaegertracing/jaeger>`_ but you can use
8-
one of the `opentracing tracers <http://opentracing.io/documentation/pages/supported-tracers.html>`_
9-
:param service_name: the name of your application to register in the tracer
10-
:return: opentracing.Tracer
11-
"""
12-
config = Config(config={
13-
'propagation': 'b3',
14-
'logging': True,
15-
}, service_name="data-connection")
16-
return config.initialize_tracer()
7+
# def init_jaeger_tracer():
8+
# """This scaffold is configured whith `Jeager <https://github.com/jaegertracing/jaeger>`_ but you can use
9+
# one of the `opentracing tracers <http://opentracing.io/documentation/pages/supported-tracers.html>`_
10+
# :param service_name: the name of your application to register in the tracer
11+
# :return: opentracing.Tracer
12+
# """
13+
# config = Config(config={
14+
# 'propagation': 'b3',
15+
# 'logging': True,
16+
# }, service_name="data-connection")
17+
# return config.initialize_tracer()
18+
19+
def init_lightstep_tracer(component_name):
20+
return lightstep.Tracer(
21+
component_name=component_name,
22+
access_token='{your_access_token}')

0 commit comments

Comments
 (0)