2222
2323class AgentWriter (object ):
2424
25- def __init__ (self , hostname = 'localhost' , port = 8126 ):
25+ def __init__ (self , hostname = 'localhost' , port = 8126 , filters = None ):
2626 self ._pid = None
2727 self ._traces = None
2828 self ._services = None
2929 self ._worker = None
30+ self ._filters = filters
3031 self .api = api .API (hostname , port )
3132
3233 def write (self , spans = None , services = None ):
@@ -52,17 +53,23 @@ def _reset_worker(self):
5253
5354 # ensure we have an active thread working on this queue
5455 if not self ._worker or not self ._worker .is_alive ():
55- self ._worker = AsyncWorker (self .api , self ._traces , self ._services )
56+ self ._worker = AsyncWorker (
57+ self .api ,
58+ self ._traces ,
59+ self ._services ,
60+ filters = self ._filters ,
61+ )
5662
5763
5864class AsyncWorker (object ):
5965
60- def __init__ (self , api , trace_queue , service_queue , shutdown_timeout = DEFAULT_TIMEOUT ):
66+ def __init__ (self , api , trace_queue , service_queue , shutdown_timeout = DEFAULT_TIMEOUT , filters = None ):
6167 self ._trace_queue = trace_queue
6268 self ._service_queue = service_queue
6369 self ._lock = threading .Lock ()
6470 self ._thread = None
6571 self ._shutdown_timeout = shutdown_timeout
72+ self ._filters = filters
6673 self ._last_error_ts = 0
6774 self .api = api
6875 self .start ()
@@ -119,6 +126,13 @@ def _target(self):
119126
120127 while True :
121128 traces = self ._trace_queue .pop ()
129+ if traces :
130+ # Before sending the traces, make them go through the
131+ # filters
132+ try :
133+ traces = self ._apply_filters (traces )
134+ except Exception as err :
135+ log .error ("error while filtering traces:{0}" .format (err ))
122136 if traces :
123137 # If we have data, let's try to send it.
124138 try :
@@ -133,7 +147,7 @@ def _target(self):
133147 except Exception as err :
134148 log .error ("cannot send services: {0}" .format (err ))
135149
136- elif self ._trace_queue .closed ():
150+ if self ._trace_queue .closed () and self . _trace_queue . size () == 0 :
137151 # no traces and the queue is closed. our work is done
138152 return
139153
@@ -155,6 +169,24 @@ def _log_error_status(self, result, result_name):
155169 getattr (result , "status" , None ), getattr (result , "reason" , None ),
156170 getattr (result , "msg" , None ))
157171
172+ def _apply_filters (self , traces ):
173+ """
174+ Here we make each trace go through the filters configured in the
175+ tracer. There is no need for a lock since the traces are owned by the
176+ AsyncWorker at that point.
177+ """
178+ if self ._filters is not None :
179+ filtered_traces = []
180+ for trace in traces :
181+ for filtr in self ._filters :
182+ trace = filtr .process_trace (trace )
183+ if trace is None :
184+ break
185+ if trace is not None :
186+ filtered_traces .append (trace )
187+ return filtered_traces
188+ return traces
189+
158190
159191class Q (object ):
160192 """
0 commit comments