@sebspark/otel 0.1.0
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/LICENSE +201 -0
- package/README.md +158 -0
- package/dist/index.d.mts +46 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.js +228 -0
- package/dist/index.mjs +212 -0
- package/package.json +36 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [2023] [SEB]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
# `@sebspark/otel`
|
|
2
|
+
|
|
3
|
+
Open Telemetry implementation of logging, tracing and metrics
|
|
4
|
+
|
|
5
|
+
## Usage
|
|
6
|
+
|
|
7
|
+
Run:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @sebspark/otel
|
|
11
|
+
# or
|
|
12
|
+
yarn add @sebspark/otel
|
|
13
|
+
# or
|
|
14
|
+
pnpm add @sebspark/otel
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
**Initialization and Context Detection**
|
|
18
|
+
|
|
19
|
+
The **OpenTelemetry SDK** is automatically initialized when you import `@sebspark/otel`.
|
|
20
|
+
|
|
21
|
+
**This should be the first import in your application.**
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import '@sebspark/otel'
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
This setup:
|
|
28
|
+
|
|
29
|
+
- Uses **OpenTelemetry auto-instrumentations** to trace supported libraries
|
|
30
|
+
- **HTTP**, **gRPC**, **Redis**, **PostgreSQL** etc.
|
|
31
|
+
- **Auto-detects environment metadata**, including:
|
|
32
|
+
- **GCP** service name (e.g., **Cloud Run**, **GKE**, **GCE**, etc.)
|
|
33
|
+
- Instance and zone/region
|
|
34
|
+
- Enables **W3C Trace Context** propagation across async operations and network boundaries
|
|
35
|
+
- Automatically links logs with `trace_id` and `span_id` inside active spans
|
|
36
|
+
- Supports clean shutdown via `SIGTERM` (e.g. **Cloud Run**, **Kubernetes**)
|
|
37
|
+
|
|
38
|
+
In **GCP** environments, this ensures that traces are correlated across **Cloud Logging**, **Cloud Trace**, and **Cloud Monitoring** without extra setup.
|
|
39
|
+
|
|
40
|
+
#### Environment-aware attributes
|
|
41
|
+
|
|
42
|
+
The following values are detected and attached as `resourceAttributes`:
|
|
43
|
+
|
|
44
|
+
**Env Variable** | **Attribute Key** | **Description**
|
|
45
|
+
------------------------|-------------------------|-------------------------------
|
|
46
|
+
OTEL_SERVICE_NAME | service.name | Overrides service name
|
|
47
|
+
OTEL_SERVICE_VERSION | service.version | Version of the current service
|
|
48
|
+
K_SERVICE | cloud.run.service | Cloud Run service name
|
|
49
|
+
K_REVISION | cloud.run.revision | Cloud Run revision
|
|
50
|
+
K_CONFIGURATION | cloud.run.configuration | Cloud Run config
|
|
51
|
+
POD_NAME | k8s.pod_name | Kubernetes pod name
|
|
52
|
+
POD_NAMESPACE | k8s.namespace_name | Kubernetes namespace
|
|
53
|
+
KUBERNETES_SERVICE_HOST | cloud.orchestrator | Set to 'kubernetes' if present
|
|
54
|
+
GCP_PROJECT | cloud.account.id | GCP project ID
|
|
55
|
+
CLOUD_PROVIDER | cloud.provider | e.g. 'gcp', 'aws', etc.
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
### Logging
|
|
60
|
+
|
|
61
|
+
The logger automatically includes `trace_id` and `span_id` if available.
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import { getLogger } from '@sebspark/otel'
|
|
65
|
+
|
|
66
|
+
const logger = getLogger()
|
|
67
|
+
|
|
68
|
+
logger.debug('message')
|
|
69
|
+
logger.info('message')
|
|
70
|
+
logger.warn('message')
|
|
71
|
+
logger.error('message')
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
### Metrics
|
|
77
|
+
|
|
78
|
+
You can use the metrics API to create and export custom application-level metrics.
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
import { getMeter } from '@sebspark/otel'
|
|
82
|
+
|
|
83
|
+
const meter = getMeter()
|
|
84
|
+
|
|
85
|
+
const counter = meter.createCounter('http_requests_total', {
|
|
86
|
+
description: 'Total number of HTTP requests'
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
counter.add(1, {
|
|
90
|
+
route: '/api/hello',
|
|
91
|
+
method: 'GET'
|
|
92
|
+
})
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
97
|
+
### Tracing
|
|
98
|
+
|
|
99
|
+
The tracer helps you capture **distributed traces** across services and automatically links logs with `trace_id` and `span_id` when called inside a span context.
|
|
100
|
+
|
|
101
|
+
#### Get a tracer
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
import { getTracer } from '@sebspark/otel'
|
|
105
|
+
|
|
106
|
+
const tracer = getTracer()
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Optionally override the service name:
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
const tracer = getTracer('my-custom-service')
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
#### Automatically wrap logic in a span
|
|
116
|
+
|
|
117
|
+
**Async**
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
await tracer.withTrace('trace name', async (span) => {
|
|
121
|
+
// span is active here
|
|
122
|
+
span.setAttribute('custom.attribute', 'value')
|
|
123
|
+
})
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
**Sync**
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
tracer.withTraceSync('init.config', () => {
|
|
130
|
+
// synchronous logic
|
|
131
|
+
})
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
**Errors**
|
|
135
|
+
|
|
136
|
+
If an error is thrown during an auto traced function:
|
|
137
|
+
|
|
138
|
+
- The span is marked with `SpanStatusCode.ERROR`
|
|
139
|
+
- The error is recorded via `span.recordException()`
|
|
140
|
+
- The span is always ended correctly
|
|
141
|
+
|
|
142
|
+
#### Manual control
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
const span = tracer.startSpan('manual-task')
|
|
146
|
+
span.setAttribute('manual', true)
|
|
147
|
+
// do work...
|
|
148
|
+
span.end()
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
#### Nested span attributes
|
|
152
|
+
|
|
153
|
+
Any span created via `withTrace` or `withTraceSync` will automatically inherit these attributes from the parent (if present):
|
|
154
|
+
|
|
155
|
+
- `parent_service_name`
|
|
156
|
+
- `parent_span_name`
|
|
157
|
+
|
|
158
|
+
This makes cross‑service tracing easier to follow in tools like **Google Cloud Trace**, **Jaeger** or **Grafana Tempo**.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import * as _opentelemetry_api from '@opentelemetry/api';
|
|
2
|
+
import { trace, SpanOptions } from '@opentelemetry/api';
|
|
3
|
+
|
|
4
|
+
type Attrs = Record<string, any>;
|
|
5
|
+
declare function getLogger(serviceOverride?: string, extraAttrs?: Attrs): {
|
|
6
|
+
debug: (msg: string, attrs?: Attrs) => void;
|
|
7
|
+
info: (msg: string, attrs?: Attrs) => void;
|
|
8
|
+
notice: (msg: string, attrs?: Attrs) => void;
|
|
9
|
+
warn: (msg: string, attrs?: Attrs) => void;
|
|
10
|
+
error: (msg: string | Error, attrs?: Attrs) => void;
|
|
11
|
+
critical: (msg: string, attrs?: Attrs) => void;
|
|
12
|
+
alert: (msg: string, attrs?: Attrs) => void;
|
|
13
|
+
emergency: (msg: string, attrs?: Attrs) => void;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
declare function getMeter(serviceOverride?: string): _opentelemetry_api.Meter;
|
|
17
|
+
|
|
18
|
+
type OtelTracer = ReturnType<typeof trace.getTracer>;
|
|
19
|
+
type Span = ReturnType<OtelTracer['startSpan']>;
|
|
20
|
+
type Func<T> = (span?: Span) => Promise<T> | T;
|
|
21
|
+
type SyncFunc<T> = (span?: Span) => T;
|
|
22
|
+
type WithTrace = {
|
|
23
|
+
<T>(name: string, fn: Func<T>): Promise<T>;
|
|
24
|
+
<T>(name: string, options: SpanOptions, fn: Func<T>): Promise<T>;
|
|
25
|
+
};
|
|
26
|
+
type WithTraceSync = {
|
|
27
|
+
<T>(name: string, fn: SyncFunc<T>): T;
|
|
28
|
+
<T>(name: string, options: SpanOptions, fn: SyncFunc<T>): T;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Extended tracer with helper methods for span-wrapped execution
|
|
32
|
+
*/
|
|
33
|
+
interface Tracer extends OtelTracer {
|
|
34
|
+
withTrace: WithTrace;
|
|
35
|
+
withTraceSync: WithTraceSync;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Returns an OpenTelemetry tracer bound to the current service.
|
|
39
|
+
* Includes `withTrace()` and `withTraceSync()` helpers for span-wrapped execution.
|
|
40
|
+
*
|
|
41
|
+
* @param serviceOverride - Optional override for service name
|
|
42
|
+
* @returns Tracer with helpers
|
|
43
|
+
*/
|
|
44
|
+
declare function getTracer(serviceOverride?: string): Tracer;
|
|
45
|
+
|
|
46
|
+
export { getLogger, getMeter, getTracer };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import * as _opentelemetry_api from '@opentelemetry/api';
|
|
2
|
+
import { trace, SpanOptions } from '@opentelemetry/api';
|
|
3
|
+
|
|
4
|
+
type Attrs = Record<string, any>;
|
|
5
|
+
declare function getLogger(serviceOverride?: string, extraAttrs?: Attrs): {
|
|
6
|
+
debug: (msg: string, attrs?: Attrs) => void;
|
|
7
|
+
info: (msg: string, attrs?: Attrs) => void;
|
|
8
|
+
notice: (msg: string, attrs?: Attrs) => void;
|
|
9
|
+
warn: (msg: string, attrs?: Attrs) => void;
|
|
10
|
+
error: (msg: string | Error, attrs?: Attrs) => void;
|
|
11
|
+
critical: (msg: string, attrs?: Attrs) => void;
|
|
12
|
+
alert: (msg: string, attrs?: Attrs) => void;
|
|
13
|
+
emergency: (msg: string, attrs?: Attrs) => void;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
declare function getMeter(serviceOverride?: string): _opentelemetry_api.Meter;
|
|
17
|
+
|
|
18
|
+
type OtelTracer = ReturnType<typeof trace.getTracer>;
|
|
19
|
+
type Span = ReturnType<OtelTracer['startSpan']>;
|
|
20
|
+
type Func<T> = (span?: Span) => Promise<T> | T;
|
|
21
|
+
type SyncFunc<T> = (span?: Span) => T;
|
|
22
|
+
type WithTrace = {
|
|
23
|
+
<T>(name: string, fn: Func<T>): Promise<T>;
|
|
24
|
+
<T>(name: string, options: SpanOptions, fn: Func<T>): Promise<T>;
|
|
25
|
+
};
|
|
26
|
+
type WithTraceSync = {
|
|
27
|
+
<T>(name: string, fn: SyncFunc<T>): T;
|
|
28
|
+
<T>(name: string, options: SpanOptions, fn: SyncFunc<T>): T;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Extended tracer with helper methods for span-wrapped execution
|
|
32
|
+
*/
|
|
33
|
+
interface Tracer extends OtelTracer {
|
|
34
|
+
withTrace: WithTrace;
|
|
35
|
+
withTraceSync: WithTraceSync;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Returns an OpenTelemetry tracer bound to the current service.
|
|
39
|
+
* Includes `withTrace()` and `withTraceSync()` helpers for span-wrapped execution.
|
|
40
|
+
*
|
|
41
|
+
* @param serviceOverride - Optional override for service name
|
|
42
|
+
* @returns Tracer with helpers
|
|
43
|
+
*/
|
|
44
|
+
declare function getTracer(serviceOverride?: string): Tracer;
|
|
45
|
+
|
|
46
|
+
export { getLogger, getMeter, getTracer };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
getLogger: () => getLogger,
|
|
24
|
+
getMeter: () => getMeter,
|
|
25
|
+
getTracer: () => getTracer
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(index_exports);
|
|
28
|
+
|
|
29
|
+
// src/otel.ts
|
|
30
|
+
var import_api = require("@opentelemetry/api");
|
|
31
|
+
var import_api_logs = require("@opentelemetry/api-logs");
|
|
32
|
+
var import_auto_instrumentations_node = require("@opentelemetry/auto-instrumentations-node");
|
|
33
|
+
var import_exporter_logs_otlp_http = require("@opentelemetry/exporter-logs-otlp-http");
|
|
34
|
+
var import_exporter_metrics_otlp_http = require("@opentelemetry/exporter-metrics-otlp-http");
|
|
35
|
+
var import_exporter_trace_otlp_http = require("@opentelemetry/exporter-trace-otlp-http");
|
|
36
|
+
var import_resources = require("@opentelemetry/resources");
|
|
37
|
+
var import_sdk_logs = require("@opentelemetry/sdk-logs");
|
|
38
|
+
var import_sdk_metrics = require("@opentelemetry/sdk-metrics");
|
|
39
|
+
var import_sdk_node = require("@opentelemetry/sdk-node");
|
|
40
|
+
var import_semantic_conventions = require("@opentelemetry/semantic-conventions");
|
|
41
|
+
import_api.diag.setLogger(new import_api.DiagConsoleLogger(), import_api.DiagLogLevel.ERROR);
|
|
42
|
+
var serviceName = process.env.OTEL_SERVICE_NAME ?? "unknown-service";
|
|
43
|
+
var otlpEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT ?? "http://localhost:4318";
|
|
44
|
+
var traceExporter = new import_exporter_trace_otlp_http.OTLPTraceExporter({
|
|
45
|
+
url: `${otlpEndpoint}/v1/traces`
|
|
46
|
+
});
|
|
47
|
+
var metricExporter = new import_exporter_metrics_otlp_http.OTLPMetricExporter({
|
|
48
|
+
url: `${otlpEndpoint}/v1/metrics`
|
|
49
|
+
});
|
|
50
|
+
var logExporter = new import_exporter_logs_otlp_http.OTLPLogExporter({ url: `${otlpEndpoint}/v1/logs` });
|
|
51
|
+
var metricReader = new import_sdk_metrics.PeriodicExportingMetricReader({
|
|
52
|
+
exporter: metricExporter
|
|
53
|
+
});
|
|
54
|
+
async function initialize() {
|
|
55
|
+
try {
|
|
56
|
+
const baseRes = await (0, import_resources.detectResources)();
|
|
57
|
+
const customRes = (0, import_resources.resourceFromAttributes)({
|
|
58
|
+
[import_semantic_conventions.ATTR_SERVICE_NAME]: serviceName,
|
|
59
|
+
[import_semantic_conventions.ATTR_SERVICE_VERSION]: "1.0.0"
|
|
60
|
+
});
|
|
61
|
+
const resource = baseRes.merge(customRes);
|
|
62
|
+
const logProvider = new import_sdk_logs.LoggerProvider({
|
|
63
|
+
resource,
|
|
64
|
+
processors: [new import_sdk_logs.BatchLogRecordProcessor(logExporter)]
|
|
65
|
+
});
|
|
66
|
+
import_api_logs.logs.setGlobalLoggerProvider(logProvider);
|
|
67
|
+
const sdk = new import_sdk_node.NodeSDK({
|
|
68
|
+
traceExporter,
|
|
69
|
+
metricReader,
|
|
70
|
+
instrumentations: [(0, import_auto_instrumentations_node.getNodeAutoInstrumentations)()],
|
|
71
|
+
resource
|
|
72
|
+
});
|
|
73
|
+
await sdk.start();
|
|
74
|
+
console.log(`[otel] Telemetry initialized for "${serviceName}"`);
|
|
75
|
+
process.on("SIGTERM", async () => {
|
|
76
|
+
console.log("[otel] Shutting down...");
|
|
77
|
+
await Promise.all([sdk.shutdown(), logProvider.shutdown()]);
|
|
78
|
+
console.log("[otel] Shutdown complete.");
|
|
79
|
+
process.exit(0);
|
|
80
|
+
});
|
|
81
|
+
} catch (err) {
|
|
82
|
+
console.error("[otel] Startup error:", err);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
initialize();
|
|
86
|
+
|
|
87
|
+
// src/logger.ts
|
|
88
|
+
var import_api2 = require("@opentelemetry/api");
|
|
89
|
+
var import_api_logs2 = require("@opentelemetry/api-logs");
|
|
90
|
+
|
|
91
|
+
// src/otel-context.ts
|
|
92
|
+
function detectTelemetryContext(serviceOverride) {
|
|
93
|
+
const {
|
|
94
|
+
OTEL_SERVICE_NAME,
|
|
95
|
+
OTEL_SERVICE_VERSION,
|
|
96
|
+
K_SERVICE,
|
|
97
|
+
K_REVISION,
|
|
98
|
+
K_CONFIGURATION,
|
|
99
|
+
KUBERNETES_SERVICE_HOST,
|
|
100
|
+
POD_NAME,
|
|
101
|
+
POD_NAMESPACE,
|
|
102
|
+
GCP_PROJECT,
|
|
103
|
+
CLOUD_PROVIDER
|
|
104
|
+
} = process.env;
|
|
105
|
+
const serviceName2 = serviceOverride || OTEL_SERVICE_NAME || "unknown-service";
|
|
106
|
+
const serviceVersion = OTEL_SERVICE_VERSION || "1.0.0";
|
|
107
|
+
const resourceAttributes = {
|
|
108
|
+
"service.name": serviceName2,
|
|
109
|
+
"service.version": serviceVersion,
|
|
110
|
+
"serviceContext.service": serviceName2,
|
|
111
|
+
"serviceContext.version": serviceVersion,
|
|
112
|
+
...K_SERVICE && { "cloud.run.service": K_SERVICE },
|
|
113
|
+
...K_REVISION && { "cloud.run.revision": K_REVISION },
|
|
114
|
+
...K_CONFIGURATION && { "cloud.run.configuration": K_CONFIGURATION },
|
|
115
|
+
...POD_NAME && { "k8s.pod_name": POD_NAME },
|
|
116
|
+
...POD_NAMESPACE && { "k8s.namespace_name": POD_NAMESPACE },
|
|
117
|
+
...KUBERNETES_SERVICE_HOST && { "cloud.orchestrator": "kubernetes" },
|
|
118
|
+
...GCP_PROJECT && { "cloud.account.id": GCP_PROJECT },
|
|
119
|
+
...CLOUD_PROVIDER && { "cloud.provider": CLOUD_PROVIDER }
|
|
120
|
+
};
|
|
121
|
+
return {
|
|
122
|
+
serviceName: serviceName2,
|
|
123
|
+
serviceVersion,
|
|
124
|
+
resourceAttributes
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// src/logger.ts
|
|
129
|
+
function getLogger(serviceOverride, extraAttrs = {}) {
|
|
130
|
+
const { serviceName: serviceName2, serviceVersion, resourceAttributes } = detectTelemetryContext(serviceOverride);
|
|
131
|
+
const logger = import_api_logs2.logs.getLogger(serviceName2, serviceVersion, {});
|
|
132
|
+
const defaultAttrs = {
|
|
133
|
+
...resourceAttributes,
|
|
134
|
+
...extraAttrs
|
|
135
|
+
};
|
|
136
|
+
function emit(severityText, body, attrs = {}) {
|
|
137
|
+
const span = import_api2.trace.getSpan(import_api2.context.active());
|
|
138
|
+
const spanContext = span?.spanContext();
|
|
139
|
+
logger.emit({
|
|
140
|
+
severityText,
|
|
141
|
+
body,
|
|
142
|
+
attributes: {
|
|
143
|
+
...defaultAttrs,
|
|
144
|
+
...spanContext && {
|
|
145
|
+
trace_id: spanContext.traceId,
|
|
146
|
+
span_id: spanContext.spanId
|
|
147
|
+
},
|
|
148
|
+
...attrs
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
return {
|
|
153
|
+
debug: (msg, attrs) => emit("DEBUG", msg, attrs),
|
|
154
|
+
info: (msg, attrs) => emit("INFO", msg, attrs),
|
|
155
|
+
notice: (msg, attrs) => emit("NOTICE", msg, attrs),
|
|
156
|
+
warn: (msg, attrs) => emit("WARNING", msg, attrs),
|
|
157
|
+
error: (msg, attrs = {}) => {
|
|
158
|
+
const body = msg instanceof Error ? msg.stack || msg.message : msg;
|
|
159
|
+
emit("ERROR", body, attrs);
|
|
160
|
+
},
|
|
161
|
+
critical: (msg, attrs) => emit("CRITICAL", msg, attrs),
|
|
162
|
+
alert: (msg, attrs) => emit("ALERT", msg, attrs),
|
|
163
|
+
emergency: (msg, attrs) => emit("EMERGENCY", msg, attrs)
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// src/metrics.ts
|
|
168
|
+
var import_api3 = require("@opentelemetry/api");
|
|
169
|
+
function getMeter(serviceOverride) {
|
|
170
|
+
const { serviceName: serviceName2 } = detectTelemetryContext(serviceOverride);
|
|
171
|
+
return import_api3.metrics.getMeter(serviceName2);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// src/tracer.ts
|
|
175
|
+
var import_api4 = require("@opentelemetry/api");
|
|
176
|
+
function getTracer(serviceOverride) {
|
|
177
|
+
const { serviceName: serviceName2 } = detectTelemetryContext(serviceOverride);
|
|
178
|
+
const tracer = import_api4.trace.getTracer(serviceName2);
|
|
179
|
+
const withTrace = async (name, optionsOrFn, maybeFn) => {
|
|
180
|
+
const options = typeof maybeFn === "function" ? optionsOrFn : {};
|
|
181
|
+
const fn = typeof maybeFn === "function" ? maybeFn : optionsOrFn;
|
|
182
|
+
const ctx = import_api4.context.active();
|
|
183
|
+
const span = tracer.startSpan(name, options, ctx);
|
|
184
|
+
return await import_api4.context.with(import_api4.trace.setSpan(ctx, span), async () => {
|
|
185
|
+
try {
|
|
186
|
+
const result = await fn(span);
|
|
187
|
+
span.setStatus({ code: import_api4.SpanStatusCode.OK });
|
|
188
|
+
return result;
|
|
189
|
+
} catch (err) {
|
|
190
|
+
const error = err;
|
|
191
|
+
span.setStatus({ code: import_api4.SpanStatusCode.ERROR, message: error.message });
|
|
192
|
+
span.recordException?.(error);
|
|
193
|
+
throw err;
|
|
194
|
+
} finally {
|
|
195
|
+
span.end();
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
};
|
|
199
|
+
const withTraceSync = (name, optionsOrFn, maybeFn) => {
|
|
200
|
+
const options = typeof maybeFn === "function" ? optionsOrFn : {};
|
|
201
|
+
const fn = typeof maybeFn === "function" ? maybeFn : optionsOrFn;
|
|
202
|
+
const ctx = import_api4.context.active();
|
|
203
|
+
const span = tracer.startSpan(name, options, ctx);
|
|
204
|
+
return import_api4.context.with(import_api4.trace.setSpan(ctx, span), () => {
|
|
205
|
+
try {
|
|
206
|
+
const result = fn(span);
|
|
207
|
+
span.setStatus({ code: import_api4.SpanStatusCode.OK });
|
|
208
|
+
return result;
|
|
209
|
+
} catch (err) {
|
|
210
|
+
const error = err;
|
|
211
|
+
span.setStatus({ code: import_api4.SpanStatusCode.ERROR, message: error.message });
|
|
212
|
+
span.recordException?.(error);
|
|
213
|
+
throw err;
|
|
214
|
+
} finally {
|
|
215
|
+
span.end();
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
};
|
|
219
|
+
tracer.withTrace = withTrace;
|
|
220
|
+
tracer.withTraceSync = withTraceSync;
|
|
221
|
+
return tracer;
|
|
222
|
+
}
|
|
223
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
224
|
+
0 && (module.exports = {
|
|
225
|
+
getLogger,
|
|
226
|
+
getMeter,
|
|
227
|
+
getTracer
|
|
228
|
+
});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
// src/otel.ts
|
|
2
|
+
import { DiagConsoleLogger, DiagLogLevel, diag } from "@opentelemetry/api";
|
|
3
|
+
import { logs } from "@opentelemetry/api-logs";
|
|
4
|
+
import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";
|
|
5
|
+
import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
|
|
6
|
+
import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
|
|
7
|
+
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
|
|
8
|
+
import {
|
|
9
|
+
detectResources,
|
|
10
|
+
resourceFromAttributes
|
|
11
|
+
} from "@opentelemetry/resources";
|
|
12
|
+
import {
|
|
13
|
+
BatchLogRecordProcessor,
|
|
14
|
+
LoggerProvider
|
|
15
|
+
} from "@opentelemetry/sdk-logs";
|
|
16
|
+
import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
|
|
17
|
+
import { NodeSDK } from "@opentelemetry/sdk-node";
|
|
18
|
+
import {
|
|
19
|
+
ATTR_SERVICE_NAME,
|
|
20
|
+
ATTR_SERVICE_VERSION
|
|
21
|
+
} from "@opentelemetry/semantic-conventions";
|
|
22
|
+
diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.ERROR);
|
|
23
|
+
var serviceName = process.env.OTEL_SERVICE_NAME ?? "unknown-service";
|
|
24
|
+
var otlpEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT ?? "http://localhost:4318";
|
|
25
|
+
var traceExporter = new OTLPTraceExporter({
|
|
26
|
+
url: `${otlpEndpoint}/v1/traces`
|
|
27
|
+
});
|
|
28
|
+
var metricExporter = new OTLPMetricExporter({
|
|
29
|
+
url: `${otlpEndpoint}/v1/metrics`
|
|
30
|
+
});
|
|
31
|
+
var logExporter = new OTLPLogExporter({ url: `${otlpEndpoint}/v1/logs` });
|
|
32
|
+
var metricReader = new PeriodicExportingMetricReader({
|
|
33
|
+
exporter: metricExporter
|
|
34
|
+
});
|
|
35
|
+
async function initialize() {
|
|
36
|
+
try {
|
|
37
|
+
const baseRes = await detectResources();
|
|
38
|
+
const customRes = resourceFromAttributes({
|
|
39
|
+
[ATTR_SERVICE_NAME]: serviceName,
|
|
40
|
+
[ATTR_SERVICE_VERSION]: "1.0.0"
|
|
41
|
+
});
|
|
42
|
+
const resource = baseRes.merge(customRes);
|
|
43
|
+
const logProvider = new LoggerProvider({
|
|
44
|
+
resource,
|
|
45
|
+
processors: [new BatchLogRecordProcessor(logExporter)]
|
|
46
|
+
});
|
|
47
|
+
logs.setGlobalLoggerProvider(logProvider);
|
|
48
|
+
const sdk = new NodeSDK({
|
|
49
|
+
traceExporter,
|
|
50
|
+
metricReader,
|
|
51
|
+
instrumentations: [getNodeAutoInstrumentations()],
|
|
52
|
+
resource
|
|
53
|
+
});
|
|
54
|
+
await sdk.start();
|
|
55
|
+
console.log(`[otel] Telemetry initialized for "${serviceName}"`);
|
|
56
|
+
process.on("SIGTERM", async () => {
|
|
57
|
+
console.log("[otel] Shutting down...");
|
|
58
|
+
await Promise.all([sdk.shutdown(), logProvider.shutdown()]);
|
|
59
|
+
console.log("[otel] Shutdown complete.");
|
|
60
|
+
process.exit(0);
|
|
61
|
+
});
|
|
62
|
+
} catch (err) {
|
|
63
|
+
console.error("[otel] Startup error:", err);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
initialize();
|
|
67
|
+
|
|
68
|
+
// src/logger.ts
|
|
69
|
+
import { context, trace } from "@opentelemetry/api";
|
|
70
|
+
import { logs as logs2 } from "@opentelemetry/api-logs";
|
|
71
|
+
|
|
72
|
+
// src/otel-context.ts
|
|
73
|
+
function detectTelemetryContext(serviceOverride) {
|
|
74
|
+
const {
|
|
75
|
+
OTEL_SERVICE_NAME,
|
|
76
|
+
OTEL_SERVICE_VERSION,
|
|
77
|
+
K_SERVICE,
|
|
78
|
+
K_REVISION,
|
|
79
|
+
K_CONFIGURATION,
|
|
80
|
+
KUBERNETES_SERVICE_HOST,
|
|
81
|
+
POD_NAME,
|
|
82
|
+
POD_NAMESPACE,
|
|
83
|
+
GCP_PROJECT,
|
|
84
|
+
CLOUD_PROVIDER
|
|
85
|
+
} = process.env;
|
|
86
|
+
const serviceName2 = serviceOverride || OTEL_SERVICE_NAME || "unknown-service";
|
|
87
|
+
const serviceVersion = OTEL_SERVICE_VERSION || "1.0.0";
|
|
88
|
+
const resourceAttributes = {
|
|
89
|
+
"service.name": serviceName2,
|
|
90
|
+
"service.version": serviceVersion,
|
|
91
|
+
"serviceContext.service": serviceName2,
|
|
92
|
+
"serviceContext.version": serviceVersion,
|
|
93
|
+
...K_SERVICE && { "cloud.run.service": K_SERVICE },
|
|
94
|
+
...K_REVISION && { "cloud.run.revision": K_REVISION },
|
|
95
|
+
...K_CONFIGURATION && { "cloud.run.configuration": K_CONFIGURATION },
|
|
96
|
+
...POD_NAME && { "k8s.pod_name": POD_NAME },
|
|
97
|
+
...POD_NAMESPACE && { "k8s.namespace_name": POD_NAMESPACE },
|
|
98
|
+
...KUBERNETES_SERVICE_HOST && { "cloud.orchestrator": "kubernetes" },
|
|
99
|
+
...GCP_PROJECT && { "cloud.account.id": GCP_PROJECT },
|
|
100
|
+
...CLOUD_PROVIDER && { "cloud.provider": CLOUD_PROVIDER }
|
|
101
|
+
};
|
|
102
|
+
return {
|
|
103
|
+
serviceName: serviceName2,
|
|
104
|
+
serviceVersion,
|
|
105
|
+
resourceAttributes
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// src/logger.ts
|
|
110
|
+
function getLogger(serviceOverride, extraAttrs = {}) {
|
|
111
|
+
const { serviceName: serviceName2, serviceVersion, resourceAttributes } = detectTelemetryContext(serviceOverride);
|
|
112
|
+
const logger = logs2.getLogger(serviceName2, serviceVersion, {});
|
|
113
|
+
const defaultAttrs = {
|
|
114
|
+
...resourceAttributes,
|
|
115
|
+
...extraAttrs
|
|
116
|
+
};
|
|
117
|
+
function emit(severityText, body, attrs = {}) {
|
|
118
|
+
const span = trace.getSpan(context.active());
|
|
119
|
+
const spanContext = span?.spanContext();
|
|
120
|
+
logger.emit({
|
|
121
|
+
severityText,
|
|
122
|
+
body,
|
|
123
|
+
attributes: {
|
|
124
|
+
...defaultAttrs,
|
|
125
|
+
...spanContext && {
|
|
126
|
+
trace_id: spanContext.traceId,
|
|
127
|
+
span_id: spanContext.spanId
|
|
128
|
+
},
|
|
129
|
+
...attrs
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
return {
|
|
134
|
+
debug: (msg, attrs) => emit("DEBUG", msg, attrs),
|
|
135
|
+
info: (msg, attrs) => emit("INFO", msg, attrs),
|
|
136
|
+
notice: (msg, attrs) => emit("NOTICE", msg, attrs),
|
|
137
|
+
warn: (msg, attrs) => emit("WARNING", msg, attrs),
|
|
138
|
+
error: (msg, attrs = {}) => {
|
|
139
|
+
const body = msg instanceof Error ? msg.stack || msg.message : msg;
|
|
140
|
+
emit("ERROR", body, attrs);
|
|
141
|
+
},
|
|
142
|
+
critical: (msg, attrs) => emit("CRITICAL", msg, attrs),
|
|
143
|
+
alert: (msg, attrs) => emit("ALERT", msg, attrs),
|
|
144
|
+
emergency: (msg, attrs) => emit("EMERGENCY", msg, attrs)
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// src/metrics.ts
|
|
149
|
+
import { metrics } from "@opentelemetry/api";
|
|
150
|
+
function getMeter(serviceOverride) {
|
|
151
|
+
const { serviceName: serviceName2 } = detectTelemetryContext(serviceOverride);
|
|
152
|
+
return metrics.getMeter(serviceName2);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// src/tracer.ts
|
|
156
|
+
import {
|
|
157
|
+
context as context2,
|
|
158
|
+
SpanStatusCode,
|
|
159
|
+
trace as trace2
|
|
160
|
+
} from "@opentelemetry/api";
|
|
161
|
+
function getTracer(serviceOverride) {
|
|
162
|
+
const { serviceName: serviceName2 } = detectTelemetryContext(serviceOverride);
|
|
163
|
+
const tracer = trace2.getTracer(serviceName2);
|
|
164
|
+
const withTrace = async (name, optionsOrFn, maybeFn) => {
|
|
165
|
+
const options = typeof maybeFn === "function" ? optionsOrFn : {};
|
|
166
|
+
const fn = typeof maybeFn === "function" ? maybeFn : optionsOrFn;
|
|
167
|
+
const ctx = context2.active();
|
|
168
|
+
const span = tracer.startSpan(name, options, ctx);
|
|
169
|
+
return await context2.with(trace2.setSpan(ctx, span), async () => {
|
|
170
|
+
try {
|
|
171
|
+
const result = await fn(span);
|
|
172
|
+
span.setStatus({ code: SpanStatusCode.OK });
|
|
173
|
+
return result;
|
|
174
|
+
} catch (err) {
|
|
175
|
+
const error = err;
|
|
176
|
+
span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
|
|
177
|
+
span.recordException?.(error);
|
|
178
|
+
throw err;
|
|
179
|
+
} finally {
|
|
180
|
+
span.end();
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
};
|
|
184
|
+
const withTraceSync = (name, optionsOrFn, maybeFn) => {
|
|
185
|
+
const options = typeof maybeFn === "function" ? optionsOrFn : {};
|
|
186
|
+
const fn = typeof maybeFn === "function" ? maybeFn : optionsOrFn;
|
|
187
|
+
const ctx = context2.active();
|
|
188
|
+
const span = tracer.startSpan(name, options, ctx);
|
|
189
|
+
return context2.with(trace2.setSpan(ctx, span), () => {
|
|
190
|
+
try {
|
|
191
|
+
const result = fn(span);
|
|
192
|
+
span.setStatus({ code: SpanStatusCode.OK });
|
|
193
|
+
return result;
|
|
194
|
+
} catch (err) {
|
|
195
|
+
const error = err;
|
|
196
|
+
span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
|
|
197
|
+
span.recordException?.(error);
|
|
198
|
+
throw err;
|
|
199
|
+
} finally {
|
|
200
|
+
span.end();
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
};
|
|
204
|
+
tracer.withTrace = withTrace;
|
|
205
|
+
tracer.withTraceSync = withTraceSync;
|
|
206
|
+
return tracer;
|
|
207
|
+
}
|
|
208
|
+
export {
|
|
209
|
+
getLogger,
|
|
210
|
+
getMeter,
|
|
211
|
+
getTracer
|
|
212
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@sebspark/otel",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"module": "dist/index.mjs",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"files": [
|
|
9
|
+
"dist"
|
|
10
|
+
],
|
|
11
|
+
"scripts": {
|
|
12
|
+
"build": "tsup-node src/index.ts --format esm,cjs --dts",
|
|
13
|
+
"dev": "tsc --watch --noEmit",
|
|
14
|
+
"lint": "biome check .",
|
|
15
|
+
"test": "vitest run --passWithNoTests --coverage",
|
|
16
|
+
"typecheck": "vitest --typecheck.only --passWithNoTests"
|
|
17
|
+
},
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"@opentelemetry/api": "1.9.0",
|
|
20
|
+
"@opentelemetry/api-logs": "0.206.0",
|
|
21
|
+
"@opentelemetry/auto-instrumentations-node": "0.65.0",
|
|
22
|
+
"@opentelemetry/exporter-logs-otlp-http": "0.206.0",
|
|
23
|
+
"@opentelemetry/exporter-metrics-otlp-http": "0.206.0",
|
|
24
|
+
"@opentelemetry/exporter-trace-otlp-http": "0.206.0",
|
|
25
|
+
"@opentelemetry/resources": "2.1.0",
|
|
26
|
+
"@opentelemetry/sdk-logs": "0.206.0",
|
|
27
|
+
"@opentelemetry/sdk-metrics": "2.1.0",
|
|
28
|
+
"@opentelemetry/sdk-node": "0.206.0",
|
|
29
|
+
"@opentelemetry/sdk-trace-node": "2.1.0",
|
|
30
|
+
"@opentelemetry/semantic-conventions": "1.37.0"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@opentelemetry/context-async-hooks": "2.1.0",
|
|
34
|
+
"tsconfig": "*"
|
|
35
|
+
}
|
|
36
|
+
}
|