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