|
3 | 3 | // SPDX-License-Identifier: Apache-2.0 |
4 | 4 | // |
5 | 5 |
|
6 | | -import OpenTelemetrySdk |
7 | 6 | import Foundation |
| 7 | +import OpenTelemetrySdk |
8 | 8 |
|
9 | 9 | public func defaultOltpHttpTracesEndpoint() -> URL { |
10 | 10 | URL(string: "http://localhost:4318/v1/traces")! |
11 | 11 | } |
12 | 12 |
|
13 | 13 | public class OtlpHttpTraceExporter: OtlpHttpExporterBase, SpanExporter { |
14 | 14 | var pendingSpans: [SpanData] = [] |
15 | | - |
| 15 | + |
16 | 16 | override |
17 | 17 | public init(endpoint: URL = defaultOltpHttpTracesEndpoint(), useSession: URLSession? = nil) { |
18 | 18 | super.init(endpoint: endpoint, useSession: useSession) |
19 | 19 | } |
20 | | - |
| 20 | + |
21 | 21 | public func export(spans: [SpanData]) -> SpanExporterResultCode { |
22 | 22 | pendingSpans.append(contentsOf: spans) |
23 | | - return self.flush() |
24 | | - } |
25 | | - |
26 | | - public func flush() -> SpanExporterResultCode { |
27 | | - var exporterResult: SpanExporterResultCode = .failure |
28 | | - let spans = pendingSpans |
| 23 | + let sendingSpans = pendingSpans |
29 | 24 | pendingSpans = [] |
| 25 | + |
30 | 26 | let body = Opentelemetry_Proto_Collector_Trace_V1_ExportTraceServiceRequest.with { |
31 | 27 | $0.resourceSpans = SpanAdapter.toProtoResourceSpans(spanDataList: spans) |
32 | 28 | } |
33 | | - |
34 | 29 | let request = createRequest(body: body, endpoint: endpoint) |
35 | | - httpClient.send(request: request) { result in |
| 30 | + httpClient.send(request: request) { [weak self] result in |
36 | 31 | switch result { |
37 | | - case .success(_): |
38 | | - exporterResult = SpanExporterResultCode.success |
| 32 | + case .success: |
| 33 | + break |
39 | 34 | case .failure(let error): |
| 35 | + self?.pendingSpans.append(contentsOf: sendingSpans) |
40 | 36 | print(error) |
41 | | - exporterResult = SpanExporterResultCode.failure |
42 | 37 | } |
43 | 38 | } |
44 | | - return exporterResult |
| 39 | + return .success |
| 40 | + } |
| 41 | + |
| 42 | + public func flush() -> SpanExporterResultCode { |
| 43 | + var resultValue: SpanExporterResultCode = .success |
| 44 | + if !pendingSpans.isEmpty { |
| 45 | + let body = Opentelemetry_Proto_Collector_Trace_V1_ExportTraceServiceRequest.with { |
| 46 | + $0.resourceSpans = SpanAdapter.toProtoResourceSpans(spanDataList: pendingSpans) |
| 47 | + } |
| 48 | + let semaphore = DispatchSemaphore(value: 0) |
| 49 | + let request = createRequest(body: body, endpoint: endpoint) |
| 50 | + |
| 51 | + httpClient.send(request: request) { result in |
| 52 | + switch result { |
| 53 | + case .success: |
| 54 | + break |
| 55 | + case .failure(let error): |
| 56 | + print(error) |
| 57 | + resultValue = .failure |
| 58 | + } |
| 59 | + semaphore.signal() |
| 60 | + } |
| 61 | + semaphore.wait() |
| 62 | + } |
| 63 | + return resultValue |
45 | 64 | } |
46 | 65 | } |
0 commit comments