|
| 1 | +import { ResourceAttributes as ResourceAttributesKeys } from '@opentelemetry/semantic-conventions'; |
| 2 | +import { Resource, defaultServiceName, ResourceAttributes } from '@opentelemetry/resources'; |
| 3 | +import { SyncDetector, syncDetectorToDetector } from 'opentelemetry-resource-detector-sync-api'; |
| 4 | +import { v4 as uuidv4 } from 'uuid'; |
| 5 | +import * as fs from 'fs'; |
| 6 | + |
| 7 | +// set as global to make sure it's the same on any invocation even for multiple |
| 8 | +// instances of ServiceSyncDetector |
| 9 | +const instanceId = uuidv4(); |
| 10 | + |
| 11 | +class ServiceSyncDetector implements SyncDetector { |
| 12 | + detect(): Resource { |
| 13 | + const packageJson = this.loadJsonFile('package.json'); |
| 14 | + const attributes: ResourceAttributes = { |
| 15 | + [ResourceAttributesKeys.SERVICE_INSTANCE_ID]: instanceId, |
| 16 | + [ResourceAttributesKeys.SERVICE_NAME]: this.getServiceName(packageJson), |
| 17 | + }; |
| 18 | + const serviceVersion = packageJson?.version; |
| 19 | + if (serviceVersion) { |
| 20 | + attributes[ResourceAttributesKeys.SERVICE_VERSION] = serviceVersion; |
| 21 | + } |
| 22 | + return new Resource(attributes); |
| 23 | + } |
| 24 | + |
| 25 | + getServiceName(packageJson: any): string { |
| 26 | + const fromEnv = process.env.OTEL_SERVICE_NAME; |
| 27 | + if (fromEnv) return fromEnv; |
| 28 | + |
| 29 | + const fromPackageJson = packageJson?.name; |
| 30 | + if (fromPackageJson) return fromPackageJson; |
| 31 | + |
| 32 | + return defaultServiceName(); |
| 33 | + } |
| 34 | + |
| 35 | + loadJsonFile(path: string): any { |
| 36 | + try { |
| 37 | + return JSON.parse(fs.readFileSync(path).toString()); |
| 38 | + } catch (err) { |
| 39 | + return null; |
| 40 | + } |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +export const serviceSyncDetector = new ServiceSyncDetector(); |
| 45 | +export const serviceDetector = syncDetectorToDetector(serviceSyncDetector); |
0 commit comments