@@ -2,7 +2,7 @@ import { NodeSDK } from "@opentelemetry/sdk-node";
2
2
import { SpanProcessor } from "@opentelemetry/sdk-trace-node" ;
3
3
import { context , diag } from "@opentelemetry/api" ;
4
4
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto" ;
5
- import { resourceFromAttributes , Resource } from "@opentelemetry/resources" ;
5
+ import { Resource } from "@opentelemetry/resources" ;
6
6
import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions" ;
7
7
import { Instrumentation } from "@opentelemetry/instrumentation" ;
8
8
import { InitializeOptions } from "../interfaces" ;
@@ -307,35 +307,10 @@ export const startTracing = (options: InitializeOptions) => {
307
307
spanProcessors . push ( options . processor ) ;
308
308
}
309
309
310
- // Create resource with proper detection and defensive handling for OTLP serialization
311
- const serviceName =
312
- options . appName || process . env . npm_package_name || "unknown-service" ;
313
- let resource : Resource ;
314
-
315
- try {
316
- // Create our custom resource with service name and let NodeSDK handle default detection
317
- resource = resourceFromAttributes ( {
318
- [ ATTR_SERVICE_NAME ] : serviceName ,
319
- } ) ;
320
-
321
- // Defensive check to prevent OTLP serialization errors
322
- if ( ! resource || typeof resource !== "object" ) {
323
- throw new Error ( "Invalid resource object" ) ;
324
- }
325
-
326
- if ( ! resource . attributes || typeof resource . attributes !== "object" ) {
327
- throw new Error ( "Resource missing attributes" ) ;
328
- }
329
- } catch ( error ) {
330
- // Fallback: create a basic resource manually
331
- diag . warn (
332
- "Failed to create resource with resourceFromAttributes, using fallback" ,
333
- error ,
334
- ) ;
335
- resource = resourceFromAttributes ( {
336
- [ ATTR_SERVICE_NAME ] : serviceName ,
337
- } ) ;
338
- }
310
+ const resource = createResource ( {
311
+ [ ATTR_SERVICE_NAME ] :
312
+ options . appName || process . env . npm_package_name || "unknown_service" ,
313
+ } ) ;
339
314
340
315
_sdk = new NodeSDK ( {
341
316
resource,
@@ -378,3 +353,17 @@ export const shouldSendTraces = () => {
378
353
export const forceFlush = async ( ) => {
379
354
await _spanProcessor . forceFlush ( ) ;
380
355
} ;
356
+
357
+ // Compatibility function for creating resources that works with both OTel v1.x and v2.x
358
+ function createResource ( attributes : Record < string , any > ) : Resource {
359
+ // Import the resource module at runtime to handle both v1.x and v2.x
360
+ const resourcesModule = require ( "@opentelemetry/resources" ) ;
361
+
362
+ // Try to use resourceFromAttributes if it exists (OTel v2.x)
363
+ if ( resourcesModule . resourceFromAttributes ) {
364
+ return resourcesModule . resourceFromAttributes ( attributes ) ;
365
+ }
366
+
367
+ // Fallback to constructor for OTel v1.x
368
+ return new resourcesModule . Resource ( attributes ) ;
369
+ }
0 commit comments