@evenicanpm/common-core 1.7.0 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,10 +1,15 @@
1
1
  {
2
2
  "name": "@evenicanpm/common-core",
3
- "version": "1.7.0",
3
+ "version": "1.8.1",
4
4
  "description": "Common module for Headless Storefront and Admin panel",
5
5
  "author": "Evenica",
6
6
  "type": "module",
7
7
  "license": "ISC",
8
+ "exports": {
9
+ ".": "./src/index.ts",
10
+ "./otel": "./src/otel/index.ts",
11
+ "./keyvault": "./src/lib/keyvault.ts"
12
+ },
8
13
  "scripts": {
9
14
  "test": "echo \"Error: no test specified\" && exit 1"
10
15
  },
@@ -25,5 +30,6 @@
25
30
  },
26
31
  "devDependencies": {
27
32
  "@types/node": "^24.0.13"
28
- }
33
+ },
34
+ "gitHead": "07cfd4496c6a137e1420a6572298998b25b6369d"
29
35
  }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./otel";
2
+ export * from "./lib";
@@ -1,44 +1,65 @@
1
- # Using Opentelemetry in e4
1
+ # Using OpenTelemetry in e4
2
2
 
3
- - `setup.ts` has two main paths:
4
- 1. Azure Not Enabled - Will setup OLTP and @vercel/otel Registration for auto instrumentation with nextjs
5
- 2. Azure Enabled - Does the above AND Azure monitoring for metrics, logs, and traces
3
+ ## Setup in Next.js
6
4
 
7
- ## Using a Tracer Example
5
+ Call `setupOtel` in a server initialization file (NOT in `instrumentation.ts` due to environment variable timing issues).
8
6
 
9
- From https://opentelemetry.io/docs/languages/js/instrumentation/
7
+ **Example: In your `src/lib/otel-init.ts` or similar:**
10
8
 
11
9
  ```ts
12
- import opentelemetry from "@opentelemetry/api";
13
- //...
10
+ import { setupOtel } from "@evenicanpm/common-core/otel";
14
11
 
15
- const tracer = opentelemetry.trace.getTracer(
16
- "instrumentation-scope-name",
17
- "instrumentation-scope-version",
18
- );
12
+ export async function initializeOTel() {
13
+ await setupOtel({
14
+ serviceName: "storefront",
15
+ azureMonitor: {
16
+ connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING,
17
+ },
18
+ });
19
+ }
20
+ ```
21
+
22
+ **Then import it early in your server startup** (e.g., in a route handler or API middleware that runs first):
19
23
 
20
- // You can now use a 'tracer' to do tracing!
24
+ ```ts
25
+ // In your first API route or middleware
26
+ import { initializeOTel } from "@/lib/otel-init";
27
+ await initializeOTel();
21
28
  ```
22
29
 
23
- ## Starting a Span
30
+ ## Configuration
24
31
 
32
+ **Azure Monitor Only:**
25
33
  ```ts
26
- return tracer.startActiveSpan("rollTheDice", (span: Span) => {
27
- const result: number[] = [];
28
- for (let i = 0; i < rolls; i++) {
29
- result.push(rollOnce(min, max));
30
- }
31
- // Be sure to end the span!
32
- span.end();
33
- return result;
34
+ await setupOtel({
35
+ serviceName: "storefront",
36
+ azureMonitor: {
37
+ connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING,
38
+ },
39
+ });
40
+ ```
41
+
42
+ **OTLP Only:**
43
+ ```ts
44
+ await setupOtel({
45
+ serviceName: "storefront",
46
+ otlp: {
47
+ traceUrl: process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT,
48
+ },
34
49
  });
35
50
  ```
36
51
 
37
52
  ## Using the Logger
38
53
 
39
54
  ```ts
40
- import log from "@evenicanpm/common-core/src/otel/logger";
55
+ import { logger } from "@evenicanpm/common-core/otel";
41
56
 
42
- const logger = log();
43
- logger.info("This is some e4 info!");
57
+ const log = logger();
58
+ log.info("Operation successful", { userId: "123" });
59
+ log.error("Operation failed", error, { operation: "createUser" });
44
60
  ```
61
+
62
+ ## References
63
+
64
+ - [OpenTelemetry JS Docs](https://opentelemetry.io/docs/languages/js/)
65
+ - [Azure Monitor Exporter](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/monitor/monitor-opentelemetry-exporter)
@@ -0,0 +1,3 @@
1
+ export { default as logger } from "./logger";
2
+ export { setupOtel } from "./setup";
3
+ export type { AzureMonitorConfig, OtelConfig, OtlpConfig } from "./setup";
package/src/otel/setup.ts CHANGED
@@ -13,87 +13,143 @@ import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-node";
13
13
  import { registerOTel } from "@vercel/otel";
14
14
 
15
15
  /**
16
- * The configuration object passed to setupOtel function.
16
+ * Configuration for OTLP trace export.
17
+ */
18
+ interface OtlpConfig {
19
+ /**
20
+ * Full OTLP HTTP endpoint used for trace export.
21
+ *
22
+ * Example: `http://otel-collector:4318/v1/traces`
23
+ */
24
+ traceUrl: string;
25
+ }
26
+
27
+ /**
28
+ * Configuration for Azure Monitor exporters.
29
+ */
30
+ interface AzureMonitorConfig {
31
+ /**
32
+ * Azure Monitor connection string used by the exporter instances.
33
+ */
34
+ connectionString: string;
35
+ /**
36
+ * Enables Azure Monitor trace exporting.
37
+ *
38
+ * Defaults to `true` when `azureMonitor` is provided.
39
+ */
40
+ traces?: boolean;
41
+ /**
42
+ * Enables Azure Monitor log exporting and registers a global logger provider.
43
+ *
44
+ * Defaults to `true` when `azureMonitor` is provided.
45
+ */
46
+ logs?: boolean;
47
+ /**
48
+ * Enables Azure Monitor metric exporting and registers a global meter provider.
49
+ *
50
+ * Defaults to `true` when `azureMonitor` is provided.
51
+ */
52
+ metrics?: boolean;
53
+ /**
54
+ * Enables host-level metric collection when Azure Monitor metrics are enabled.
55
+ *
56
+ * Defaults to the value of `metrics`.
57
+ */
58
+ hostMetrics?: boolean;
59
+ }
60
+
61
+ /**
62
+ * Public configuration for OTel setup.
17
63
  */
18
64
  interface OtelConfig {
65
+ /**
66
+ * Logical service name attached to emitted telemetry.
67
+ */
19
68
  serviceName: string;
20
- AzureEnabled?: boolean;
21
- AzureMonitorKey?: string;
69
+ /**
70
+ * Optional OTLP trace exporter configuration.
71
+ */
72
+ otlp?: OtlpConfig;
73
+ /**
74
+ * Optional Azure Monitor exporter configuration.
75
+ */
76
+ azureMonitor?: AzureMonitorConfig;
22
77
  }
23
78
 
24
79
  /**
25
- * The core setup for Azure Insights and opentelemetry for
26
- * admin and storefront. Config can be extended to support multiple
27
- * opentelemetry exports.
80
+ * Registers telemetry exporters and providers for the current runtime.
81
+ *
82
+ * The caller owns environment-variable lookup and passes only the
83
+ * configuration needed for the current project.
84
+ *
85
+ * @param otelConfig Configuration for service naming and enabled exporters.
86
+ * @returns The result of `registerOTel` after span processors are attached.
28
87
  */
29
- async function setupOtel(otelConfig?: OtelConfig) {
30
- if (!process.env.OTELCOL_URL) {
31
- throw new Error("Missing OTELCOL_URL environment variable.");
32
- }
33
-
34
- const { serviceName, AzureEnabled, AzureMonitorKey } = otelConfig ?? {};
88
+ async function setupOtel(otelConfig: OtelConfig) {
89
+ const { serviceName, otlp, azureMonitor } = otelConfig;
90
+ const spanProcessors: BatchSpanProcessor[] = [];
35
91
 
36
- if (!AzureEnabled) {
37
- return registerOTel({
38
- serviceName: otelConfig?.serviceName,
39
- spanProcessors: [
40
- new BatchSpanProcessor(
41
- new OTLPTraceExporter({ url: process.env.OTELCOL_URL }),
42
- ),
43
- ],
44
- });
92
+ if (otlp?.traceUrl) {
93
+ spanProcessors.push(
94
+ new BatchSpanProcessor(new OTLPTraceExporter({ url: otlp.traceUrl })),
95
+ );
45
96
  }
46
97
 
47
- /** Azure Enabled */
48
- if (!AzureMonitorKey)
49
- throw new Error("No Azure Monitor Connection String Provided.");
98
+ if (azureMonitor) {
99
+ const enableAzureTraces = azureMonitor.traces ?? true;
100
+ const enableAzureLogs = azureMonitor.logs ?? true;
101
+ const enableAzureMetrics = azureMonitor.metrics ?? true;
102
+ const enableHostMetrics = azureMonitor.hostMetrics ?? enableAzureMetrics;
103
+ const config = {
104
+ connectionString: azureMonitor.connectionString,
105
+ };
50
106
 
51
- const connectionString = AzureMonitorKey;
52
- const config = { connectionString };
107
+ const {
108
+ AzureMonitorMetricExporter,
109
+ AzureMonitorTraceExporter,
110
+ AzureMonitorLogExporter,
111
+ } = await import("@azure/monitor-opentelemetry-exporter");
53
112
 
54
- // Azure - Imports
55
- const {
56
- AzureMonitorMetricExporter,
57
- AzureMonitorTraceExporter,
58
- AzureMonitorLogExporter,
59
- } = await import("@azure/monitor-opentelemetry-exporter");
60
- const { HostMetrics } = await import("@opentelemetry/host-metrics");
113
+ if (enableAzureTraces) {
114
+ spanProcessors.push(
115
+ new BatchSpanProcessor(new AzureMonitorTraceExporter(config)),
116
+ );
117
+ }
61
118
 
62
- // Azure - Monitor Exporters
63
- const metricsExporter = new AzureMonitorMetricExporter(config);
64
- const logExporter = new AzureMonitorLogExporter(config);
65
- const traceExporter = new AzureMonitorTraceExporter(config);
119
+ if (enableAzureLogs) {
120
+ const logExporter = new AzureMonitorLogExporter(config);
121
+ const logProcessor = new BatchLogRecordProcessor(logExporter, {
122
+ maxExportBatchSize: 100,
123
+ });
124
+ const loggerProvider = new LoggerProvider({
125
+ processors: [logProcessor],
126
+ });
127
+ logs.setGlobalLoggerProvider(loggerProvider);
128
+ }
66
129
 
67
- // Azure - Logging
68
- const logProcessor = new BatchLogRecordProcessor(logExporter, {
69
- maxExportBatchSize: 100,
70
- });
71
- const loggerProvider = new LoggerProvider({ processors: [logProcessor] });
72
- logs.setGlobalLoggerProvider(loggerProvider);
130
+ if (enableAzureMetrics) {
131
+ const metricsExporter = new AzureMonitorMetricExporter(config);
132
+ const metricReader = new PeriodicExportingMetricReader({
133
+ exporter: metricsExporter,
134
+ });
135
+ const meterProvider = new MeterProvider({
136
+ readers: [metricReader],
137
+ });
138
+ metrics.setGlobalMeterProvider(meterProvider);
73
139
 
74
- // Azure - Metrics
75
- const metricReaderOptions = {
76
- exporter: metricsExporter,
77
- };
78
- const metricReader = new PeriodicExportingMetricReader(metricReaderOptions);
79
- const meterProvider = new MeterProvider({
80
- readers: [metricReader],
81
- });
82
- metrics.setGlobalMeterProvider(meterProvider);
83
- // OS level Metrics
84
- const hostMetrics = new HostMetrics({ meterProvider });
85
- hostMetrics.start();
140
+ if (enableHostMetrics) {
141
+ const { HostMetrics } = await import("@opentelemetry/host-metrics");
142
+ const hostMetrics = new HostMetrics({ meterProvider });
143
+ hostMetrics.start();
144
+ }
145
+ }
146
+ }
86
147
 
87
- /** NextJS Otel Registration */
88
- registerOTel({
89
- serviceName: serviceName,
90
- spanProcessors: [
91
- new BatchSpanProcessor(traceExporter),
92
- new BatchSpanProcessor(
93
- new OTLPTraceExporter({ url: process.env.OTELCOL_URL }),
94
- ),
95
- ],
148
+ return registerOTel({
149
+ serviceName,
150
+ ...(spanProcessors.length > 0 ? { spanProcessors } : {}),
96
151
  });
97
152
  }
98
153
 
154
+ export type { AzureMonitorConfig, OtelConfig, OtlpConfig };
99
155
  export { setupOtel };