@onelog-sdk/node 0.1.2 → 0.1.4
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/README.md +26 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +16 -2
- package/dist/index.d.ts +16 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -40,11 +40,37 @@ sdkStartPromise.finally(() => {
|
|
|
40
40
|
});
|
|
41
41
|
```
|
|
42
42
|
|
|
43
|
+
### Dynamic attributes at runtime
|
|
44
|
+
Set attributes without restarting—globally or per request—and they’ll show up in spans, logs, HTTP call logs, and error responses.
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
import {
|
|
48
|
+
setGlobalAttributes,
|
|
49
|
+
setRequestAttributes,
|
|
50
|
+
withRequestAttributes,
|
|
51
|
+
} from '@onelog/node';
|
|
52
|
+
|
|
53
|
+
// Global attributes (applied to all spans/logs going forward)
|
|
54
|
+
setGlobalAttributes({ version: '1.2.3', cluster: 'blue' });
|
|
55
|
+
|
|
56
|
+
// Per-request attributes (inside middleware/handlers)
|
|
57
|
+
app.use((req, _res, next) => {
|
|
58
|
+
setRequestAttributes({ userId: req.get('x-user-id') });
|
|
59
|
+
next();
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
// Or wrap a block with temporary attributes
|
|
63
|
+
await withRequestAttributes({ tenant: 'acme' }, async () => {
|
|
64
|
+
// logs and spans inside here carry tenant=acme
|
|
65
|
+
});
|
|
66
|
+
```
|
|
67
|
+
|
|
43
68
|
## What’s inside
|
|
44
69
|
- **Tracing** (`sdkStartPromise`, `instrumentApp`) — boots OpenTelemetry Node SDK with HTTP/Express/undici auto-instrumentation and renames spans to `[module] METHOD /path` while adding `module.name`.
|
|
45
70
|
- **Logging** (`createLogger`) — Pino with dual transports: OTLP-friendly output plus pretty console, pre-tagged with env/app/module.
|
|
46
71
|
- **Exceptions** (`errorMiddleware`) — records exceptions on the active span, sets span status to ERROR, logs details, and returns JSON.
|
|
47
72
|
- **HTTP calls** (`httpCall`) — fetch wrapper with consistent logging, JSON handling, and error propagation.
|
|
73
|
+
- **Runtime attributes** (`setGlobalAttributes`, `setRequestAttributes`) — update attributes on the fly (globally or per request) and they flow into spans, logs, outbound calls, and error responses.
|
|
48
74
|
|
|
49
75
|
## Environment variables
|
|
50
76
|
- `PORT` — HTTP port for your service.
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var w=Object.create;var c=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var C=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty;var H=(e,t)=>{for(var o in t)c(e,o,{get:t[o],enumerable:!0})},v=(e,t,o,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of I(t))!D.call(e,n)&&n!==o&&c(e,n,{get:()=>t[n],enumerable:!(r=M(t,n))||r.enumerable});return e};var k=(e,t,o)=>(o=e!=null?w(C(e)):{},v(t||!e||!e.__esModule?c(o,"default",{value:e,enumerable:!0}):o,e)),$=e=>v(c({},"__esModule",{value:!0}),e);var J={};H(J,{createLogger:()=>b,errorMiddleware:()=>O,httpCall:()=>R,instrumentApp:()=>S,sdkStartPromise:()=>x});module.exports=$(J);var i=require("@opentelemetry/api"),E=require("@opentelemetry/sdk-node"),y=require("@opentelemetry/resources"),N=require("@opentelemetry/exporter-trace-otlp-http"),g=require("@opentelemetry/auto-instrumentations-node"),m=require("undici");i.diag.setLogger(new i.DiagConsoleLogger,i.DiagLogLevel.WARN);var F=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",U=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",q=process.env.MAIN_ENV||process.env.NODE_ENV||"development",T=process.env.MAIN_MODULE||"unknown-module",G=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),V=(process.env.ONELOG_EXPRESS_LAYERS||"").toLowerCase()==="true",A=process.env.MAIN_MODULE||T,f=[process.env.HTTPS_PROXY,process.env.https_proxy,process.env.HTTP_PROXY,process.env.http_proxy].find(e=>e&&e.trim().length>0);if(f)try{(0,m.setGlobalDispatcher)(new m.ProxyAgent(f)),console.log(`[onelog] Proxy enabled for outbound traffic: ${f}`)}catch(e){console.error("[onelog] Failed to configure proxy agent:",e.message)}var j=y.Resource.default().merge(new y.Resource({"service.name":F,"service.namespace":U,"deployment.environment":q,"module.name":A})),h=class{constructor(t){this.moduleName=t}onStart(t){if(!t)return;let o=t.name||t._name||"";this.moduleName&&!o.startsWith(`[${this.moduleName}] `)&&t.updateName(`[${this.moduleName}] ${o}`),this.moduleName&&t.setAttribute("module.name",this.moduleName)}onEnd(t){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}},X=(0,g.getNodeAutoInstrumentations)({"@opentelemetry/instrumentation-http":{enabled:!0},"@opentelemetry/instrumentation-express":{enabled:!0,ignoreLayersType:V?[]:["middleware","request_handler"]},"@opentelemetry/instrumentation-undici":{enabled:!0},"@opentelemetry/instrumentation-ioredis":{enabled:!1},"@opentelemetry/instrumentation-redis":{enabled:!1},"@opentelemetry/instrumentation-fs":{enabled:!1},"@opentelemetry/instrumentation-dns":{enabled:!1},"@opentelemetry/instrumentation-net":{enabled:!1}}),P=new E.NodeSDK({traceExporter:new N.OTLPTraceExporter({url:`${G}/v1/traces`}),resource:j,instrumentations:[X],spanProcessor:new h(A)}),x=Promise.resolve(P.start()).catch(e=>(console.error("Failed to start OpenTelemetry SDK",e),Promise.resolve())),L=async()=>{try{await P.shutdown()}catch(e){console.error("Error shutting down OpenTelemetry SDK",e)}};process.on("SIGTERM",L);process.on("SIGINT",L);var S=(e,t,o)=>{let r=o||process.env.MAIN_MODULE||T;e.use((n,a,s)=>{let p=i.trace.getActiveSpan();p&&(p.setAttribute("module.name",r),p.updateName(`[${r}] ${n.method} ${n.path}`)),t&&t.info({method:n.method,path:n.path,ip:n.ip},"Incoming request"),s()})};var _=k(require("pino"),1);function b(){let e=process.env.MAIN_ENV||"development",t=process.env.MAIN_APP||"app",o=process.env.MAIN_MODULE||"unknown-module";return(0,_.default)({transport:{targets:[{target:"pino-opentelemetry-transport",level:"info",options:{resourceAttributes:{"service.name":t,"service.namespace":e,"deployment.environment":e,"module.name":o,"host.name":require("os").hostname()}}},{target:"pino-pretty",level:"debug",options:{colorize:!0,translateTime:"HH:MM:ss Z",ignore:"pid,hostname"}}]}}).child({env:e,app:t,module:o})}var l=require("@opentelemetry/api"),O=e=>(t,o,r,n)=>{e&&e.error({error:t.message,stack:t.stack,path:o.path},"Unhandled error");let a=l.trace.getActiveSpan();if(a&&(a.recordException(t),a.setStatus({code:l.SpanStatusCode.ERROR,message:t.message})),r.headersSent)return n(t);r.status(500).json({error:t.message,module:process.env.MAIN_MODULE||"unknown-module"})};async function R(e,t={},o,r={}){let n={...t},a=(n.method||"GET").toString().toUpperCase();n.body&&typeof n.body!="string"&&!(n.body instanceof Buffer)&&!(n.body instanceof ArrayBuffer)&&(n.body=JSON.stringify(n.body),n.headers={"Content-Type":"application/json",...n.headers||{}}),o&&o.info({...r,url:e,method:a},"HTTP call start");try{let s=await fetch(e,n),u=(s.headers.get("content-type")||"").includes("application/json")?await s.json().catch(()=>null):await s.text().catch(()=>null);if(!s.ok){let d=new Error(`HTTP ${s.status} ${s.statusText||""}`.trim());throw d.status=s.status,d.data=u,o&&o.error({...r,url:e,method:a,status:s.status,data:u},"HTTP call failed"),d}return o&&o.info({...r,url:e,method:a,status:s.status},"HTTP call success"),u}catch(s){throw o&&o.error({...r,url:e,method:a,error:s.message},"HTTP call error"),s}}0&&(module.exports={createLogger,errorMiddleware,httpCall,instrumentApp,sdkStartPromise});
|
|
1
|
+
"use strict";var ce=Object.create;var S=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var Oe=Object.getOwnPropertyNames;var fe=Object.getPrototypeOf,me=Object.prototype.hasOwnProperty;var Re=(e,t)=>{for(var r in t)S(e,r,{get:t[r],enumerable:!0})},F=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Oe(t))!me.call(e,n)&&n!==r&&S(e,n,{get:()=>t[n],enumerable:!(o=le(t,n))||o.enumerable});return e};var Le=(e,t,r)=>(r=e!=null?ce(fe(e)):{},F(t||!e||!e.__esModule?S(r,"default",{value:e,enumerable:!0}):r,e)),de=e=>F(S({},"__esModule",{value:!0}),e);var st={};Re(st,{createLogger:()=>Te,errorMiddleware:()=>pe,getGlobalAttributes:()=>E,getRequestAttributes:()=>_,httpCall:()=>ue,instrumentApp:()=>Ee,mergeGlobalAttributes:()=>$,mergeRequestAttributes:()=>J,runWithRequestContext:()=>A,sdkStartPromise:()=>ie,setGlobalAttributes:()=>Z,setRequestAttributes:()=>m,withRequestAttributes:()=>k});module.exports=de(st);var O=require("@opentelemetry/api"),ee=require("@opentelemetry/sdk-node");var V=require("@opentelemetry/api"),he=(0,V.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function b(e){return e.setValue(he,!0)}var K=require("@opentelemetry/api");function q(){return function(e){K.diag.error(Ae(e))}}function Ae(e){return typeof e=="string"?e:JSON.stringify(Pe(e))}function Pe(e){for(var t={},r=e;r!==null;)Object.getOwnPropertyNames(r).forEach(function(o){if(!t[o]){var n=r[o];n&&(t[o]=String(n))}}),r=Object.getPrototypeOf(r);return t}var Se=q();function I(e){try{Se(e)}catch{}}var c=require("@opentelemetry/api");var x;(function(e){e.AlwaysOff="always_off",e.AlwaysOn="always_on",e.ParentBasedAlwaysOff="parentbased_always_off",e.ParentBasedAlwaysOn="parentbased_always_on",e.ParentBasedTraceIdRatio="parentbased_traceidratio",e.TraceIdRatio="traceidratio"})(x||(x={}));var Ie=",",xe=["OTEL_SDK_DISABLED"];function Ne(e){return xe.indexOf(e)>-1}var ye=["OTEL_BSP_EXPORT_TIMEOUT","OTEL_BSP_MAX_EXPORT_BATCH_SIZE","OTEL_BSP_MAX_QUEUE_SIZE","OTEL_BSP_SCHEDULE_DELAY","OTEL_BLRP_EXPORT_TIMEOUT","OTEL_BLRP_MAX_EXPORT_BATCH_SIZE","OTEL_BLRP_MAX_QUEUE_SIZE","OTEL_BLRP_SCHEDULE_DELAY","OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_EVENT_COUNT_LIMIT","OTEL_SPAN_LINK_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","OTEL_EXPORTER_OTLP_TIMEOUT","OTEL_EXPORTER_OTLP_TRACES_TIMEOUT","OTEL_EXPORTER_OTLP_METRICS_TIMEOUT","OTEL_EXPORTER_OTLP_LOGS_TIMEOUT","OTEL_EXPORTER_JAEGER_AGENT_PORT"];function Ce(e){return ye.indexOf(e)>-1}var ge=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS","OTEL_SEMCONV_STABILITY_OPT_IN"];function ve(e){return ge.indexOf(e)>-1}var M=1/0,U=128,be=128,Me=128,B={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:c.DiagLogLevel.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:M,OTEL_ATTRIBUTE_COUNT_LIMIT:U,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:M,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:U,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:M,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:U,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:be,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:Me,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:x.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative",OTEL_SEMCONV_STABILITY_OPT_IN:[]};function Ue(e,t,r){if(!(typeof r[e]>"u")){var o=String(r[e]);t[e]=o.toLowerCase()==="true"}}function Be(e,t,r,o,n){if(o===void 0&&(o=-1/0),n===void 0&&(n=1/0),typeof r[e]<"u"){var s=Number(r[e]);isNaN(s)||(s<o?t[e]=o:s>n?t[e]=n:t[e]=s)}}function De(e,t,r,o){o===void 0&&(o=Ie);var n=r[e];typeof n=="string"&&(t[e]=n.split(o).map(function(s){return s.trim()}))}var we={ALL:c.DiagLogLevel.ALL,VERBOSE:c.DiagLogLevel.VERBOSE,DEBUG:c.DiagLogLevel.DEBUG,INFO:c.DiagLogLevel.INFO,WARN:c.DiagLogLevel.WARN,ERROR:c.DiagLogLevel.ERROR,NONE:c.DiagLogLevel.NONE};function Xe(e,t,r){var o=r[e];if(typeof o=="string"){var n=we[o.toUpperCase()];n!=null&&(t[e]=n)}}function z(e){var t={};for(var r in B){var o=r;switch(o){case"OTEL_LOG_LEVEL":Xe(o,t,e);break;default:if(Ne(o))Ue(o,t,e);else if(Ce(o))Be(o,t,e);else if(ve(o))De(o,t,e);else{var n=e[o];typeof n<"u"&&n!==null&&(t[o]=String(n))}}}return t}function R(){var e=z(process.env);return Object.assign({},B,e)}function L(e){e.unref()}var d;(function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"})(d||(d={}));var Y=(function(){function e(){var t=this;this._promise=new Promise(function(r,o){t._resolve=r,t._reject=o})}return Object.defineProperty(e.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),e.prototype.resolve=function(t){this._resolve(t)},e.prototype.reject=function(t){this._reject(t)},e})();var qe=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var o=r.call(e),n,s=[],a;try{for(;(t===void 0||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(i){a={error:i}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(a)throw a.error}}return s},ze=function(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,s;o<n;o++)(s||!(o in t))&&(s||(s=Array.prototype.slice.call(t,0,o)),s[o]=t[o]);return e.concat(s||Array.prototype.slice.call(t))},D=(function(){function e(t,r){this._callback=t,this._that=r,this._isCalled=!1,this._deferred=new Y}return Object.defineProperty(e.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),e.prototype.call=function(){for(var t,r=this,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];if(!this._isCalled){this._isCalled=!0;try{Promise.resolve((t=this._callback).call.apply(t,ze([this._that],qe(o),!1))).then(function(s){return r._deferred.resolve(s)},function(s){return r._deferred.reject(s)})}catch(s){this._deferred.reject(s)}}return this._deferred.promise},e})();var l=require("@opentelemetry/api");var W=(function(){function e(t,r){this._exporter=t,this._isExporting=!1,this._finishedSpans=[],this._droppedSpansCount=0;var o=R();this._maxExportBatchSize=typeof r?.maxExportBatchSize=="number"?r.maxExportBatchSize:o.OTEL_BSP_MAX_EXPORT_BATCH_SIZE,this._maxQueueSize=typeof r?.maxQueueSize=="number"?r.maxQueueSize:o.OTEL_BSP_MAX_QUEUE_SIZE,this._scheduledDelayMillis=typeof r?.scheduledDelayMillis=="number"?r.scheduledDelayMillis:o.OTEL_BSP_SCHEDULE_DELAY,this._exportTimeoutMillis=typeof r?.exportTimeoutMillis=="number"?r.exportTimeoutMillis:o.OTEL_BSP_EXPORT_TIMEOUT,this._shutdownOnce=new D(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(l.diag.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}return e.prototype.forceFlush=function(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()},e.prototype.onStart=function(t,r){},e.prototype.onEnd=function(t){this._shutdownOnce.isCalled||(t.spanContext().traceFlags&l.TraceFlags.SAMPLED)!==0&&this._addToBuffer(t)},e.prototype.shutdown=function(){return this._shutdownOnce.call()},e.prototype._shutdown=function(){var t=this;return Promise.resolve().then(function(){return t.onShutdown()}).then(function(){return t._flushAll()}).then(function(){return t._exporter.shutdown()})},e.prototype._addToBuffer=function(t){if(this._finishedSpans.length>=this._maxQueueSize){this._droppedSpansCount===0&&l.diag.debug("maxQueueSize reached, dropping spans"),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(l.diag.warn("Dropped "+this._droppedSpansCount+" spans because maxQueueSize reached"),this._droppedSpansCount=0),this._finishedSpans.push(t),this._maybeStartTimer()},e.prototype._flushAll=function(){var t=this;return new Promise(function(r,o){for(var n=[],s=Math.ceil(t._finishedSpans.length/t._maxExportBatchSize),a=0,i=s;a<i;a++)n.push(t._flushOneBatch());Promise.all(n).then(function(){r()}).catch(o)})},e.prototype._flushOneBatch=function(){var t=this;return this._clearTimer(),this._finishedSpans.length===0?Promise.resolve():new Promise(function(r,o){var n=setTimeout(function(){o(new Error("Timeout"))},t._exportTimeoutMillis);l.context.with(b(l.context.active()),function(){var s;t._finishedSpans.length<=t._maxExportBatchSize?(s=t._finishedSpans,t._finishedSpans=[]):s=t._finishedSpans.splice(0,t._maxExportBatchSize);for(var a=function(){return t._exporter.export(s,function(u){var v;clearTimeout(n),u.code===d.SUCCESS?r():o((v=u.error)!==null&&v!==void 0?v:new Error("BatchSpanProcessor: span export failed"))})},i=null,p=0,P=s.length;p<P;p++){var T=s[p];T.resource.asyncAttributesPending&&T.resource.waitForAsyncAttributes&&(i??(i=[]),i.push(T.resource.waitForAsyncAttributes()))}i===null?a():Promise.all(i).then(a,function(u){I(u),o(u)})})})},e.prototype._maybeStartTimer=function(){var t=this;if(!this._isExporting){var r=function(){t._isExporting=!0,t._flushOneBatch().finally(function(){t._isExporting=!1,t._finishedSpans.length>0&&(t._clearTimer(),t._maybeStartTimer())}).catch(function(o){t._isExporting=!1,I(o)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return r();this._timer===void 0&&(this._timer=setTimeout(function(){return r()},this._scheduledDelayMillis),L(this._timer))}},e.prototype._clearTimer=function(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)},e})();var je=(function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,n){o.__proto__=n}||function(o,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(o[s]=n[s])},e(t,r)};return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function o(){this.constructor=t}t.prototype=r===null?Object.create(r):(o.prototype=r.prototype,new o)}})(),h=(function(e){je(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.onShutdown=function(){},t})(W);var X=require("@opentelemetry/resources"),te=require("@opentelemetry/exporter-trace-otlp-http"),re=require("@opentelemetry/auto-instrumentations-node"),C=require("undici");var Q=require("async_hooks"),y=new Q.AsyncLocalStorage,N={},f=e=>({...e||{}}),E=()=>f(N),Z=e=>{N=f(e)},$=e=>{N={...N,...f(e)}},_=()=>y.getStore()?.requestAttributes||{},m=(e,t)=>{let r=y.getStore();if(!r)return;let o=t?.append===!1?f(e):{...r.requestAttributes,...f(e)};r.requestAttributes=o},J=e=>m(e),k=(e,t,r)=>y.getStore()?(m(e,r),t()):A(()=>t(),e),A=(e,t)=>y.run({requestAttributes:f(t)},e);O.diag.setLogger(new O.DiagConsoleLogger,O.DiagLogLevel.WARN);var We=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",Qe=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",Ze=process.env.MAIN_ENV||process.env.NODE_ENV||"development",oe=process.env.MAIN_MODULE||"unknown-module",$e=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),Je=(process.env.ONELOG_EXPRESS_LAYERS||"").toLowerCase()==="true",ne=process.env.MAIN_MODULE||oe,w=[process.env.HTTPS_PROXY,process.env.https_proxy,process.env.HTTP_PROXY,process.env.http_proxy].find(e=>e&&e.trim().length>0);if(w)try{(0,C.setGlobalDispatcher)(new C.ProxyAgent(w)),console.log(`[onelog] Proxy enabled for outbound traffic: ${w}`)}catch(e){console.error("[onelog] Failed to configure proxy agent:",e.message)}var ke=X.Resource.default().merge(new X.Resource({"service.name":We,"service.namespace":Qe,"deployment.environment":Ze,"module.name":ne})),G=class{constructor(t){this.moduleName=t}onStart(t){if(!t)return;let r=t.name||t._name||"";this.moduleName&&!r.startsWith(`[${this.moduleName}] `)&&t.updateName(`[${this.moduleName}] ${r}`),this.moduleName&&t.setAttribute("module.name",this.moduleName);let o={...E(),..._()};for(let[n,s]of Object.entries(o))s!==void 0&&t.setAttribute(n,s)}onEnd(t){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}},H=class{constructor(t){this.processors=t}onStart(t,r){for(let o of this.processors)o.onStart(t,r)}onEnd(t){for(let r of this.processors)r.onEnd(t)}shutdown(){return Promise.all(this.processors.map(t=>t.shutdown())).then(()=>{})}forceFlush(){return Promise.all(this.processors.map(t=>t.forceFlush())).then(()=>{})}},et=(0,re.getNodeAutoInstrumentations)({"@opentelemetry/instrumentation-http":{enabled:!0},"@opentelemetry/instrumentation-express":{enabled:!0,ignoreLayersType:Je?[]:["middleware","request_handler"]},"@opentelemetry/instrumentation-undici":{enabled:!0},"@opentelemetry/instrumentation-ioredis":{enabled:!1},"@opentelemetry/instrumentation-redis":{enabled:!1},"@opentelemetry/instrumentation-fs":{enabled:!1},"@opentelemetry/instrumentation-dns":{enabled:!1},"@opentelemetry/instrumentation-net":{enabled:!1}}),tt=new te.OTLPTraceExporter({url:`${$e}/v1/traces`}),rt=new H([new G(ne),new h(tt)]),se=new ee.NodeSDK({resource:ke,instrumentations:[et],spanProcessor:rt}),ie=Promise.resolve(se.start()).catch(e=>(console.error("Failed to start OpenTelemetry SDK",e),Promise.resolve())),ae=async()=>{try{await se.shutdown()}catch(e){console.error("Error shutting down OpenTelemetry SDK",e)}};process.on("SIGTERM",ae);process.on("SIGINT",ae);var Ee=(e,t,r)=>{let o=r||process.env.MAIN_MODULE||oe;e.use((n,s,a)=>{A(()=>{m({"module.name":o,"http.method":n.method,"http.target":n.path});let i=O.trace.getActiveSpan();if(i){i.setAttribute("module.name",o),i.updateName(`[${o}] ${n.method} ${n.path}`);let p={...E(),..._()};for(let[P,T]of Object.entries(p))T!==void 0&&i.setAttribute(P,T)}t&&t.info({method:n.method,path:n.path,ip:n.ip},"Incoming request"),a()})})};var _e=Le(require("pino"),1);var ot=["fatal","error","warn","info","debug","trace"],nt=e=>{let t=()=>({...E(),..._()});return new Proxy(e,{get(r,o,n){let s=Reflect.get(r,o,n);return typeof o=="string"&&ot.includes(o)&&typeof s=="function"?(a,...i)=>{let p=t();return a&&typeof a=="object"&&!Array.isArray(a)?s.call(r,{...p,...a},...i):s.call(r,{...p},a,...i)}:s}})};function Te(){let e=process.env.MAIN_ENV||"development",t=process.env.MAIN_APP||"app",r=process.env.MAIN_MODULE||"unknown-module",n=(0,_e.default)({transport:{targets:[{target:"pino-opentelemetry-transport",level:"info",options:{resourceAttributes:{"service.name":t,"service.namespace":e,"deployment.environment":e,"module.name":r,"host.name":require("os").hostname()}}},{target:"pino-pretty",level:"debug",options:{colorize:!0,translateTime:"HH:MM:ss Z",ignore:"pid,hostname"}}]}}).child({env:e,app:t,module:r});return nt(n)}var g=require("@opentelemetry/api");var pe=e=>(t,r,o,n)=>{let s={...E(),..._()};e&&e.error({...s,error:t.message,stack:t.stack,path:r.path},"Unhandled error");let a=g.trace.getActiveSpan();if(a&&(a.recordException(t),a.setStatus({code:g.SpanStatusCode.ERROR,message:t.message})),o.headersSent)return n(t);o.status(500).json({error:t.message,attributes:s,module:process.env.MAIN_MODULE||"unknown-module"})};async function ue(e,t={},r,o={}){let n={...t},s=(n.method||"GET").toString().toUpperCase();n.body&&typeof n.body!="string"&&!(n.body instanceof Buffer)&&!(n.body instanceof ArrayBuffer)&&(n.body=JSON.stringify(n.body),n.headers={"Content-Type":"application/json",...n.headers||{}});let a={...E(),..._(),...o};r&&r.info({...a,url:e,method:s},"HTTP call start");try{let i=await fetch(e,n),T=(i.headers.get("content-type")||"").includes("application/json")?await i.json().catch(()=>null):await i.text().catch(()=>null);if(!i.ok){let u=new Error(`HTTP ${i.status} ${i.statusText||""}`.trim());throw u.status=i.status,u.data=T,r&&r.error({...a,url:e,method:s,status:i.status,data:T},"HTTP call failed"),u}return r&&r.info({...a,url:e,method:s,status:i.status},"HTTP call success"),T}catch(i){throw r&&r.error({...a,url:e,method:s,error:i.message},"HTTP call error"),i}}0&&(module.exports={createLogger,errorMiddleware,getGlobalAttributes,getRequestAttributes,httpCall,instrumentApp,mergeGlobalAttributes,mergeRequestAttributes,runWithRequestContext,sdkStartPromise,setGlobalAttributes,setRequestAttributes,withRequestAttributes});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/tracing.ts","../src/logger.ts","../src/exceptions.ts","../src/http-caller.ts"],"sourcesContent":["export { sdkStartPromise, instrumentApp } from './tracing.js';\nexport { createLogger } from './logger.js';\nexport { errorMiddleware } from './exceptions.js';\nexport { httpCall } from './http-caller.js';\n","import { diag, DiagConsoleLogger, DiagLogLevel, trace, Span } from '@opentelemetry/api';\nimport { NodeSDK } from '@opentelemetry/sdk-node';\nimport { SpanProcessor, ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport { Resource } from '@opentelemetry/resources';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\nimport { ProxyAgent, setGlobalDispatcher } from 'undici';\nimport type { Application, Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\n\ndiag.setLogger(new DiagConsoleLogger(), DiagLogLevel.WARN);\n\nconst serviceName =\n process.env.OTEL_SERVICE_NAME ||\n process.env.MAIN_MODULE ||\n 'unknown-service';\nconst serviceNamespace =\n process.env.OTEL_NAMESPACE ||\n process.env.OTEL_SERVICE_NAMESPACE ||\n process.env.MAIN_APP ||\n 'app';\nconst environment = process.env.MAIN_ENV || process.env.NODE_ENV || 'development';\nconst moduleName = process.env.MAIN_MODULE || 'unknown-module';\nconst otlpEndpoint = (process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318').replace(/\\/$/, '');\nconst expressLayersEnabled = (process.env.ONELOG_EXPRESS_LAYERS || '').toLowerCase() === 'true';\nconst moduleLabel = process.env.MAIN_MODULE || moduleName;\n\n// Optional proxy support for environments with HTTP(S)_PROXY set\nconst proxyUrl = [process.env.HTTPS_PROXY, process.env.https_proxy, process.env.HTTP_PROXY, process.env.http_proxy]\n .find((v) => v && v.trim().length > 0);\n\nif (proxyUrl) {\n try {\n setGlobalDispatcher(new ProxyAgent(proxyUrl));\n // eslint-disable-next-line no-console\n console.log(`[onelog] Proxy enabled for outbound traffic: ${proxyUrl}`);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to configure proxy agent:', (err as Error).message);\n }\n}\n\nconst resource = Resource.default().merge(\n new Resource({\n 'service.name': serviceName,\n 'service.namespace': serviceNamespace,\n 'deployment.environment': environment,\n 'module.name': moduleLabel,\n }),\n);\n\nclass ModuleNameSpanProcessor implements SpanProcessor {\n constructor(private readonly moduleName: string) {}\n onStart(span: Span): void {\n if (!span) return;\n const currentName = (span as any).name || (span as any)._name || '';\n if (this.moduleName && !currentName.startsWith(`[${this.moduleName}] `)) {\n span.updateName(`[${this.moduleName}] ${currentName}`);\n }\n if (this.moduleName) {\n span.setAttribute('module.name', this.moduleName);\n }\n }\n onEnd(_span: ReadableSpan): void {\n // no-op\n }\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\nconst instrumentations = getNodeAutoInstrumentations({\n '@opentelemetry/instrumentation-http': {\n enabled: true,\n },\n '@opentelemetry/instrumentation-express': {\n enabled: true,\n ignoreLayersType: expressLayersEnabled ? [] : (['middleware', 'request_handler'] as any),\n },\n '@opentelemetry/instrumentation-undici': {\n enabled: true,\n },\n // Redis instrumentation is noisy in our workloads; keep it off by default\n '@opentelemetry/instrumentation-ioredis': { enabled: false },\n '@opentelemetry/instrumentation-redis': { enabled: false },\n '@opentelemetry/instrumentation-fs': { enabled: false },\n '@opentelemetry/instrumentation-dns': { enabled: false },\n '@opentelemetry/instrumentation-net': { enabled: false },\n});\n\nconst sdk = new NodeSDK({\n traceExporter: new OTLPTraceExporter({\n url: `${otlpEndpoint}/v1/traces`,\n }),\n resource,\n instrumentations: [instrumentations],\n spanProcessor: new ModuleNameSpanProcessor(moduleLabel),\n});\n\nexport const sdkStartPromise = Promise.resolve(sdk.start()).catch((error) => {\n console.error('Failed to start OpenTelemetry SDK', error);\n return Promise.resolve();\n});\n\nconst shutdown = async () => {\n try {\n await sdk.shutdown();\n } catch (error) {\n console.error('Error shutting down OpenTelemetry SDK', error);\n }\n};\n\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n\nexport const instrumentApp = (app: Application, logger?: Logger, customModuleName?: string) => {\n const moduleLabel = customModuleName || process.env.MAIN_MODULE || moduleName;\n app.use((req: Request, _res: Response, next: NextFunction) => {\n const span = trace.getActiveSpan();\n if (span) {\n span.setAttribute('module.name', moduleLabel);\n span.updateName(`[${moduleLabel}] ${req.method} ${req.path}`);\n }\n if (logger) {\n logger.info(\n {\n method: req.method,\n path: req.path,\n ip: req.ip,\n },\n 'Incoming request',\n );\n }\n next();\n });\n};\n","import pino from 'pino';\n\nexport function createLogger() {\n const mainEnv = process.env.MAIN_ENV || 'development';\n const mainApp = process.env.MAIN_APP || 'app';\n const mainModule = process.env.MAIN_MODULE || 'unknown-module';\n\n const logger = pino({\n transport: {\n targets: [\n {\n target: 'pino-opentelemetry-transport',\n level: 'info',\n options: {\n resourceAttributes: {\n 'service.name': mainApp,\n 'service.namespace': mainEnv,\n 'deployment.environment': mainEnv,\n 'module.name': mainModule,\n 'host.name': require('os').hostname(),\n },\n },\n },\n {\n target: 'pino-pretty',\n level: 'debug',\n options: {\n colorize: true,\n translateTime: 'HH:MM:ss Z',\n ignore: 'pid,hostname',\n },\n },\n ],\n },\n });\n\n return logger.child({\n env: mainEnv,\n app: mainApp,\n module: mainModule,\n });\n}\n","import { trace, SpanStatusCode } from '@opentelemetry/api';\nimport type { Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\n\nexport const errorMiddleware =\n (logger?: Logger) =>\n (err: Error, req: Request, res: Response, next: NextFunction) => {\n if (logger) {\n logger.error(\n {\n error: err.message,\n stack: err.stack,\n path: req.path,\n },\n 'Unhandled error',\n );\n }\n\n const span = trace.getActiveSpan();\n if (span) {\n span.recordException(err);\n span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });\n }\n\n if (res.headersSent) {\n return next(err);\n }\n\n res.status(500).json({\n error: err.message,\n module: process.env.MAIN_MODULE || 'unknown-module',\n });\n };\n","export interface HttpCallContext {\n [key: string]: any;\n}\n\nexport interface HttpCallOptions extends RequestInit {\n body?: any;\n}\n\nexport async function httpCall(\n url: string,\n options: HttpCallOptions = {},\n logger?: { info: Function; error: Function },\n logContext: HttpCallContext = {},\n) {\n const fetchOptions: RequestInit = { ...options };\n const method = (fetchOptions.method || 'GET').toString().toUpperCase();\n\n if (\n fetchOptions.body &&\n typeof fetchOptions.body !== 'string' &&\n !(fetchOptions.body instanceof Buffer) &&\n !(fetchOptions.body instanceof ArrayBuffer)\n ) {\n fetchOptions.body = JSON.stringify(fetchOptions.body);\n fetchOptions.headers = {\n 'Content-Type': 'application/json',\n ...(fetchOptions.headers || {}),\n };\n }\n\n if (logger) {\n logger.info({ ...logContext, url, method }, 'HTTP call start');\n }\n\n try {\n const res = await fetch(url, fetchOptions);\n const contentType = res.headers.get('content-type') || '';\n const isJson = contentType.includes('application/json');\n const data = isJson ? await res.json().catch(() => null) : await res.text().catch(() => null);\n\n if (!res.ok) {\n const error = new Error(`HTTP ${res.status} ${res.statusText || ''}`.trim());\n (error as any).status = res.status;\n (error as any).data = data;\n if (logger) {\n logger.error({ ...logContext, url, method, status: res.status, data }, 'HTTP call failed');\n }\n throw error;\n }\n\n if (logger) {\n logger.info({ ...logContext, url, method, status: res.status }, 'HTTP call success');\n }\n\n return data;\n } catch (err: any) {\n if (logger) {\n logger.error({ ...logContext, url, method, error: err.message }, 'HTTP call error');\n }\n throw err;\n }\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,oBAAAC,EAAA,aAAAC,EAAA,kBAAAC,EAAA,oBAAAC,IAAA,eAAAC,EAAAP,GCAA,IAAAQ,EAAmE,8BACnEC,EAAwB,mCAExBC,EAAyB,oCACzBC,EAAkC,mDAClCC,EAA4C,qDAC5CC,EAAgD,kBAIhD,OAAK,UAAU,IAAI,oBAAqB,eAAa,IAAI,EAEzD,IAAMC,EACJ,QAAQ,IAAI,mBACZ,QAAQ,IAAI,aACZ,kBACIC,EACJ,QAAQ,IAAI,gBACZ,QAAQ,IAAI,wBACZ,QAAQ,IAAI,UACZ,MACIC,EAAc,QAAQ,IAAI,UAAY,QAAQ,IAAI,UAAY,cAC9DC,EAAa,QAAQ,IAAI,aAAe,iBACxCC,GAAgB,QAAQ,IAAI,6BAA+B,yBAAyB,QAAQ,MAAO,EAAE,EACrGC,GAAwB,QAAQ,IAAI,uBAAyB,IAAI,YAAY,IAAM,OACnFC,EAAc,QAAQ,IAAI,aAAeH,EAGzCI,EAAW,CAAC,QAAQ,IAAI,YAAa,QAAQ,IAAI,YAAa,QAAQ,IAAI,WAAY,QAAQ,IAAI,UAAU,EAC/G,KAAMC,GAAMA,GAAKA,EAAE,KAAK,EAAE,OAAS,CAAC,EAEvC,GAAID,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AI,CAACA,EAAI,GAAI,CACX,IAAME,EAAQ,IAAI,MAAM,QAAQF,EAAI,MAAM,IAAIA,EAAI,YAAc,EAAE,GAAG,KAAK,CAAC,EAC3E,MAACE,EAAc,OAASF,EAAI,OAC3BE,EAAc,KAAOD,EAClBL,GACFA,EAAO,MAAM,CAAE,GAAGC,EAAY,IAAAH,EAAK,OAAAK,EAAQ,OAAQC,EAAI,OAAQ,KAAAC,CAAK,EAAG,kBAAkB,EAErFC,CACR,CAEA,OAAIN,GACFA,EAAO,KAAK,CAAE,GAAGC,EAAY,IAAAH,EAAK,OAAAK,EAAQ,OAAQC,EAAI,MAAO,EAAG,mBAAmB,EAG9EC,CACT,OAASE,EAAU,CACjB,MAAIP,GACFA,EAAO,MAAM,CAAE,GAAGC,EAAY,IAAAH,EAAK,OAAAK,EAAQ,MAAOI,EAAI,OAAQ,EAAG,iBAAiB,EAE9EA,CACR,CACF","names":["index_exports","__export","createLogger","errorMiddleware","httpCall","instrumentApp","sdkStartPromise","__toCommonJS","import_api","import_sdk_node","import_resources","import_exporter_trace_otlp_http","import_auto_instrumentations_node","import_undici","serviceName","serviceNamespace","environment","moduleName","otlpEndpoint","expressLayersEnabled","moduleLabel","proxyUrl","v","err","resource","ModuleNameSpanProcessor","span","currentName","_span","instrumentations","sdk","sdkStartPromise","error","shutdown","instrumentApp","app","logger","customModuleName","req","_res","next","import_pino","createLogger","mainEnv","mainApp","mainModule","pino","import_api","errorMiddleware","logger","err","req","res","next","span","httpCall","url","options","logger","logContext","fetchOptions","method","res","data","error","err"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/logging-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/global-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/sampling.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/timer-util.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/ExportResult.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/promise.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/callback.ts","../node_modules/@opentelemetry/sdk-trace-base/src/export/BatchSpanProcessorBase.ts","../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/export/BatchSpanProcessor.ts","../src/attributes.ts","../src/logger.ts","../src/exceptions.ts","../src/http-caller.ts"],"sourcesContent":["export { sdkStartPromise, instrumentApp } from './tracing.js';\nexport { createLogger } from './logger.js';\nexport { errorMiddleware } from './exceptions.js';\nexport { httpCall } from './http-caller.js';\nexport {\n getGlobalAttributes,\n setGlobalAttributes,\n mergeGlobalAttributes,\n getRequestAttributes,\n setRequestAttributes,\n mergeRequestAttributes,\n withRequestAttributes,\n runWithRequestContext,\n} from './attributes.js';\n","import { diag, DiagConsoleLogger, DiagLogLevel, trace } from '@opentelemetry/api';\nimport { NodeSDK } from '@opentelemetry/sdk-node';\nimport { SpanProcessor, ReadableSpan, BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';\nimport { Resource } from '@opentelemetry/resources';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\nimport { ProxyAgent, setGlobalDispatcher } from 'undici';\nimport type { Application, Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\nimport {\n getGlobalAttributes,\n getRequestAttributes,\n runWithRequestContext,\n setRequestAttributes,\n} from './attributes.js';\n\ndiag.setLogger(new DiagConsoleLogger(), DiagLogLevel.WARN);\n\nconst serviceName =\n process.env.OTEL_SERVICE_NAME ||\n process.env.MAIN_MODULE ||\n 'unknown-service';\nconst serviceNamespace =\n process.env.OTEL_NAMESPACE ||\n process.env.OTEL_SERVICE_NAMESPACE ||\n process.env.MAIN_APP ||\n 'app';\nconst environment = process.env.MAIN_ENV || process.env.NODE_ENV || 'development';\nconst moduleName = process.env.MAIN_MODULE || 'unknown-module';\nconst otlpEndpoint = (process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318').replace(/\\/$/, '');\nconst expressLayersEnabled = (process.env.ONELOG_EXPRESS_LAYERS || '').toLowerCase() === 'true';\nconst moduleLabel = process.env.MAIN_MODULE || moduleName;\n\n// Optional proxy support for environments with HTTP(S)_PROXY set\nconst proxyUrl = [process.env.HTTPS_PROXY, process.env.https_proxy, process.env.HTTP_PROXY, process.env.http_proxy]\n .find((v) => v && v.trim().length > 0);\n\nif (proxyUrl) {\n try {\n setGlobalDispatcher(new ProxyAgent(proxyUrl));\n // eslint-disable-next-line no-console\n console.log(`[onelog] Proxy enabled for outbound traffic: ${proxyUrl}`);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to configure proxy agent:', (err as Error).message);\n }\n}\n\nconst resource = Resource.default().merge(\n new Resource({\n 'service.name': serviceName,\n 'service.namespace': serviceNamespace,\n 'deployment.environment': environment,\n 'module.name': moduleLabel,\n }),\n);\n\nclass ModuleNameSpanProcessor implements SpanProcessor {\n constructor(private readonly moduleName: string) {}\n onStart(span: any): void {\n if (!span) return;\n const currentName = (span as any).name || (span as any)._name || '';\n if (this.moduleName && !currentName.startsWith(`[${this.moduleName}] `)) {\n span.updateName(`[${this.moduleName}] ${currentName}`);\n }\n if (this.moduleName) {\n span.setAttribute('module.name', this.moduleName);\n }\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(dynamicAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n onEnd(_span: ReadableSpan): void {\n // no-op\n }\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\nclass CombinedSpanProcessor implements SpanProcessor {\n constructor(private readonly processors: SpanProcessor[]) {}\n onStart(span: any, ctx?: any): void {\n for (const p of this.processors) p.onStart(span as any, ctx);\n }\n onEnd(span: ReadableSpan): void {\n for (const p of this.processors) p.onEnd(span);\n }\n shutdown(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.shutdown())).then(() => undefined);\n }\n forceFlush(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.forceFlush())).then(() => undefined);\n }\n}\n\nconst instrumentations = getNodeAutoInstrumentations({\n '@opentelemetry/instrumentation-http': {\n enabled: true,\n },\n '@opentelemetry/instrumentation-express': {\n enabled: true,\n ignoreLayersType: expressLayersEnabled ? [] : (['middleware', 'request_handler'] as any),\n },\n '@opentelemetry/instrumentation-undici': {\n enabled: true,\n },\n // Redis instrumentation is noisy in our workloads; keep it off by default\n '@opentelemetry/instrumentation-ioredis': { enabled: false },\n '@opentelemetry/instrumentation-redis': { enabled: false },\n '@opentelemetry/instrumentation-fs': { enabled: false },\n '@opentelemetry/instrumentation-dns': { enabled: false },\n '@opentelemetry/instrumentation-net': { enabled: false },\n});\n\nconst exporter = new OTLPTraceExporter({\n url: `${otlpEndpoint}/v1/traces`,\n});\n\nconst spanProcessor = new CombinedSpanProcessor([\n new ModuleNameSpanProcessor(moduleLabel),\n new BatchSpanProcessor(exporter),\n]);\n\nconst sdk = new NodeSDK({\n resource,\n instrumentations: [instrumentations],\n spanProcessor,\n});\n\nexport const sdkStartPromise = Promise.resolve(sdk.start()).catch((error) => {\n console.error('Failed to start OpenTelemetry SDK', error);\n return Promise.resolve();\n});\n\nconst shutdown = async () => {\n try {\n await sdk.shutdown();\n } catch (error) {\n console.error('Error shutting down OpenTelemetry SDK', error);\n }\n};\n\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n\nexport const instrumentApp = (app: Application, logger?: Logger, customModuleName?: string) => {\n const moduleLabel = customModuleName || process.env.MAIN_MODULE || moduleName;\n app.use((req: Request, _res: Response, next: NextFunction) => {\n runWithRequestContext(() => {\n setRequestAttributes({\n 'module.name': moduleLabel,\n 'http.method': req.method,\n 'http.target': req.path,\n });\n\n const span = trace.getActiveSpan();\n if (span) {\n span.setAttribute('module.name', moduleLabel);\n span.updateName(`[${moduleLabel}] ${req.method} ${req.path}`);\n const requestAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(requestAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n if (logger) {\n logger.info(\n {\n method: req.method,\n path: req.path,\n ip: req.ip,\n },\n 'Incoming request',\n );\n }\n next();\n });\n });\n};\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag, Exception } from '@opentelemetry/api';\nimport { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n const result = {} as Record<string, string>;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogLevel } from '@opentelemetry/api';\nimport { TracesSamplerValues } from './sampling';\n\nconst DEFAULT_LIST_SEPARATOR = ',';\n\n/**\n * Environment interface to define all names\n */\n\nconst ENVIRONMENT_BOOLEAN_KEYS = ['OTEL_SDK_DISABLED'] as const;\n\ntype ENVIRONMENT_BOOLEANS = {\n [K in (typeof ENVIRONMENT_BOOLEAN_KEYS)[number]]?: boolean;\n};\n\nfunction isEnvVarABoolean(key: unknown): key is keyof ENVIRONMENT_BOOLEANS {\n return (\n ENVIRONMENT_BOOLEAN_KEYS.indexOf(key as keyof ENVIRONMENT_BOOLEANS) > -1\n );\n}\n\nconst ENVIRONMENT_NUMBERS_KEYS = [\n 'OTEL_BSP_EXPORT_TIMEOUT',\n 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BSP_MAX_QUEUE_SIZE',\n 'OTEL_BSP_SCHEDULE_DELAY',\n 'OTEL_BLRP_EXPORT_TIMEOUT',\n 'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BLRP_MAX_QUEUE_SIZE',\n 'OTEL_BLRP_SCHEDULE_DELAY',\n 'OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_LINK_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT',\n 'OTEL_EXPORTER_OTLP_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_TRACES_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_METRICS_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_LOGS_TIMEOUT',\n 'OTEL_EXPORTER_JAEGER_AGENT_PORT',\n] as const;\n\ntype ENVIRONMENT_NUMBERS = {\n [K in (typeof ENVIRONMENT_NUMBERS_KEYS)[number]]?: number;\n};\n\nfunction isEnvVarANumber(key: unknown): key is keyof ENVIRONMENT_NUMBERS {\n return (\n ENVIRONMENT_NUMBERS_KEYS.indexOf(key as keyof ENVIRONMENT_NUMBERS) > -1\n );\n}\n\nconst ENVIRONMENT_LISTS_KEYS = [\n 'OTEL_NO_PATCH_MODULES',\n 'OTEL_PROPAGATORS',\n 'OTEL_SEMCONV_STABILITY_OPT_IN',\n] as const;\n\ntype ENVIRONMENT_LISTS = {\n [K in (typeof ENVIRONMENT_LISTS_KEYS)[number]]?: string[];\n};\n\nfunction isEnvVarAList(key: unknown): key is keyof ENVIRONMENT_LISTS {\n return ENVIRONMENT_LISTS_KEYS.indexOf(key as keyof ENVIRONMENT_LISTS) > -1;\n}\n\nexport type ENVIRONMENT = {\n CONTAINER_NAME?: string;\n ECS_CONTAINER_METADATA_URI_V4?: string;\n ECS_CONTAINER_METADATA_URI?: string;\n HOSTNAME?: string;\n KUBERNETES_SERVICE_HOST?: string;\n NAMESPACE?: string;\n OTEL_EXPORTER_JAEGER_AGENT_HOST?: string;\n OTEL_EXPORTER_JAEGER_ENDPOINT?: string;\n OTEL_EXPORTER_JAEGER_PASSWORD?: string;\n OTEL_EXPORTER_JAEGER_USER?: string;\n OTEL_EXPORTER_OTLP_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_HEADERS?: string;\n OTEL_EXPORTER_OTLP_TRACES_HEADERS?: string;\n OTEL_EXPORTER_OTLP_METRICS_HEADERS?: string;\n OTEL_EXPORTER_OTLP_LOGS_HEADERS?: string;\n OTEL_EXPORTER_ZIPKIN_ENDPOINT?: string;\n OTEL_LOG_LEVEL?: DiagLogLevel;\n OTEL_RESOURCE_ATTRIBUTES?: string;\n OTEL_SERVICE_NAME?: string;\n OTEL_TRACES_EXPORTER?: string;\n OTEL_TRACES_SAMPLER_ARG?: string;\n OTEL_TRACES_SAMPLER?: string;\n OTEL_LOGS_EXPORTER?: string;\n OTEL_EXPORTER_OTLP_INSECURE?: string;\n OTEL_EXPORTER_OTLP_TRACES_INSECURE?: string;\n OTEL_EXPORTER_OTLP_METRICS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_LOGS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE?: string;\n} & ENVIRONMENT_BOOLEANS &\n ENVIRONMENT_NUMBERS &\n ENVIRONMENT_LISTS;\n\nexport type RAW_ENVIRONMENT = {\n [key: string]: string | number | undefined | string[];\n};\n\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\n\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 128;\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 128;\n\n/**\n * Default environment variables\n */\nexport const DEFAULT_ENVIRONMENT: Required<ENVIRONMENT> = {\n OTEL_SDK_DISABLED: false,\n CONTAINER_NAME: '',\n ECS_CONTAINER_METADATA_URI_V4: '',\n ECS_CONTAINER_METADATA_URI: '',\n HOSTNAME: '',\n KUBERNETES_SERVICE_HOST: '',\n NAMESPACE: '',\n OTEL_BSP_EXPORT_TIMEOUT: 30000,\n OTEL_BSP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BSP_MAX_QUEUE_SIZE: 2048,\n OTEL_BSP_SCHEDULE_DELAY: 5000,\n OTEL_BLRP_EXPORT_TIMEOUT: 30000,\n OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BLRP_MAX_QUEUE_SIZE: 2048,\n OTEL_BLRP_SCHEDULE_DELAY: 5000,\n OTEL_EXPORTER_JAEGER_AGENT_HOST: '',\n OTEL_EXPORTER_JAEGER_AGENT_PORT: 6832,\n OTEL_EXPORTER_JAEGER_ENDPOINT: '',\n OTEL_EXPORTER_JAEGER_PASSWORD: '',\n OTEL_EXPORTER_JAEGER_USER: '',\n OTEL_EXPORTER_OTLP_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_HEADERS: '',\n OTEL_EXPORTER_OTLP_TRACES_HEADERS: '',\n OTEL_EXPORTER_OTLP_METRICS_HEADERS: '',\n OTEL_EXPORTER_OTLP_LOGS_HEADERS: '',\n OTEL_EXPORTER_OTLP_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_TRACES_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_METRICS_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_LOGS_TIMEOUT: 10000,\n OTEL_EXPORTER_ZIPKIN_ENDPOINT: 'http://localhost:9411/api/v2/spans',\n OTEL_LOG_LEVEL: DiagLogLevel.INFO,\n OTEL_NO_PATCH_MODULES: [],\n OTEL_PROPAGATORS: ['tracecontext', 'baggage'],\n OTEL_RESOURCE_ATTRIBUTES: '',\n OTEL_SERVICE_NAME: '',\n OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_EVENT_COUNT_LIMIT: 128,\n OTEL_SPAN_LINK_COUNT_LIMIT: 128,\n OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n OTEL_TRACES_EXPORTER: '',\n OTEL_TRACES_SAMPLER: TracesSamplerValues.ParentBasedAlwaysOn,\n OTEL_TRACES_SAMPLER_ARG: '',\n OTEL_LOGS_EXPORTER: '',\n OTEL_EXPORTER_OTLP_INSECURE: '',\n OTEL_EXPORTER_OTLP_TRACES_INSECURE: '',\n OTEL_EXPORTER_OTLP_METRICS_INSECURE: '',\n OTEL_EXPORTER_OTLP_LOGS_INSECURE: '',\n OTEL_EXPORTER_OTLP_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: 'cumulative',\n OTEL_SEMCONV_STABILITY_OPT_IN: [],\n};\n\n/**\n * @param key\n * @param environment\n * @param values\n */\nfunction parseBoolean(\n key: keyof ENVIRONMENT_BOOLEANS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n if (typeof values[key] === 'undefined') {\n return;\n }\n\n const value = String(values[key]);\n // support case-insensitive \"true\"\n environment[key] = value.toLowerCase() === 'true';\n}\n\n/**\n * Parses a variable as number with number validation\n * @param name\n * @param environment\n * @param values\n * @param min\n * @param max\n */\nfunction parseNumber(\n name: keyof ENVIRONMENT_NUMBERS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT,\n min = -Infinity,\n max = Infinity\n) {\n if (typeof values[name] !== 'undefined') {\n const value = Number(values[name] as string);\n if (!isNaN(value)) {\n if (value < min) {\n environment[name] = min;\n } else if (value > max) {\n environment[name] = max;\n } else {\n environment[name] = value;\n }\n }\n }\n}\n\n/**\n * Parses list-like strings from input into output.\n * @param name\n * @param environment\n * @param values\n * @param separator\n */\nfunction parseStringList(\n name: keyof ENVIRONMENT_LISTS,\n output: ENVIRONMENT,\n input: RAW_ENVIRONMENT,\n separator = DEFAULT_LIST_SEPARATOR\n) {\n const givenValue = input[name];\n if (typeof givenValue === 'string') {\n output[name] = givenValue.split(separator).map(v => v.trim());\n }\n}\n\n// The support string -> DiagLogLevel mappings\nconst logLevelMap: { [key: string]: DiagLogLevel } = {\n ALL: DiagLogLevel.ALL,\n VERBOSE: DiagLogLevel.VERBOSE,\n DEBUG: DiagLogLevel.DEBUG,\n INFO: DiagLogLevel.INFO,\n WARN: DiagLogLevel.WARN,\n ERROR: DiagLogLevel.ERROR,\n NONE: DiagLogLevel.NONE,\n};\n\n/**\n * Environmentally sets log level if valid log level string is provided\n * @param key\n * @param environment\n * @param values\n */\nfunction setLogLevelFromEnv(\n key: keyof ENVIRONMENT,\n environment: RAW_ENVIRONMENT | ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n const value = values[key];\n if (typeof value === 'string') {\n const theLevel = logLevelMap[value.toUpperCase()];\n if (theLevel != null) {\n environment[key] = theLevel;\n }\n }\n}\n\n/**\n * Parses environment values\n * @param values\n */\nexport function parseEnvironment(values: RAW_ENVIRONMENT): ENVIRONMENT {\n const environment: ENVIRONMENT = {};\n\n for (const env in DEFAULT_ENVIRONMENT) {\n const key = env as keyof ENVIRONMENT;\n\n switch (key) {\n case 'OTEL_LOG_LEVEL':\n setLogLevelFromEnv(key, environment, values);\n break;\n\n default:\n if (isEnvVarABoolean(key)) {\n parseBoolean(key, environment, values);\n } else if (isEnvVarANumber(key)) {\n parseNumber(key, environment, values);\n } else if (isEnvVarAList(key)) {\n parseStringList(key, environment, values);\n } else {\n const value = values[key];\n if (typeof value !== 'undefined' && value !== null) {\n environment[key] = String(value);\n }\n }\n }\n }\n\n return environment;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DEFAULT_ENVIRONMENT,\n ENVIRONMENT,\n RAW_ENVIRONMENT,\n parseEnvironment,\n} from '../../utils/environment';\n\n/**\n * Gets the environment variables\n */\nexport function getEnv(): Required<ENVIRONMENT> {\n const processEnv = parseEnvironment(process.env as RAW_ENVIRONMENT);\n return Object.assign({}, DEFAULT_ENVIRONMENT, processEnv);\n}\n\nexport function getEnvWithoutDefaults(): ENVIRONMENT {\n return parseEnvironment(process.env as RAW_ENVIRONMENT);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport function unrefTimer(timer: NodeJS.Timer): void {\n timer.unref();\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred<R>();\n constructor(\n private _callback: T,\n private _that: This\n ) {}\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters<T>): Promise<R> {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { context, Context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getEnv,\n globalErrorHandler,\n suppressTracing,\n unrefTimer,\n} from '@opentelemetry/core';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\nimport { BufferConfig } from '../types';\nimport { ReadableSpan } from './ReadableSpan';\nimport { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(\n private readonly _exporter: SpanExporter,\n config?: T\n ) {\n const env = getEnv();\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE;\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : env.OTEL_BSP_MAX_QUEUE_SIZE;\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : env.OTEL_BSP_SCHEDULE_DELAY;\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : env.OTEL_BSP_EXPORT_TIMEOUT;\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n unrefTimer(this._timer);\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\n\nexport type AttributeMap = Record<string, any>;\n\ntype RequestAttributeContext = {\n requestAttributes: AttributeMap;\n};\n\nconst requestAttributeStorage = new AsyncLocalStorage<RequestAttributeContext>();\n\nlet globalAttributes: AttributeMap = {};\n\nconst clone = (attrs?: AttributeMap) => ({ ...(attrs || {}) });\n\nexport const getGlobalAttributes = (): AttributeMap => clone(globalAttributes);\n\nexport const setGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = clone(attrs);\n};\n\nexport const mergeGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = { ...globalAttributes, ...clone(attrs) };\n};\n\nexport const getRequestAttributes = (): AttributeMap => {\n const store = requestAttributeStorage.getStore();\n return store?.requestAttributes || {};\n};\n\nexport const setRequestAttributes = (attrs: AttributeMap, options?: { append?: boolean }) => {\n const store = requestAttributeStorage.getStore();\n if (!store) return;\n\n const nextAttributes =\n options?.append === false ? clone(attrs) : { ...store.requestAttributes, ...clone(attrs) };\n store.requestAttributes = nextAttributes;\n};\n\nexport const mergeRequestAttributes = (attrs: AttributeMap) => setRequestAttributes(attrs);\n\nexport const withRequestAttributes = <T>(\n attrs: AttributeMap,\n fn: () => T,\n options?: { append?: boolean },\n): T => {\n const store = requestAttributeStorage.getStore();\n if (!store) {\n return runWithRequestContext(() => fn(), attrs);\n }\n setRequestAttributes(attrs, options);\n return fn();\n};\n\nexport const runWithRequestContext = <T>(fn: () => T, initialAttributes?: AttributeMap): T => {\n return requestAttributeStorage.run(\n {\n requestAttributes: clone(initialAttributes),\n },\n fn,\n );\n};\n","import pino, { Logger } from 'pino';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nconst levelMethods = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'] as const;\n\nconst wrapWithDynamicAttributes = (logger: Logger): Logger => {\n const buildAttrs = () => ({ ...getGlobalAttributes(), ...getRequestAttributes() });\n\n return new Proxy(logger, {\n get(target, prop, receiver) {\n const original = Reflect.get(target, prop, receiver);\n if (typeof prop === 'string' && levelMethods.includes(prop as any) && typeof original === 'function') {\n return (firstArg?: any, ...rest: any[]) => {\n const attrs = buildAttrs();\n if (firstArg && typeof firstArg === 'object' && !Array.isArray(firstArg)) {\n return (original as any).call(target, { ...attrs, ...firstArg }, ...rest);\n }\n return (original as any).call(target, { ...attrs }, firstArg, ...rest);\n };\n }\n return original;\n },\n });\n};\n\nexport function createLogger() {\n const mainEnv = process.env.MAIN_ENV || 'development';\n const mainApp = process.env.MAIN_APP || 'app';\n const mainModule = process.env.MAIN_MODULE || 'unknown-module';\n\n const logger = pino({\n transport: {\n targets: [\n {\n target: 'pino-opentelemetry-transport',\n level: 'info',\n options: {\n resourceAttributes: {\n 'service.name': mainApp,\n 'service.namespace': mainEnv,\n 'deployment.environment': mainEnv,\n 'module.name': mainModule,\n 'host.name': require('os').hostname(),\n },\n },\n },\n {\n target: 'pino-pretty',\n level: 'debug',\n options: {\n colorize: true,\n translateTime: 'HH:MM:ss Z',\n ignore: 'pid,hostname',\n },\n },\n ],\n },\n });\n\n const base = logger.child({\n env: mainEnv,\n app: mainApp,\n module: mainModule,\n });\n\n return wrapWithDynamicAttributes(base);\n}\n","import { trace, SpanStatusCode } from '@opentelemetry/api';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\nimport type { Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\n\nexport const errorMiddleware =\n (logger?: Logger) =>\n (err: Error, req: Request, res: Response, next: NextFunction) => {\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n\n if (logger) {\n logger.error(\n {\n ...dynamicAttributes,\n error: err.message,\n stack: err.stack,\n path: req.path,\n },\n 'Unhandled error',\n );\n }\n\n const span = trace.getActiveSpan();\n if (span) {\n span.recordException(err);\n span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });\n }\n\n if (res.headersSent) {\n return next(err);\n }\n\n res.status(500).json({\n error: err.message,\n attributes: dynamicAttributes,\n module: process.env.MAIN_MODULE || 'unknown-module',\n });\n };\n","import { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nexport interface HttpCallContext {\n [key: string]: any;\n}\n\nexport interface HttpCallOptions extends RequestInit {\n body?: any;\n}\n\nexport async function httpCall(\n url: string,\n options: HttpCallOptions = {},\n logger?: { info: Function; error: Function },\n logContext: HttpCallContext = {},\n) {\n const fetchOptions: RequestInit = { ...options };\n const method = (fetchOptions.method || 'GET').toString().toUpperCase();\n\n if (\n fetchOptions.body &&\n typeof fetchOptions.body !== 'string' &&\n !(fetchOptions.body instanceof Buffer) &&\n !(fetchOptions.body instanceof ArrayBuffer)\n ) {\n fetchOptions.body = JSON.stringify(fetchOptions.body);\n fetchOptions.headers = {\n 'Content-Type': 'application/json',\n ...(fetchOptions.headers || {}),\n };\n }\n\n const dynamicContext = { ...getGlobalAttributes(), ...getRequestAttributes(), ...logContext };\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method }, 'HTTP call start');\n }\n\n try {\n const res = await fetch(url, fetchOptions);\n const contentType = res.headers.get('content-type') || '';\n const isJson = contentType.includes('application/json');\n const data = isJson ? await res.json().catch(() => null) : await res.text().catch(() => null);\n\n if (!res.ok) {\n const error = new Error(`HTTP ${res.status} ${res.statusText || ''}`.trim());\n (error as any).status = res.status;\n (error as any).data = data;\n if (logger) {\n logger.error({ ...dynamicContext, url, method, status: res.status, data }, 'HTTP call failed');\n }\n throw error;\n }\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method, status: res.status }, 'HTTP call success');\n }\n\n return data;\n } catch (err: any) {\n if (logger) {\n logger.error({ ...dynamicContext, url, method, error: err.message }, 'HTTP call error');\n }\n throw err;\n }\n}\n"],"mappings":"ukBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,kBAAAE,GAAA,oBAAAC,GAAA,wBAAAC,EAAA,yBAAAC,EAAA,aAAAC,GAAA,kBAAAC,GAAA,0BAAAC,EAAA,2BAAAC,EAAA,0BAAAC,EAAA,oBAAAC,GAAA,wBAAAC,EAAA,yBAAAC,EAAA,0BAAAC,IAAA,eAAAC,GAAAf,ICAA,IAAAgB,EAA6D,8BAC7DC,GAAwB,mCCexB,IAAAC,EAA0C,8BAEp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AAI,MAAO,EAAG,mBAAmB,EAGlFC,CACT,OAASE,EAAU,CACjB,MAAIV,GACFA,EAAO,MAAM,CAAE,GAAGI,EAAgB,IAAAN,EAAK,OAAAK,EAAQ,MAAOO,EAAI,OAAQ,EAAG,iBAAiB,EAElFA,CACR,CACF","names":["index_exports","__export","createLogger","errorMiddleware","getGlobalAttributes","getRequestAttributes","httpCall","instrumentApp","mergeGlobalAttributes","mergeRequestAttributes","runWithRequestContext","sdkStartPromise","setGlobalAttributes","setRequestAttributes","withRequestAttributes","__toCommonJS","import_api","import_sdk_node","import_api","SUPPRESS_TRACING_KEY","suppressTracing","context","import_api","loggingErrorHandler","ex","stringifyException","flattenException","result","current","propertyName","value","delegateHandler","loggingErrorHandler","globalErrorHandler","ex","delegateHandler","import_api","TracesSamplerValues","DEFAULT_LIST_SEPARATOR","ENVIRONMENT_BOOLEAN_KEYS","isEnvVarABoolean","key","ENVIRONMENT_NUMBERS_KEYS","isEnvVarANumber","ENVIRONMENT_LISTS_KEYS","isEnvVarAList","DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT","DEFAULT_ATTRIBUTE_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","DEFAULT_ENVIRONMENT","TracesSamplerValues","parseBoolean","environment","values","value","parseNumber","name","min","max","parseStringList","output","input","separator","givenValue","v","logLevelMap","setLogLevelFromEnv","theLevel","parseEnvironment","env","getEnv","processEnv","parseEnvironment","DEFAULT_ENVIRONMENT","unrefTimer","timer","ExportResultCode","Deferred","_this","resolve","reject","val","err","BindOnceFuture","_callback","_that","Deferred","_this","args","_i","_a","__spreadArray","__read","val","err","import_api","BatchSpanProcessorBase","_exporter","config","env","getEnv","BindOnceFuture","_span","_parentContext","span","_this","resolve","reject","promises","count","i","j","timer","suppressTracing","spans","doExport","result","ExportResultCode","_a","pendingResources","len","err","globalErrorHandler","flush","e","unrefTimer","BatchSpanProcessor","_super","__extends","BatchSpanProcessorBase","import_resources","import_exporter_trace_otlp_http","import_auto_instrumentations_node","import_undici","import_node_async_hooks","requestAttributeStorage","globalAttributes","clone","attrs","getGlobalAttributes","setGlobalAttributes","mergeGlobalAttributes","getRequestAttributes","setRequestAttributes","options","store","nextAttributes","mergeRequestAttributes","withRequestAttributes","fn","runWithRequestContext","initialAttributes","serviceName","serviceNamespace","environment","moduleName","otlpEndpoint","expressLayersEnabled","moduleLabel","proxyUrl","v","err","resource","ModuleNameSpanProcessor","span","currentName","dynamicAttributes","getGlobalAttributes","getRequestAttributes","key","value","_span","CombinedSpanProcessor","processors","ctx","p","instrumentations","exporter","spanProcessor","BatchSpanProcessor","sdk","sdkStartPromise","error","shutdown","instrumentApp","app","logger","customModuleName","req","_res","next","runWithRequestContext","setRequestAttributes","requestAttributes","import_pino","levelMethods","wrapWithDynamicAttributes","logger","buildAttrs","getGlobalAttributes","getRequestAttributes","target","prop","receiver","original","firstArg","rest","attrs","createLogger","mainEnv","mainApp","mainModule","base","pino","import_api","errorMiddleware","logger","err","req","res","next","dynamicAttributes","getGlobalAttributes","getRequestAttributes","span","httpCall","url","options","logger","logContext","fetchOptions","method","dynamicContext","getGlobalAttributes","getRequestAttributes","res","data","error","err"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -4,7 +4,7 @@ import pino, { Logger } from 'pino';
|
|
|
4
4
|
declare const sdkStartPromise: Promise<void>;
|
|
5
5
|
declare const instrumentApp: (app: Application, logger?: Logger, customModuleName?: string) => void;
|
|
6
6
|
|
|
7
|
-
declare function createLogger(): pino.Logger
|
|
7
|
+
declare function createLogger(): pino.Logger;
|
|
8
8
|
|
|
9
9
|
declare const errorMiddleware: (logger?: Logger) => (err: Error, req: Request, res: Response, next: NextFunction) => void;
|
|
10
10
|
|
|
@@ -19,4 +19,18 @@ declare function httpCall(url: string, options?: HttpCallOptions, logger?: {
|
|
|
19
19
|
error: Function;
|
|
20
20
|
}, logContext?: HttpCallContext): Promise<any>;
|
|
21
21
|
|
|
22
|
-
|
|
22
|
+
type AttributeMap = Record<string, any>;
|
|
23
|
+
declare const getGlobalAttributes: () => AttributeMap;
|
|
24
|
+
declare const setGlobalAttributes: (attrs: AttributeMap) => void;
|
|
25
|
+
declare const mergeGlobalAttributes: (attrs: AttributeMap) => void;
|
|
26
|
+
declare const getRequestAttributes: () => AttributeMap;
|
|
27
|
+
declare const setRequestAttributes: (attrs: AttributeMap, options?: {
|
|
28
|
+
append?: boolean;
|
|
29
|
+
}) => void;
|
|
30
|
+
declare const mergeRequestAttributes: (attrs: AttributeMap) => void;
|
|
31
|
+
declare const withRequestAttributes: <T>(attrs: AttributeMap, fn: () => T, options?: {
|
|
32
|
+
append?: boolean;
|
|
33
|
+
}) => T;
|
|
34
|
+
declare const runWithRequestContext: <T>(fn: () => T, initialAttributes?: AttributeMap) => T;
|
|
35
|
+
|
|
36
|
+
export { createLogger, errorMiddleware, getGlobalAttributes, getRequestAttributes, httpCall, instrumentApp, mergeGlobalAttributes, mergeRequestAttributes, runWithRequestContext, sdkStartPromise, setGlobalAttributes, setRequestAttributes, withRequestAttributes };
|
package/dist/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import pino, { Logger } from 'pino';
|
|
|
4
4
|
declare const sdkStartPromise: Promise<void>;
|
|
5
5
|
declare const instrumentApp: (app: Application, logger?: Logger, customModuleName?: string) => void;
|
|
6
6
|
|
|
7
|
-
declare function createLogger(): pino.Logger
|
|
7
|
+
declare function createLogger(): pino.Logger;
|
|
8
8
|
|
|
9
9
|
declare const errorMiddleware: (logger?: Logger) => (err: Error, req: Request, res: Response, next: NextFunction) => void;
|
|
10
10
|
|
|
@@ -19,4 +19,18 @@ declare function httpCall(url: string, options?: HttpCallOptions, logger?: {
|
|
|
19
19
|
error: Function;
|
|
20
20
|
}, logContext?: HttpCallContext): Promise<any>;
|
|
21
21
|
|
|
22
|
-
|
|
22
|
+
type AttributeMap = Record<string, any>;
|
|
23
|
+
declare const getGlobalAttributes: () => AttributeMap;
|
|
24
|
+
declare const setGlobalAttributes: (attrs: AttributeMap) => void;
|
|
25
|
+
declare const mergeGlobalAttributes: (attrs: AttributeMap) => void;
|
|
26
|
+
declare const getRequestAttributes: () => AttributeMap;
|
|
27
|
+
declare const setRequestAttributes: (attrs: AttributeMap, options?: {
|
|
28
|
+
append?: boolean;
|
|
29
|
+
}) => void;
|
|
30
|
+
declare const mergeRequestAttributes: (attrs: AttributeMap) => void;
|
|
31
|
+
declare const withRequestAttributes: <T>(attrs: AttributeMap, fn: () => T, options?: {
|
|
32
|
+
append?: boolean;
|
|
33
|
+
}) => T;
|
|
34
|
+
declare const runWithRequestContext: <T>(fn: () => T, initialAttributes?: AttributeMap) => T;
|
|
35
|
+
|
|
36
|
+
export { createLogger, errorMiddleware, getGlobalAttributes, getRequestAttributes, httpCall, instrumentApp, mergeGlobalAttributes, mergeRequestAttributes, runWithRequestContext, sdkStartPromise, setGlobalAttributes, setRequestAttributes, withRequestAttributes };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var v=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,o)=>(typeof require<"u"?require:t)[o]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{diag as E,DiagConsoleLogger as N,DiagLogLevel as g,trace as T}from"@opentelemetry/api";import{NodeSDK as A}from"@opentelemetry/sdk-node";import{Resource as u}from"@opentelemetry/resources";import{OTLPTraceExporter as P}from"@opentelemetry/exporter-trace-otlp-http";import{getNodeAutoInstrumentations as x}from"@opentelemetry/auto-instrumentations-node";import{ProxyAgent as L,setGlobalDispatcher as S}from"undici";E.setLogger(new N,g.WARN);var _=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",b=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",O=process.env.MAIN_ENV||process.env.NODE_ENV||"development",d=process.env.MAIN_MODULE||"unknown-module",R=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),w=(process.env.ONELOG_EXPRESS_LAYERS||"").toLowerCase()==="true",f=process.env.MAIN_MODULE||d,m=[process.env.HTTPS_PROXY,process.env.https_proxy,process.env.HTTP_PROXY,process.env.http_proxy].find(e=>e&&e.trim().length>0);if(m)try{S(new L(m)),console.log(`[onelog] Proxy enabled for outbound traffic: ${m}`)}catch(e){console.error("[onelog] Failed to configure proxy agent:",e.message)}var M=u.default().merge(new u({"service.name":_,"service.namespace":b,"deployment.environment":O,"module.name":f})),l=class{constructor(t){this.moduleName=t}onStart(t){if(!t)return;let o=t.name||t._name||"";this.moduleName&&!o.startsWith(`[${this.moduleName}] `)&&t.updateName(`[${this.moduleName}] ${o}`),this.moduleName&&t.setAttribute("module.name",this.moduleName)}onEnd(t){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}},I=x({"@opentelemetry/instrumentation-http":{enabled:!0},"@opentelemetry/instrumentation-express":{enabled:!0,ignoreLayersType:w?[]:["middleware","request_handler"]},"@opentelemetry/instrumentation-undici":{enabled:!0},"@opentelemetry/instrumentation-ioredis":{enabled:!1},"@opentelemetry/instrumentation-redis":{enabled:!1},"@opentelemetry/instrumentation-fs":{enabled:!1},"@opentelemetry/instrumentation-dns":{enabled:!1},"@opentelemetry/instrumentation-net":{enabled:!1}}),y=new A({traceExporter:new P({url:`${R}/v1/traces`}),resource:M,instrumentations:[I],spanProcessor:new l(f)}),C=Promise.resolve(y.start()).catch(e=>(console.error("Failed to start OpenTelemetry SDK",e),Promise.resolve())),h=async()=>{try{await y.shutdown()}catch(e){console.error("Error shutting down OpenTelemetry SDK",e)}};process.on("SIGTERM",h);process.on("SIGINT",h);var D=(e,t,o)=>{let s=o||process.env.MAIN_MODULE||d;e.use((n,a,r)=>{let i=T.getActiveSpan();i&&(i.setAttribute("module.name",s),i.updateName(`[${s}] ${n.method} ${n.path}`)),t&&t.info({method:n.method,path:n.path,ip:n.ip},"Incoming request"),r()})};import H from"pino";function k(){let e=process.env.MAIN_ENV||"development",t=process.env.MAIN_APP||"app",o=process.env.MAIN_MODULE||"unknown-module";return H({transport:{targets:[{target:"pino-opentelemetry-transport",level:"info",options:{resourceAttributes:{"service.name":t,"service.namespace":e,"deployment.environment":e,"module.name":o,"host.name":v("os").hostname()}}},{target:"pino-pretty",level:"debug",options:{colorize:!0,translateTime:"HH:MM:ss Z",ignore:"pid,hostname"}}]}}).child({env:e,app:t,module:o})}import{trace as $,SpanStatusCode as F}from"@opentelemetry/api";var U=e=>(t,o,s,n)=>{e&&e.error({error:t.message,stack:t.stack,path:o.path},"Unhandled error");let a=$.getActiveSpan();if(a&&(a.recordException(t),a.setStatus({code:F.ERROR,message:t.message})),s.headersSent)return n(t);s.status(500).json({error:t.message,module:process.env.MAIN_MODULE||"unknown-module"})};async function q(e,t={},o,s={}){let n={...t},a=(n.method||"GET").toString().toUpperCase();n.body&&typeof n.body!="string"&&!(n.body instanceof Buffer)&&!(n.body instanceof ArrayBuffer)&&(n.body=JSON.stringify(n.body),n.headers={"Content-Type":"application/json",...n.headers||{}}),o&&o.info({...s,url:e,method:a},"HTTP call start");try{let r=await fetch(e,n),p=(r.headers.get("content-type")||"").includes("application/json")?await r.json().catch(()=>null):await r.text().catch(()=>null);if(!r.ok){let c=new Error(`HTTP ${r.status} ${r.statusText||""}`.trim());throw c.status=r.status,c.data=p,o&&o.error({...s,url:e,method:a,status:r.status,data:p},"HTTP call failed"),c}return o&&o.info({...s,url:e,method:a,status:r.status},"HTTP call success"),p}catch(r){throw o&&o.error({...s,url:e,method:a,error:r.message},"HTTP call error"),r}}export{k as createLogger,U as errorMiddleware,q as httpCall,D as instrumentApp,C as sdkStartPromise};
|
|
1
|
+
var Y=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{diag as Ce,DiagConsoleLogger as ge,DiagLogLevel as ve,trace as be}from"@opentelemetry/api";import{NodeSDK as Me}from"@opentelemetry/sdk-node";import{createContextKey as W}from"@opentelemetry/api";var Q=W("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function N(e){return e.setValue(Q,!0)}import{diag as Z}from"@opentelemetry/api";function D(){return function(e){Z.error($(e))}}function $(e){return typeof e=="string"?e:JSON.stringify(J(e))}function J(e){for(var t={},r=e;r!==null;)Object.getOwnPropertyNames(r).forEach(function(o){if(!t[o]){var n=r[o];n&&(t[o]=String(n))}}),r=Object.getPrototypeOf(r);return t}var k=D();function h(e){try{k(e)}catch{}}import{DiagLogLevel as c}from"@opentelemetry/api";var A;(function(e){e.AlwaysOff="always_off",e.AlwaysOn="always_on",e.ParentBasedAlwaysOff="parentbased_always_off",e.ParentBasedAlwaysOn="parentbased_always_on",e.ParentBasedTraceIdRatio="parentbased_traceidratio",e.TraceIdRatio="traceidratio"})(A||(A={}));var ee=",",te=["OTEL_SDK_DISABLED"];function re(e){return te.indexOf(e)>-1}var oe=["OTEL_BSP_EXPORT_TIMEOUT","OTEL_BSP_MAX_EXPORT_BATCH_SIZE","OTEL_BSP_MAX_QUEUE_SIZE","OTEL_BSP_SCHEDULE_DELAY","OTEL_BLRP_EXPORT_TIMEOUT","OTEL_BLRP_MAX_EXPORT_BATCH_SIZE","OTEL_BLRP_MAX_QUEUE_SIZE","OTEL_BLRP_SCHEDULE_DELAY","OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_EVENT_COUNT_LIMIT","OTEL_SPAN_LINK_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","OTEL_EXPORTER_OTLP_TIMEOUT","OTEL_EXPORTER_OTLP_TRACES_TIMEOUT","OTEL_EXPORTER_OTLP_METRICS_TIMEOUT","OTEL_EXPORTER_OTLP_LOGS_TIMEOUT","OTEL_EXPORTER_JAEGER_AGENT_PORT"];function ne(e){return oe.indexOf(e)>-1}var se=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS","OTEL_SEMCONV_STABILITY_OPT_IN"];function ie(e){return se.indexOf(e)>-1}var y=1/0,C=128,ae=128,Ee=128,g={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:c.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:y,OTEL_ATTRIBUTE_COUNT_LIMIT:C,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:y,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:C,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:y,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:C,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:ae,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:Ee,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:A.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative",OTEL_SEMCONV_STABILITY_OPT_IN:[]};function _e(e,t,r){if(!(typeof r[e]>"u")){var o=String(r[e]);t[e]=o.toLowerCase()==="true"}}function Te(e,t,r,o,n){if(o===void 0&&(o=-1/0),n===void 0&&(n=1/0),typeof r[e]<"u"){var s=Number(r[e]);isNaN(s)||(s<o?t[e]=o:s>n?t[e]=n:t[e]=s)}}function pe(e,t,r,o){o===void 0&&(o=ee);var n=r[e];typeof n=="string"&&(t[e]=n.split(o).map(function(s){return s.trim()}))}var ue={ALL:c.ALL,VERBOSE:c.VERBOSE,DEBUG:c.DEBUG,INFO:c.INFO,WARN:c.WARN,ERROR:c.ERROR,NONE:c.NONE};function ce(e,t,r){var o=r[e];if(typeof o=="string"){var n=ue[o.toUpperCase()];n!=null&&(t[e]=n)}}function w(e){var t={};for(var r in g){var o=r;switch(o){case"OTEL_LOG_LEVEL":ce(o,t,e);break;default:if(re(o))_e(o,t,e);else if(ne(o))Te(o,t,e);else if(ie(o))pe(o,t,e);else{var n=e[o];typeof n<"u"&&n!==null&&(t[o]=String(n))}}}return t}function O(){var e=w(process.env);return Object.assign({},g,e)}function f(e){e.unref()}var m;(function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"})(m||(m={}));var G=(function(){function e(){var t=this;this._promise=new Promise(function(r,o){t._resolve=r,t._reject=o})}return Object.defineProperty(e.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),e.prototype.resolve=function(t){this._resolve(t)},e.prototype.reject=function(t){this._reject(t)},e})();var Le=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var o=r.call(e),n,s=[],a;try{for(;(t===void 0||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(i){a={error:i}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(a)throw a.error}}return s},de=function(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,s;o<n;o++)(s||!(o in t))&&(s||(s=Array.prototype.slice.call(t,0,o)),s[o]=t[o]);return e.concat(s||Array.prototype.slice.call(t))},v=(function(){function e(t,r){this._callback=t,this._that=r,this._isCalled=!1,this._deferred=new G}return Object.defineProperty(e.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),e.prototype.call=function(){for(var t,r=this,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];if(!this._isCalled){this._isCalled=!0;try{Promise.resolve((t=this._callback).call.apply(t,de([this._that],Le(o),!1))).then(function(s){return r._deferred.resolve(s)},function(s){return r._deferred.reject(s)})}catch(s){this._deferred.reject(s)}}return this._deferred.promise},e})();import{context as H,diag as b,TraceFlags as he}from"@opentelemetry/api";var F=(function(){function e(t,r){this._exporter=t,this._isExporting=!1,this._finishedSpans=[],this._droppedSpansCount=0;var o=O();this._maxExportBatchSize=typeof r?.maxExportBatchSize=="number"?r.maxExportBatchSize:o.OTEL_BSP_MAX_EXPORT_BATCH_SIZE,this._maxQueueSize=typeof r?.maxQueueSize=="number"?r.maxQueueSize:o.OTEL_BSP_MAX_QUEUE_SIZE,this._scheduledDelayMillis=typeof r?.scheduledDelayMillis=="number"?r.scheduledDelayMillis:o.OTEL_BSP_SCHEDULE_DELAY,this._exportTimeoutMillis=typeof r?.exportTimeoutMillis=="number"?r.exportTimeoutMillis:o.OTEL_BSP_EXPORT_TIMEOUT,this._shutdownOnce=new v(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(b.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}return e.prototype.forceFlush=function(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()},e.prototype.onStart=function(t,r){},e.prototype.onEnd=function(t){this._shutdownOnce.isCalled||(t.spanContext().traceFlags&he.SAMPLED)!==0&&this._addToBuffer(t)},e.prototype.shutdown=function(){return this._shutdownOnce.call()},e.prototype._shutdown=function(){var t=this;return Promise.resolve().then(function(){return t.onShutdown()}).then(function(){return t._flushAll()}).then(function(){return t._exporter.shutdown()})},e.prototype._addToBuffer=function(t){if(this._finishedSpans.length>=this._maxQueueSize){this._droppedSpansCount===0&&b.debug("maxQueueSize reached, dropping spans"),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(b.warn("Dropped "+this._droppedSpansCount+" spans because maxQueueSize reached"),this._droppedSpansCount=0),this._finishedSpans.push(t),this._maybeStartTimer()},e.prototype._flushAll=function(){var t=this;return new Promise(function(r,o){for(var n=[],s=Math.ceil(t._finishedSpans.length/t._maxExportBatchSize),a=0,i=s;a<i;a++)n.push(t._flushOneBatch());Promise.all(n).then(function(){r()}).catch(o)})},e.prototype._flushOneBatch=function(){var t=this;return this._clearTimer(),this._finishedSpans.length===0?Promise.resolve():new Promise(function(r,o){var n=setTimeout(function(){o(new Error("Timeout"))},t._exportTimeoutMillis);H.with(N(H.active()),function(){var s;t._finishedSpans.length<=t._maxExportBatchSize?(s=t._finishedSpans,t._finishedSpans=[]):s=t._finishedSpans.splice(0,t._maxExportBatchSize);for(var a=function(){return t._exporter.export(s,function(u){var x;clearTimeout(n),u.code===m.SUCCESS?r():o((x=u.error)!==null&&x!==void 0?x:new Error("BatchSpanProcessor: span export failed"))})},i=null,p=0,d=s.length;p<d;p++){var E=s[p];E.resource.asyncAttributesPending&&E.resource.waitForAsyncAttributes&&(i??(i=[]),i.push(E.resource.waitForAsyncAttributes()))}i===null?a():Promise.all(i).then(a,function(u){h(u),o(u)})})})},e.prototype._maybeStartTimer=function(){var t=this;if(!this._isExporting){var r=function(){t._isExporting=!0,t._flushOneBatch().finally(function(){t._isExporting=!1,t._finishedSpans.length>0&&(t._clearTimer(),t._maybeStartTimer())}).catch(function(o){t._isExporting=!1,h(o)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return r();this._timer===void 0&&(this._timer=setTimeout(function(){return r()},this._scheduledDelayMillis),f(this._timer))}},e.prototype._clearTimer=function(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)},e})();var Ae=(function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,n){o.__proto__=n}||function(o,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(o[s]=n[s])},e(t,r)};return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function o(){this.constructor=t}t.prototype=r===null?Object.create(r):(o.prototype=r.prototype,new o)}})(),R=(function(e){Ae(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.onShutdown=function(){},t})(F);import{Resource as V}from"@opentelemetry/resources";import{OTLPTraceExporter as Ue}from"@opentelemetry/exporter-trace-otlp-http";import{getNodeAutoInstrumentations as Be}from"@opentelemetry/auto-instrumentations-node";import{ProxyAgent as De,setGlobalDispatcher as we}from"undici";import{AsyncLocalStorage as Se}from"async_hooks";var S=new Se,P={},l=e=>({...e||{}}),_=()=>l(P),Ie=e=>{P=l(e)},xe=e=>{P={...P,...l(e)}},T=()=>S.getStore()?.requestAttributes||{},L=(e,t)=>{let r=S.getStore();if(!r)return;let o=t?.append===!1?l(e):{...r.requestAttributes,...l(e)};r.requestAttributes=o},Ne=e=>L(e),ye=(e,t,r)=>S.getStore()?(L(e,r),t()):I(()=>t(),e),I=(e,t)=>S.run({requestAttributes:l(t)},e);Ce.setLogger(new ge,ve.WARN);var Xe=process.env.OTEL_SERVICE_NAME||process.env.MAIN_MODULE||"unknown-service",Ge=process.env.OTEL_NAMESPACE||process.env.OTEL_SERVICE_NAMESPACE||process.env.MAIN_APP||"app",He=process.env.MAIN_ENV||process.env.NODE_ENV||"development",K=process.env.MAIN_MODULE||"unknown-module",Fe=(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318").replace(/\/$/,""),Ve=(process.env.ONELOG_EXPRESS_LAYERS||"").toLowerCase()==="true",q=process.env.MAIN_MODULE||K,M=[process.env.HTTPS_PROXY,process.env.https_proxy,process.env.HTTP_PROXY,process.env.http_proxy].find(e=>e&&e.trim().length>0);if(M)try{we(new De(M)),console.log(`[onelog] Proxy enabled for outbound traffic: ${M}`)}catch(e){console.error("[onelog] Failed to configure proxy agent:",e.message)}var Ke=V.default().merge(new V({"service.name":Xe,"service.namespace":Ge,"deployment.environment":He,"module.name":q})),U=class{constructor(t){this.moduleName=t}onStart(t){if(!t)return;let r=t.name||t._name||"";this.moduleName&&!r.startsWith(`[${this.moduleName}] `)&&t.updateName(`[${this.moduleName}] ${r}`),this.moduleName&&t.setAttribute("module.name",this.moduleName);let o={..._(),...T()};for(let[n,s]of Object.entries(o))s!==void 0&&t.setAttribute(n,s)}onEnd(t){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}},B=class{constructor(t){this.processors=t}onStart(t,r){for(let o of this.processors)o.onStart(t,r)}onEnd(t){for(let r of this.processors)r.onEnd(t)}shutdown(){return Promise.all(this.processors.map(t=>t.shutdown())).then(()=>{})}forceFlush(){return Promise.all(this.processors.map(t=>t.forceFlush())).then(()=>{})}},qe=Be({"@opentelemetry/instrumentation-http":{enabled:!0},"@opentelemetry/instrumentation-express":{enabled:!0,ignoreLayersType:Ve?[]:["middleware","request_handler"]},"@opentelemetry/instrumentation-undici":{enabled:!0},"@opentelemetry/instrumentation-ioredis":{enabled:!1},"@opentelemetry/instrumentation-redis":{enabled:!1},"@opentelemetry/instrumentation-fs":{enabled:!1},"@opentelemetry/instrumentation-dns":{enabled:!1},"@opentelemetry/instrumentation-net":{enabled:!1}}),ze=new Ue({url:`${Fe}/v1/traces`}),je=new B([new U(q),new R(ze)]),z=new Me({resource:Ke,instrumentations:[qe],spanProcessor:je}),Ye=Promise.resolve(z.start()).catch(e=>(console.error("Failed to start OpenTelemetry SDK",e),Promise.resolve())),j=async()=>{try{await z.shutdown()}catch(e){console.error("Error shutting down OpenTelemetry SDK",e)}};process.on("SIGTERM",j);process.on("SIGINT",j);var We=(e,t,r)=>{let o=r||process.env.MAIN_MODULE||K;e.use((n,s,a)=>{I(()=>{L({"module.name":o,"http.method":n.method,"http.target":n.path});let i=be.getActiveSpan();if(i){i.setAttribute("module.name",o),i.updateName(`[${o}] ${n.method} ${n.path}`);let p={..._(),...T()};for(let[d,E]of Object.entries(p))E!==void 0&&i.setAttribute(d,E)}t&&t.info({method:n.method,path:n.path,ip:n.ip},"Incoming request"),a()})})};import Qe from"pino";var Ze=["fatal","error","warn","info","debug","trace"],$e=e=>{let t=()=>({..._(),...T()});return new Proxy(e,{get(r,o,n){let s=Reflect.get(r,o,n);return typeof o=="string"&&Ze.includes(o)&&typeof s=="function"?(a,...i)=>{let p=t();return a&&typeof a=="object"&&!Array.isArray(a)?s.call(r,{...p,...a},...i):s.call(r,{...p},a,...i)}:s}})};function Je(){let e=process.env.MAIN_ENV||"development",t=process.env.MAIN_APP||"app",r=process.env.MAIN_MODULE||"unknown-module",n=Qe({transport:{targets:[{target:"pino-opentelemetry-transport",level:"info",options:{resourceAttributes:{"service.name":t,"service.namespace":e,"deployment.environment":e,"module.name":r,"host.name":Y("os").hostname()}}},{target:"pino-pretty",level:"debug",options:{colorize:!0,translateTime:"HH:MM:ss Z",ignore:"pid,hostname"}}]}}).child({env:e,app:t,module:r});return $e(n)}import{trace as ke,SpanStatusCode as et}from"@opentelemetry/api";var tt=e=>(t,r,o,n)=>{let s={..._(),...T()};e&&e.error({...s,error:t.message,stack:t.stack,path:r.path},"Unhandled error");let a=ke.getActiveSpan();if(a&&(a.recordException(t),a.setStatus({code:et.ERROR,message:t.message})),o.headersSent)return n(t);o.status(500).json({error:t.message,attributes:s,module:process.env.MAIN_MODULE||"unknown-module"})};async function rt(e,t={},r,o={}){let n={...t},s=(n.method||"GET").toString().toUpperCase();n.body&&typeof n.body!="string"&&!(n.body instanceof Buffer)&&!(n.body instanceof ArrayBuffer)&&(n.body=JSON.stringify(n.body),n.headers={"Content-Type":"application/json",...n.headers||{}});let a={..._(),...T(),...o};r&&r.info({...a,url:e,method:s},"HTTP call start");try{let i=await fetch(e,n),E=(i.headers.get("content-type")||"").includes("application/json")?await i.json().catch(()=>null):await i.text().catch(()=>null);if(!i.ok){let u=new Error(`HTTP ${i.status} ${i.statusText||""}`.trim());throw u.status=i.status,u.data=E,r&&r.error({...a,url:e,method:s,status:i.status,data:E},"HTTP call failed"),u}return r&&r.info({...a,url:e,method:s,status:i.status},"HTTP call success"),E}catch(i){throw r&&r.error({...a,url:e,method:s,error:i.message},"HTTP call error"),i}}export{Je as createLogger,tt as errorMiddleware,_ as getGlobalAttributes,T as getRequestAttributes,rt as httpCall,We as instrumentApp,xe as mergeGlobalAttributes,Ne as mergeRequestAttributes,I as runWithRequestContext,Ye as sdkStartPromise,Ie as setGlobalAttributes,L as setRequestAttributes,ye as withRequestAttributes};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/tracing.ts","../src/logger.ts","../src/exceptions.ts","../src/http-caller.ts"],"sourcesContent":["import { diag, DiagConsoleLogger, DiagLogLevel, trace, Span } from '@opentelemetry/api';\nimport { NodeSDK } from '@opentelemetry/sdk-node';\nimport { SpanProcessor, ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport { Resource } from '@opentelemetry/resources';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\nimport { ProxyAgent, setGlobalDispatcher } from 'undici';\nimport type { Application, Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\n\ndiag.setLogger(new DiagConsoleLogger(), DiagLogLevel.WARN);\n\nconst serviceName =\n process.env.OTEL_SERVICE_NAME ||\n process.env.MAIN_MODULE ||\n 'unknown-service';\nconst serviceNamespace =\n process.env.OTEL_NAMESPACE ||\n process.env.OTEL_SERVICE_NAMESPACE ||\n process.env.MAIN_APP ||\n 'app';\nconst environment = process.env.MAIN_ENV || process.env.NODE_ENV || 'development';\nconst moduleName = process.env.MAIN_MODULE || 'unknown-module';\nconst otlpEndpoint = (process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318').replace(/\\/$/, '');\nconst expressLayersEnabled = (process.env.ONELOG_EXPRESS_LAYERS || '').toLowerCase() === 'true';\nconst moduleLabel = process.env.MAIN_MODULE || moduleName;\n\n// Optional proxy support for environments with HTTP(S)_PROXY set\nconst proxyUrl = [process.env.HTTPS_PROXY, process.env.https_proxy, process.env.HTTP_PROXY, process.env.http_proxy]\n .find((v) => v && v.trim().length > 0);\n\nif (proxyUrl) {\n try {\n setGlobalDispatcher(new ProxyAgent(proxyUrl));\n // eslint-disable-next-line no-console\n console.log(`[onelog] Proxy enabled for outbound traffic: ${proxyUrl}`);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to configure proxy agent:', (err as Error).message);\n }\n}\n\nconst resource = Resource.default().merge(\n new Resource({\n 'service.name': serviceName,\n 'service.namespace': serviceNamespace,\n 'deployment.environment': environment,\n 'module.name': moduleLabel,\n }),\n);\n\nclass ModuleNameSpanProcessor implements SpanProcessor {\n constructor(private readonly moduleName: string) {}\n onStart(span: Span): void {\n if (!span) return;\n const currentName = (span as any).name || (span as any)._name || '';\n if (this.moduleName && !currentName.startsWith(`[${this.moduleName}] `)) {\n span.updateName(`[${this.moduleName}] ${currentName}`);\n }\n if (this.moduleName) {\n span.setAttribute('module.name', this.moduleName);\n }\n }\n onEnd(_span: ReadableSpan): void {\n // no-op\n }\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\nconst instrumentations = getNodeAutoInstrumentations({\n '@opentelemetry/instrumentation-http': {\n enabled: true,\n },\n '@opentelemetry/instrumentation-express': {\n enabled: true,\n ignoreLayersType: expressLayersEnabled ? [] : (['middleware', 'request_handler'] as any),\n },\n '@opentelemetry/instrumentation-undici': {\n enabled: true,\n },\n // Redis instrumentation is noisy in our workloads; keep it off by default\n '@opentelemetry/instrumentation-ioredis': { enabled: false },\n '@opentelemetry/instrumentation-redis': { enabled: false },\n '@opentelemetry/instrumentation-fs': { enabled: false },\n '@opentelemetry/instrumentation-dns': { enabled: false },\n '@opentelemetry/instrumentation-net': { enabled: false },\n});\n\nconst sdk = new NodeSDK({\n traceExporter: new OTLPTraceExporter({\n url: `${otlpEndpoint}/v1/traces`,\n }),\n resource,\n instrumentations: [instrumentations],\n spanProcessor: new ModuleNameSpanProcessor(moduleLabel),\n});\n\nexport const sdkStartPromise = Promise.resolve(sdk.start()).catch((error) => {\n console.error('Failed to start OpenTelemetry SDK', error);\n return Promise.resolve();\n});\n\nconst shutdown = async () => {\n try {\n await sdk.shutdown();\n } catch (error) {\n console.error('Error shutting down OpenTelemetry SDK', error);\n }\n};\n\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n\nexport const instrumentApp = (app: Application, logger?: Logger, customModuleName?: string) => {\n const moduleLabel = customModuleName || process.env.MAIN_MODULE || moduleName;\n app.use((req: Request, _res: Response, next: NextFunction) => {\n const span = trace.getActiveSpan();\n if (span) {\n span.setAttribute('module.name', moduleLabel);\n span.updateName(`[${moduleLabel}] ${req.method} ${req.path}`);\n }\n if (logger) {\n logger.info(\n {\n method: req.method,\n path: req.path,\n ip: req.ip,\n },\n 'Incoming request',\n );\n }\n next();\n });\n};\n","import pino from 'pino';\n\nexport function createLogger() {\n const mainEnv = process.env.MAIN_ENV || 'development';\n const mainApp = process.env.MAIN_APP || 'app';\n const mainModule = process.env.MAIN_MODULE || 'unknown-module';\n\n const logger = pino({\n transport: {\n targets: [\n {\n target: 'pino-opentelemetry-transport',\n level: 'info',\n options: {\n resourceAttributes: {\n 'service.name': mainApp,\n 'service.namespace': mainEnv,\n 'deployment.environment': mainEnv,\n 'module.name': mainModule,\n 'host.name': require('os').hostname(),\n },\n },\n },\n {\n target: 'pino-pretty',\n level: 'debug',\n options: {\n colorize: true,\n translateTime: 'HH:MM:ss Z',\n ignore: 'pid,hostname',\n },\n },\n ],\n },\n });\n\n return logger.child({\n env: mainEnv,\n app: mainApp,\n module: mainModule,\n });\n}\n","import { trace, SpanStatusCode } from '@opentelemetry/api';\nimport type { Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\n\nexport const errorMiddleware =\n (logger?: Logger) =>\n (err: Error, req: Request, res: Response, next: NextFunction) => {\n if (logger) {\n logger.error(\n {\n error: err.message,\n stack: err.stack,\n path: req.path,\n },\n 'Unhandled error',\n );\n }\n\n const span = trace.getActiveSpan();\n if (span) {\n span.recordException(err);\n span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });\n }\n\n if (res.headersSent) {\n return next(err);\n }\n\n res.status(500).json({\n error: err.message,\n module: process.env.MAIN_MODULE || 'unknown-module',\n });\n };\n","export interface HttpCallContext {\n [key: string]: any;\n}\n\nexport interface HttpCallOptions extends RequestInit {\n body?: any;\n}\n\nexport async function httpCall(\n url: string,\n options: HttpCallOptions = {},\n logger?: { info: Function; error: Function },\n logContext: HttpCallContext = {},\n) {\n const fetchOptions: RequestInit = { ...options };\n const method = (fetchOptions.method || 'GET').toString().toUpperCase();\n\n if (\n fetchOptions.body &&\n typeof fetchOptions.body !== 'string' &&\n !(fetchOptions.body instanceof Buffer) &&\n !(fetchOptions.body instanceof ArrayBuffer)\n ) {\n fetchOptions.body = JSON.stringify(fetchOptions.body);\n fetchOptions.headers = {\n 'Content-Type': 'application/json',\n ...(fetchOptions.headers || {}),\n };\n }\n\n if (logger) {\n logger.info({ ...logContext, url, method }, 'HTTP call start');\n }\n\n try {\n const res = await fetch(url, fetchOptions);\n const contentType = res.headers.get('content-type') || '';\n const isJson = contentType.includes('application/json');\n const data = isJson ? await res.json().catch(() => null) : await res.text().catch(() => null);\n\n if (!res.ok) {\n const error = new Error(`HTTP ${res.status} ${res.statusText || ''}`.trim());\n (error as any).status = res.status;\n (error as any).data = data;\n if (logger) {\n logger.error({ ...logContext, url, method, status: res.status, data }, 'HTTP call failed');\n }\n throw error;\n }\n\n if (logger) {\n logger.info({ ...logContext, url, method, status: res.status }, 'HTTP call success');\n }\n\n return data;\n } catch (err: any) {\n if (logger) {\n logger.error({ ...logContext, url, method, error: err.message }, 'HTTP call error');\n }\n throw err;\n }\n}\n"],"mappings":"yPAAA,OAAS,QAAAA,EAAM,qBAAAC,EAAmB,gBAAAC,EAAc,SAAAC,MAAmB,qBACnE,OAAS,WAAAC,MAAe,0BAExB,OAAS,YAAAC,MAAgB,2BACzB,OAAS,qBAAAC,MAAyB,0CAClC,OAAS,+BAAAC,MAAmC,4CAC5C,OAAS,cAAAC,EAAY,uBAAAC,MAA2B,SAIhDT,EAAK,UAAU,IAAIC,EAAqBC,EAAa,IAAI,EAEzD,IAAMQ,EACJ,Q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S,EAAE,YAAY,EAGnEA,EAAa,MACb,OAAOA,EAAa,MAAS,UAC7B,EAAEA,EAAa,gBAAgB,SAC/B,EAAEA,EAAa,gBAAgB,eAE/BA,EAAa,KAAO,KAAK,UAAUA,EAAa,IAAI,EACpDA,EAAa,QAAU,CACrB,eAAgB,mBAChB,GAAIA,EAAa,SAAW,CAAC,CAC/B,GAGEF,GACFA,EAAO,KAAK,CAAE,GAAGC,EAAY,IAAAH,EAAK,OAAAK,CAAO,EAAG,iBAAiB,EAG/D,GAAI,CACF,IAAMC,EAAM,MAAM,MAAMN,EAAKI,CAAY,EAGnCG,GAFcD,EAAI,QAAQ,IAAI,cAAc,GAAK,IAC5B,SAAS,kBAAkB,EAChC,MAAMA,EAAI,KAAK,EAAE,MAAM,IAAM,IAAI,EAAI,MAAMA,EAAI,KAAK,EAAE,MAAM,IAAM,IAAI,EAE5F,GAAI,CAACA,EAAI,GAAI,CACX,IAAME,EAAQ,IAAI,MAAM,QAAQF,EAAI,MAAM,IAAIA,EAAI,YAAc,EAAE,GAAG,KAAK,CAAC,EAC3E,MAACE,EAAc,OAASF,EAAI,OAC3BE,EAAc,KAAOD,EAClBL,GACFA,EAAO,MAAM,CAAE,GAAGC,EAAY,IAAAH,EAAK,OAAAK,EAAQ,OAAQC,EAAI,OAAQ,KAAAC,CAAK,EAAG,kBAAkB,EAErFC,CACR,CAEA,OAAIN,GACFA,EAAO,KAAK,CAAE,GAAGC,EAAY,IAAAH,EAAK,OAAAK,EAAQ,OAAQC,EAAI,MAAO,EAAG,mBAAmB,EAG9EC,CACT,OAASE,EAAU,CACjB,MAAIP,GACFA,EAAO,MAAM,CAAE,GAAGC,EAAY,IAAAH,EAAK,OAAAK,EAAQ,MAAOI,EAAI,OAAQ,EAAG,iBAAiB,EAE9EA,CACR,CACF","names":["diag","DiagConsoleLogger","DiagLogLevel","trace","NodeSDK","Resource","OTLPTraceExporter","getNodeAutoInstrumentations","ProxyAgent","setGlobalDispatcher","serviceName","serviceNamespace","environment","moduleName","otlpEndpoint","expressLayersEnabled","moduleLabel","proxyUrl","v","err","resource","ModuleNameSpanProcessor","span","currentName","_span","instrumentations","sdk","sdkStartPromise","error","shutdown","instrumentApp","app","logger","customModuleName","req","_res","next","pino","createLogger","mainEnv","mainApp","mainModule","trace","SpanStatusCode","errorMiddleware","logger","err","req","res","next","span","httpCall","url","options","logger","logContext","fetchOptions","method","res","data","error","err"]}
|
|
1
|
+
{"version":3,"sources":["../src/tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/logging-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/common/global-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/sampling.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/environment.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/platform/node/timer-util.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/ExportResult.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/promise.ts","../node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/core/src/utils/callback.ts","../node_modules/@opentelemetry/sdk-trace-base/src/export/BatchSpanProcessorBase.ts","../node_modules/@opentelemetry/sdk-trace-base/src/platform/node/export/BatchSpanProcessor.ts","../src/attributes.ts","../src/logger.ts","../src/exceptions.ts","../src/http-caller.ts"],"sourcesContent":["import { diag, DiagConsoleLogger, DiagLogLevel, trace } from '@opentelemetry/api';\nimport { NodeSDK } from '@opentelemetry/sdk-node';\nimport { SpanProcessor, ReadableSpan, BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';\nimport { Resource } from '@opentelemetry/resources';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\nimport { ProxyAgent, setGlobalDispatcher } from 'undici';\nimport type { Application, Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\nimport {\n getGlobalAttributes,\n getRequestAttributes,\n runWithRequestContext,\n setRequestAttributes,\n} from './attributes.js';\n\ndiag.setLogger(new DiagConsoleLogger(), DiagLogLevel.WARN);\n\nconst serviceName =\n process.env.OTEL_SERVICE_NAME ||\n process.env.MAIN_MODULE ||\n 'unknown-service';\nconst serviceNamespace =\n process.env.OTEL_NAMESPACE ||\n process.env.OTEL_SERVICE_NAMESPACE ||\n process.env.MAIN_APP ||\n 'app';\nconst environment = process.env.MAIN_ENV || process.env.NODE_ENV || 'development';\nconst moduleName = process.env.MAIN_MODULE || 'unknown-module';\nconst otlpEndpoint = (process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318').replace(/\\/$/, '');\nconst expressLayersEnabled = (process.env.ONELOG_EXPRESS_LAYERS || '').toLowerCase() === 'true';\nconst moduleLabel = process.env.MAIN_MODULE || moduleName;\n\n// Optional proxy support for environments with HTTP(S)_PROXY set\nconst proxyUrl = [process.env.HTTPS_PROXY, process.env.https_proxy, process.env.HTTP_PROXY, process.env.http_proxy]\n .find((v) => v && v.trim().length > 0);\n\nif (proxyUrl) {\n try {\n setGlobalDispatcher(new ProxyAgent(proxyUrl));\n // eslint-disable-next-line no-console\n console.log(`[onelog] Proxy enabled for outbound traffic: ${proxyUrl}`);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[onelog] Failed to configure proxy agent:', (err as Error).message);\n }\n}\n\nconst resource = Resource.default().merge(\n new Resource({\n 'service.name': serviceName,\n 'service.namespace': serviceNamespace,\n 'deployment.environment': environment,\n 'module.name': moduleLabel,\n }),\n);\n\nclass ModuleNameSpanProcessor implements SpanProcessor {\n constructor(private readonly moduleName: string) {}\n onStart(span: any): void {\n if (!span) return;\n const currentName = (span as any).name || (span as any)._name || '';\n if (this.moduleName && !currentName.startsWith(`[${this.moduleName}] `)) {\n span.updateName(`[${this.moduleName}] ${currentName}`);\n }\n if (this.moduleName) {\n span.setAttribute('module.name', this.moduleName);\n }\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(dynamicAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n onEnd(_span: ReadableSpan): void {\n // no-op\n }\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\nclass CombinedSpanProcessor implements SpanProcessor {\n constructor(private readonly processors: SpanProcessor[]) {}\n onStart(span: any, ctx?: any): void {\n for (const p of this.processors) p.onStart(span as any, ctx);\n }\n onEnd(span: ReadableSpan): void {\n for (const p of this.processors) p.onEnd(span);\n }\n shutdown(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.shutdown())).then(() => undefined);\n }\n forceFlush(): Promise<void> {\n return Promise.all(this.processors.map((p) => p.forceFlush())).then(() => undefined);\n }\n}\n\nconst instrumentations = getNodeAutoInstrumentations({\n '@opentelemetry/instrumentation-http': {\n enabled: true,\n },\n '@opentelemetry/instrumentation-express': {\n enabled: true,\n ignoreLayersType: expressLayersEnabled ? [] : (['middleware', 'request_handler'] as any),\n },\n '@opentelemetry/instrumentation-undici': {\n enabled: true,\n },\n // Redis instrumentation is noisy in our workloads; keep it off by default\n '@opentelemetry/instrumentation-ioredis': { enabled: false },\n '@opentelemetry/instrumentation-redis': { enabled: false },\n '@opentelemetry/instrumentation-fs': { enabled: false },\n '@opentelemetry/instrumentation-dns': { enabled: false },\n '@opentelemetry/instrumentation-net': { enabled: false },\n});\n\nconst exporter = new OTLPTraceExporter({\n url: `${otlpEndpoint}/v1/traces`,\n});\n\nconst spanProcessor = new CombinedSpanProcessor([\n new ModuleNameSpanProcessor(moduleLabel),\n new BatchSpanProcessor(exporter),\n]);\n\nconst sdk = new NodeSDK({\n resource,\n instrumentations: [instrumentations],\n spanProcessor,\n});\n\nexport const sdkStartPromise = Promise.resolve(sdk.start()).catch((error) => {\n console.error('Failed to start OpenTelemetry SDK', error);\n return Promise.resolve();\n});\n\nconst shutdown = async () => {\n try {\n await sdk.shutdown();\n } catch (error) {\n console.error('Error shutting down OpenTelemetry SDK', error);\n }\n};\n\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);\n\nexport const instrumentApp = (app: Application, logger?: Logger, customModuleName?: string) => {\n const moduleLabel = customModuleName || process.env.MAIN_MODULE || moduleName;\n app.use((req: Request, _res: Response, next: NextFunction) => {\n runWithRequestContext(() => {\n setRequestAttributes({\n 'module.name': moduleLabel,\n 'http.method': req.method,\n 'http.target': req.path,\n });\n\n const span = trace.getActiveSpan();\n if (span) {\n span.setAttribute('module.name', moduleLabel);\n span.updateName(`[${moduleLabel}] ${req.method} ${req.path}`);\n const requestAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n for (const [key, value] of Object.entries(requestAttributes)) {\n if (value === undefined) continue;\n span.setAttribute(key, value);\n }\n }\n if (logger) {\n logger.info(\n {\n method: req.method,\n path: req.path,\n ip: req.ip,\n },\n 'Incoming request',\n );\n }\n next();\n });\n });\n};\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag, Exception } from '@opentelemetry/api';\nimport { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n const result = {} as Record<string, string>;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogLevel } from '@opentelemetry/api';\nimport { TracesSamplerValues } from './sampling';\n\nconst DEFAULT_LIST_SEPARATOR = ',';\n\n/**\n * Environment interface to define all names\n */\n\nconst ENVIRONMENT_BOOLEAN_KEYS = ['OTEL_SDK_DISABLED'] as const;\n\ntype ENVIRONMENT_BOOLEANS = {\n [K in (typeof ENVIRONMENT_BOOLEAN_KEYS)[number]]?: boolean;\n};\n\nfunction isEnvVarABoolean(key: unknown): key is keyof ENVIRONMENT_BOOLEANS {\n return (\n ENVIRONMENT_BOOLEAN_KEYS.indexOf(key as keyof ENVIRONMENT_BOOLEANS) > -1\n );\n}\n\nconst ENVIRONMENT_NUMBERS_KEYS = [\n 'OTEL_BSP_EXPORT_TIMEOUT',\n 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BSP_MAX_QUEUE_SIZE',\n 'OTEL_BSP_SCHEDULE_DELAY',\n 'OTEL_BLRP_EXPORT_TIMEOUT',\n 'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BLRP_MAX_QUEUE_SIZE',\n 'OTEL_BLRP_SCHEDULE_DELAY',\n 'OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_LINK_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT',\n 'OTEL_EXPORTER_OTLP_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_TRACES_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_METRICS_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_LOGS_TIMEOUT',\n 'OTEL_EXPORTER_JAEGER_AGENT_PORT',\n] as const;\n\ntype ENVIRONMENT_NUMBERS = {\n [K in (typeof ENVIRONMENT_NUMBERS_KEYS)[number]]?: number;\n};\n\nfunction isEnvVarANumber(key: unknown): key is keyof ENVIRONMENT_NUMBERS {\n return (\n ENVIRONMENT_NUMBERS_KEYS.indexOf(key as keyof ENVIRONMENT_NUMBERS) > -1\n );\n}\n\nconst ENVIRONMENT_LISTS_KEYS = [\n 'OTEL_NO_PATCH_MODULES',\n 'OTEL_PROPAGATORS',\n 'OTEL_SEMCONV_STABILITY_OPT_IN',\n] as const;\n\ntype ENVIRONMENT_LISTS = {\n [K in (typeof ENVIRONMENT_LISTS_KEYS)[number]]?: string[];\n};\n\nfunction isEnvVarAList(key: unknown): key is keyof ENVIRONMENT_LISTS {\n return ENVIRONMENT_LISTS_KEYS.indexOf(key as keyof ENVIRONMENT_LISTS) > -1;\n}\n\nexport type ENVIRONMENT = {\n CONTAINER_NAME?: string;\n ECS_CONTAINER_METADATA_URI_V4?: string;\n ECS_CONTAINER_METADATA_URI?: string;\n HOSTNAME?: string;\n KUBERNETES_SERVICE_HOST?: string;\n NAMESPACE?: string;\n OTEL_EXPORTER_JAEGER_AGENT_HOST?: string;\n OTEL_EXPORTER_JAEGER_ENDPOINT?: string;\n OTEL_EXPORTER_JAEGER_PASSWORD?: string;\n OTEL_EXPORTER_JAEGER_USER?: string;\n OTEL_EXPORTER_OTLP_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_HEADERS?: string;\n OTEL_EXPORTER_OTLP_TRACES_HEADERS?: string;\n OTEL_EXPORTER_OTLP_METRICS_HEADERS?: string;\n OTEL_EXPORTER_OTLP_LOGS_HEADERS?: string;\n OTEL_EXPORTER_ZIPKIN_ENDPOINT?: string;\n OTEL_LOG_LEVEL?: DiagLogLevel;\n OTEL_RESOURCE_ATTRIBUTES?: string;\n OTEL_SERVICE_NAME?: string;\n OTEL_TRACES_EXPORTER?: string;\n OTEL_TRACES_SAMPLER_ARG?: string;\n OTEL_TRACES_SAMPLER?: string;\n OTEL_LOGS_EXPORTER?: string;\n OTEL_EXPORTER_OTLP_INSECURE?: string;\n OTEL_EXPORTER_OTLP_TRACES_INSECURE?: string;\n OTEL_EXPORTER_OTLP_METRICS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_LOGS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE?: string;\n} & ENVIRONMENT_BOOLEANS &\n ENVIRONMENT_NUMBERS &\n ENVIRONMENT_LISTS;\n\nexport type RAW_ENVIRONMENT = {\n [key: string]: string | number | undefined | string[];\n};\n\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\n\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 128;\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 128;\n\n/**\n * Default environment variables\n */\nexport const DEFAULT_ENVIRONMENT: Required<ENVIRONMENT> = {\n OTEL_SDK_DISABLED: false,\n CONTAINER_NAME: '',\n ECS_CONTAINER_METADATA_URI_V4: '',\n ECS_CONTAINER_METADATA_URI: '',\n HOSTNAME: '',\n KUBERNETES_SERVICE_HOST: '',\n NAMESPACE: '',\n OTEL_BSP_EXPORT_TIMEOUT: 30000,\n OTEL_BSP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BSP_MAX_QUEUE_SIZE: 2048,\n OTEL_BSP_SCHEDULE_DELAY: 5000,\n OTEL_BLRP_EXPORT_TIMEOUT: 30000,\n OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BLRP_MAX_QUEUE_SIZE: 2048,\n OTEL_BLRP_SCHEDULE_DELAY: 5000,\n OTEL_EXPORTER_JAEGER_AGENT_HOST: '',\n OTEL_EXPORTER_JAEGER_AGENT_PORT: 6832,\n OTEL_EXPORTER_JAEGER_ENDPOINT: '',\n OTEL_EXPORTER_JAEGER_PASSWORD: '',\n OTEL_EXPORTER_JAEGER_USER: '',\n OTEL_EXPORTER_OTLP_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_HEADERS: '',\n OTEL_EXPORTER_OTLP_TRACES_HEADERS: '',\n OTEL_EXPORTER_OTLP_METRICS_HEADERS: '',\n OTEL_EXPORTER_OTLP_LOGS_HEADERS: '',\n OTEL_EXPORTER_OTLP_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_TRACES_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_METRICS_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_LOGS_TIMEOUT: 10000,\n OTEL_EXPORTER_ZIPKIN_ENDPOINT: 'http://localhost:9411/api/v2/spans',\n OTEL_LOG_LEVEL: DiagLogLevel.INFO,\n OTEL_NO_PATCH_MODULES: [],\n OTEL_PROPAGATORS: ['tracecontext', 'baggage'],\n OTEL_RESOURCE_ATTRIBUTES: '',\n OTEL_SERVICE_NAME: '',\n OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_EVENT_COUNT_LIMIT: 128,\n OTEL_SPAN_LINK_COUNT_LIMIT: 128,\n OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n OTEL_TRACES_EXPORTER: '',\n OTEL_TRACES_SAMPLER: TracesSamplerValues.ParentBasedAlwaysOn,\n OTEL_TRACES_SAMPLER_ARG: '',\n OTEL_LOGS_EXPORTER: '',\n OTEL_EXPORTER_OTLP_INSECURE: '',\n OTEL_EXPORTER_OTLP_TRACES_INSECURE: '',\n OTEL_EXPORTER_OTLP_METRICS_INSECURE: '',\n OTEL_EXPORTER_OTLP_LOGS_INSECURE: '',\n OTEL_EXPORTER_OTLP_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: 'cumulative',\n OTEL_SEMCONV_STABILITY_OPT_IN: [],\n};\n\n/**\n * @param key\n * @param environment\n * @param values\n */\nfunction parseBoolean(\n key: keyof ENVIRONMENT_BOOLEANS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n if (typeof values[key] === 'undefined') {\n return;\n }\n\n const value = String(values[key]);\n // support case-insensitive \"true\"\n environment[key] = value.toLowerCase() === 'true';\n}\n\n/**\n * Parses a variable as number with number validation\n * @param name\n * @param environment\n * @param values\n * @param min\n * @param max\n */\nfunction parseNumber(\n name: keyof ENVIRONMENT_NUMBERS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT,\n min = -Infinity,\n max = Infinity\n) {\n if (typeof values[name] !== 'undefined') {\n const value = Number(values[name] as string);\n if (!isNaN(value)) {\n if (value < min) {\n environment[name] = min;\n } else if (value > max) {\n environment[name] = max;\n } else {\n environment[name] = value;\n }\n }\n }\n}\n\n/**\n * Parses list-like strings from input into output.\n * @param name\n * @param environment\n * @param values\n * @param separator\n */\nfunction parseStringList(\n name: keyof ENVIRONMENT_LISTS,\n output: ENVIRONMENT,\n input: RAW_ENVIRONMENT,\n separator = DEFAULT_LIST_SEPARATOR\n) {\n const givenValue = input[name];\n if (typeof givenValue === 'string') {\n output[name] = givenValue.split(separator).map(v => v.trim());\n }\n}\n\n// The support string -> DiagLogLevel mappings\nconst logLevelMap: { [key: string]: DiagLogLevel } = {\n ALL: DiagLogLevel.ALL,\n VERBOSE: DiagLogLevel.VERBOSE,\n DEBUG: DiagLogLevel.DEBUG,\n INFO: DiagLogLevel.INFO,\n WARN: DiagLogLevel.WARN,\n ERROR: DiagLogLevel.ERROR,\n NONE: DiagLogLevel.NONE,\n};\n\n/**\n * Environmentally sets log level if valid log level string is provided\n * @param key\n * @param environment\n * @param values\n */\nfunction setLogLevelFromEnv(\n key: keyof ENVIRONMENT,\n environment: RAW_ENVIRONMENT | ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n const value = values[key];\n if (typeof value === 'string') {\n const theLevel = logLevelMap[value.toUpperCase()];\n if (theLevel != null) {\n environment[key] = theLevel;\n }\n }\n}\n\n/**\n * Parses environment values\n * @param values\n */\nexport function parseEnvironment(values: RAW_ENVIRONMENT): ENVIRONMENT {\n const environment: ENVIRONMENT = {};\n\n for (const env in DEFAULT_ENVIRONMENT) {\n const key = env as keyof ENVIRONMENT;\n\n switch (key) {\n case 'OTEL_LOG_LEVEL':\n setLogLevelFromEnv(key, environment, values);\n break;\n\n default:\n if (isEnvVarABoolean(key)) {\n parseBoolean(key, environment, values);\n } else if (isEnvVarANumber(key)) {\n parseNumber(key, environment, values);\n } else if (isEnvVarAList(key)) {\n parseStringList(key, environment, values);\n } else {\n const value = values[key];\n if (typeof value !== 'undefined' && value !== null) {\n environment[key] = String(value);\n }\n }\n }\n }\n\n return environment;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DEFAULT_ENVIRONMENT,\n ENVIRONMENT,\n RAW_ENVIRONMENT,\n parseEnvironment,\n} from '../../utils/environment';\n\n/**\n * Gets the environment variables\n */\nexport function getEnv(): Required<ENVIRONMENT> {\n const processEnv = parseEnvironment(process.env as RAW_ENVIRONMENT);\n return Object.assign({}, DEFAULT_ENVIRONMENT, processEnv);\n}\n\nexport function getEnvWithoutDefaults(): ENVIRONMENT {\n return parseEnvironment(process.env as RAW_ENVIRONMENT);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport function unrefTimer(timer: NodeJS.Timer): void {\n timer.unref();\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred<R>();\n constructor(\n private _callback: T,\n private _that: This\n ) {}\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters<T>): Promise<R> {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { context, Context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getEnv,\n globalErrorHandler,\n suppressTracing,\n unrefTimer,\n} from '@opentelemetry/core';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\nimport { BufferConfig } from '../types';\nimport { ReadableSpan } from './ReadableSpan';\nimport { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(\n private readonly _exporter: SpanExporter,\n config?: T\n ) {\n const env = getEnv();\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE;\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : env.OTEL_BSP_MAX_QUEUE_SIZE;\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : env.OTEL_BSP_SCHEDULE_DELAY;\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : env.OTEL_BSP_EXPORT_TIMEOUT;\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n unrefTimer(this._timer);\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\n\nexport type AttributeMap = Record<string, any>;\n\ntype RequestAttributeContext = {\n requestAttributes: AttributeMap;\n};\n\nconst requestAttributeStorage = new AsyncLocalStorage<RequestAttributeContext>();\n\nlet globalAttributes: AttributeMap = {};\n\nconst clone = (attrs?: AttributeMap) => ({ ...(attrs || {}) });\n\nexport const getGlobalAttributes = (): AttributeMap => clone(globalAttributes);\n\nexport const setGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = clone(attrs);\n};\n\nexport const mergeGlobalAttributes = (attrs: AttributeMap) => {\n globalAttributes = { ...globalAttributes, ...clone(attrs) };\n};\n\nexport const getRequestAttributes = (): AttributeMap => {\n const store = requestAttributeStorage.getStore();\n return store?.requestAttributes || {};\n};\n\nexport const setRequestAttributes = (attrs: AttributeMap, options?: { append?: boolean }) => {\n const store = requestAttributeStorage.getStore();\n if (!store) return;\n\n const nextAttributes =\n options?.append === false ? clone(attrs) : { ...store.requestAttributes, ...clone(attrs) };\n store.requestAttributes = nextAttributes;\n};\n\nexport const mergeRequestAttributes = (attrs: AttributeMap) => setRequestAttributes(attrs);\n\nexport const withRequestAttributes = <T>(\n attrs: AttributeMap,\n fn: () => T,\n options?: { append?: boolean },\n): T => {\n const store = requestAttributeStorage.getStore();\n if (!store) {\n return runWithRequestContext(() => fn(), attrs);\n }\n setRequestAttributes(attrs, options);\n return fn();\n};\n\nexport const runWithRequestContext = <T>(fn: () => T, initialAttributes?: AttributeMap): T => {\n return requestAttributeStorage.run(\n {\n requestAttributes: clone(initialAttributes),\n },\n fn,\n );\n};\n","import pino, { Logger } from 'pino';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nconst levelMethods = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'] as const;\n\nconst wrapWithDynamicAttributes = (logger: Logger): Logger => {\n const buildAttrs = () => ({ ...getGlobalAttributes(), ...getRequestAttributes() });\n\n return new Proxy(logger, {\n get(target, prop, receiver) {\n const original = Reflect.get(target, prop, receiver);\n if (typeof prop === 'string' && levelMethods.includes(prop as any) && typeof original === 'function') {\n return (firstArg?: any, ...rest: any[]) => {\n const attrs = buildAttrs();\n if (firstArg && typeof firstArg === 'object' && !Array.isArray(firstArg)) {\n return (original as any).call(target, { ...attrs, ...firstArg }, ...rest);\n }\n return (original as any).call(target, { ...attrs }, firstArg, ...rest);\n };\n }\n return original;\n },\n });\n};\n\nexport function createLogger() {\n const mainEnv = process.env.MAIN_ENV || 'development';\n const mainApp = process.env.MAIN_APP || 'app';\n const mainModule = process.env.MAIN_MODULE || 'unknown-module';\n\n const logger = pino({\n transport: {\n targets: [\n {\n target: 'pino-opentelemetry-transport',\n level: 'info',\n options: {\n resourceAttributes: {\n 'service.name': mainApp,\n 'service.namespace': mainEnv,\n 'deployment.environment': mainEnv,\n 'module.name': mainModule,\n 'host.name': require('os').hostname(),\n },\n },\n },\n {\n target: 'pino-pretty',\n level: 'debug',\n options: {\n colorize: true,\n translateTime: 'HH:MM:ss Z',\n ignore: 'pid,hostname',\n },\n },\n ],\n },\n });\n\n const base = logger.child({\n env: mainEnv,\n app: mainApp,\n module: mainModule,\n });\n\n return wrapWithDynamicAttributes(base);\n}\n","import { trace, SpanStatusCode } from '@opentelemetry/api';\nimport { getGlobalAttributes, getRequestAttributes } from './attributes.js';\nimport type { Request, Response, NextFunction } from 'express';\nimport type { Logger } from 'pino';\n\nexport const errorMiddleware =\n (logger?: Logger) =>\n (err: Error, req: Request, res: Response, next: NextFunction) => {\n const dynamicAttributes = { ...getGlobalAttributes(), ...getRequestAttributes() };\n\n if (logger) {\n logger.error(\n {\n ...dynamicAttributes,\n error: err.message,\n stack: err.stack,\n path: req.path,\n },\n 'Unhandled error',\n );\n }\n\n const span = trace.getActiveSpan();\n if (span) {\n span.recordException(err);\n span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });\n }\n\n if (res.headersSent) {\n return next(err);\n }\n\n res.status(500).json({\n error: err.message,\n attributes: dynamicAttributes,\n module: process.env.MAIN_MODULE || 'unknown-module',\n });\n };\n","import { getGlobalAttributes, getRequestAttributes } from './attributes.js';\n\nexport interface HttpCallContext {\n [key: string]: any;\n}\n\nexport interface HttpCallOptions extends RequestInit {\n body?: any;\n}\n\nexport async function httpCall(\n url: string,\n options: HttpCallOptions = {},\n logger?: { info: Function; error: Function },\n logContext: HttpCallContext = {},\n) {\n const fetchOptions: RequestInit = { ...options };\n const method = (fetchOptions.method || 'GET').toString().toUpperCase();\n\n if (\n fetchOptions.body &&\n typeof fetchOptions.body !== 'string' &&\n !(fetchOptions.body instanceof Buffer) &&\n !(fetchOptions.body instanceof ArrayBuffer)\n ) {\n fetchOptions.body = JSON.stringify(fetchOptions.body);\n fetchOptions.headers = {\n 'Content-Type': 'application/json',\n ...(fetchOptions.headers || {}),\n };\n }\n\n const dynamicContext = { ...getGlobalAttributes(), ...getRequestAttributes(), ...logContext };\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method }, 'HTTP call start');\n }\n\n try {\n const res = await fetch(url, fetchOptions);\n const contentType = res.headers.get('content-type') || '';\n const isJson = contentType.includes('application/json');\n const data = isJson ? await res.json().catch(() => null) : await res.text().catch(() => null);\n\n if (!res.ok) {\n const error = new Error(`HTTP ${res.status} ${res.statusText || ''}`.trim());\n (error as any).status = res.status;\n (error as any).data = data;\n if (logger) {\n logger.error({ ...dynamicContext, url, method, status: res.status, data }, 'HTTP call failed');\n }\n throw error;\n }\n\n if (logger) {\n logger.info({ ...dynamicContext, url, method, status: res.status }, 'HTTP call success');\n }\n\n return data;\n } catch (err: any) {\n if (logger) {\n logger.error({ ...dynamicContext, url, method, error: err.message }, 'HTTP call error');\n }\n throw err;\n }\n}\n"],"mappings":"yPAAA,OAAS,QAAAA,GAAM,q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C3E,MAACE,EAAc,OAASF,EAAI,OAC3BE,EAAc,KAAOD,EAClBR,GACFA,EAAO,MAAM,CAAE,GAAGI,EAAgB,IAAAN,EAAK,OAAAK,EAAQ,OAAQI,EAAI,OAAQ,KAAAC,CAAK,EAAG,kBAAkB,EAEzFC,CACR,CAEA,OAAIT,GACFA,EAAO,KAAK,CAAE,GAAGI,EAAgB,IAAAN,EAAK,OAAAK,EAAQ,OAAQI,EAAI,MAAO,EAAG,mBAAmB,EAGlFC,CACT,OAASE,EAAU,CACjB,MAAIV,GACFA,EAAO,MAAM,CAAE,GAAGI,EAAgB,IAAAN,EAAK,OAAAK,EAAQ,MAAOO,EAAI,OAAQ,EAAG,iBAAiB,EAElFA,CACR,CACF","names":["diag","DiagConsoleLogger","DiagLogLevel","trace","NodeSDK","createContextKey","SUPPRESS_TRACING_KEY","suppressTracing","context","diag","loggingErrorHandler","ex","stringifyException","flattenException","result","current","propertyName","value","delegateHandler","loggingErrorHandler","globalErrorHandler","ex","delegateHandler","DiagLogLevel","TracesSamplerValues","DEFAULT_LIST_SEPARATOR","ENVIRONMENT_BOOLEAN_KEYS","isEnvVarABoolean","key","ENVIRONMENT_NUMBERS_KEYS","isEnvVarANumber","ENVIRONMENT_LISTS_KEYS","isEnvVarAList","DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT","DEFAULT_ATTRIBUTE_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","DEFAULT_ENVIRONMENT","DiagLogLevel","TracesSamplerValues","parseBoolean","environment","values","value","parseNumber","name","min","max","parseStringList","output","input","separator","givenValue","v","logLevelMap","setLogLevelFromEnv","theLevel","parseEnvironment","env","getEnv","processEnv","parseEnvironment","DEFAULT_ENVIRONMENT","unrefTimer","timer","ExportResultCode","Deferred","_this","resolve","reject","val","err","BindOnceFuture","_callback","_that","Deferred","_this","args","_i","_a","__spreadArray","__read","val","err","context","diag","TraceFlags","BatchSpanProcessorBase","_exporter","config","env","getEnv","BindOnceFuture","diag","_span","_parentContext","span","TraceFlags","_this","resolve","reject","promises","count","i","j","timer","context","suppressTracing","spans","doExport","result","ExportResultCode","_a","pendingResources","len","err","globalErrorHandler","flush","e","unrefTimer","BatchSpanProcessor","_super","__extends","BatchSpanProcessorBase","Resource","OTLPTraceExporter","getNodeAutoInstrumentations","ProxyAgent","setGlobalDispatcher","AsyncLocalStorage","requestAttributeStorage","globalAttributes","clone","attrs","getGlobalAttributes","setGlobalAttributes","mergeGlobalAttributes","getRequestAttributes","setRequestAttributes","options","store","nextAttributes","mergeRequestAttributes","withRequestAttributes","fn","runWithRequestContext","initialAttributes","diag","DiagConsoleLogger","DiagLogLevel","serviceName","serviceNamespace","environment","moduleName","otlpEndpoint","expressLayersEnabled","moduleLabel","proxyUrl","v","setGlobalDispatcher","ProxyAgent","err","resource","Resource","ModuleNameSpanProcessor","span","currentName","dynamicAttributes","getGlobalAttributes","getRequestAttributes","key","value","_span","CombinedSpanProcessor","processors","ctx","p","instrumentations","getNodeAutoInstrumentations","exporter","OTLPTraceExporter","spanProcessor","BatchSpanProcessor","sdk","NodeSDK","sdkStartPromise","error","shutdown","instrumentApp","app","logger","customModuleName","req","_res","next","runWithRequestContext","setRequestAttributes","trace","requestAttributes","pino","levelMethods","wrapWithDynamicAttributes","logger","buildAttrs","getGlobalAttributes","getRequestAttributes","target","prop","receiver","original","firstArg","rest","attrs","createLogger","mainEnv","mainApp","mainModule","base","pino","trace","SpanStatusCode","errorMiddleware","logger","err","req","res","next","dynamicAttributes","getGlobalAttributes","getRequestAttributes","span","trace","SpanStatusCode","httpCall","url","options","logger","logContext","fetchOptions","method","dynamicContext","getGlobalAttributes","getRequestAttributes","res","data","error","err"]}
|