open-telemetry / opentelemetry-swift

OpenTelemetry API for Swift
https://opentelemetry.io/docs/instrumentation/swift/
Apache License 2.0
207 stars 124 forks source link

OC project references this project #267

Closed lzctxwd closed 2 years ago

lzctxwd commented 2 years ago

Whether this project supports the use of the OC project. I tried to introduce this project into the OC project, which can be initialized, but it did not take effect when I used the HTTP request to intercept it

nachoBonafonte commented 2 years ago

Yes, it supports Objective-C project, you must initialize it from Swift code, but the network instrumentation should capture your network requests started from Objective-C, the network library must be NSURLSession or based on it . In fact, I am using it myself in another project for intersecting network requests initiated from Objective-C.

NSURLConnection API's are not supported though, if you network requests are NSURLConnection based, then they will not be captured. The library could be updated to support it, but that API has been obsoleted for a way long time. Is your code using NSURLConnection or NSURLSession? The latter should work independently from the language.

lzctxwd commented 2 years ago

@nachoBonafonte Yes, I use NSURLsession, and initialized in swift like it:

class Test: NSObject {
    @objc func initInstrumentation() {
        let spanProcessor = BatchSpanProcessor(spanExporter:     ZipkinTraceExporter.init(options:ZipkinTraceExporterOptions(endpoint: "http://100.83.82.43:9411/api/v2/spans")))
        OpenTelemetrySDK.instance.tracerProvider.addSpanProcessor(spanProcessor)
        let networkInstrumentation = URLSessionInstrumentation(configuration: URLSessionInstrumentationConfiguration(shouldInstrument: {
            if $0.url?.absoluteString == "http://xx.xx.xx.xx:9411/api/v2/spans" {
               return false
            }
            return true}))
    }
}

Then it is called in the Objective-C project project like it:

Test *test = [[Test alloc] init];
[test initInstrumentation];
nachoBonafonte commented 2 years ago

I have recreated a Obj-C small project, and have started simple, just using StdoutExporter like this:

class Test: NSObject {
    @objc func initInstrumentation() {
        let spanProcessor = BatchSpanProcessor(spanExporter: StdoutExporter(isDebug: true))
        OpenTelemetrySDK.instance.tracerProvider.addSpanProcessor(spanProcessor)
        _ = URLSessionInstrumentation(configuration: URLSessionInstrumentationConfiguration())
    }
}

And it works as expected for me, can you confirm if if it also works for you?

I am attaching the sample project here: OTTEST.zip

lzctxwd commented 2 years ago

@nachoBonafonte Thank you very much. Through your example, I found some problems I cited. Now the problems have been solved