@lark-apaas/observable 1.0.1-alpha.13 → 1.0.1-alpha.14

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/dist/index.cjs CHANGED
@@ -308,8 +308,6 @@ var CustomExporter = class {
308
308
  }
309
309
  export(logs2, resultCallback) {
310
310
  const isDev = process.env.NODE_ENV === "development";
311
- if (isDev) {
312
- }
313
311
  const defaultAttributes = {
314
312
  uuid: idGenerator.generateTraceId(),
315
313
  app_env: isDev ? AppEnv.Dev : AppEnv.Prod
@@ -341,7 +339,8 @@ var CustomExporter = class {
341
339
  body: log.body,
342
340
  attributes: {
343
341
  ...defaultAttributes,
344
- ...contextAttributes
342
+ ...contextAttributes,
343
+ ...log.attributes ?? {}
345
344
  },
346
345
  traceId: log.spanContext?.traceId,
347
346
  spanId: log.spanContext?.spanId
@@ -376,7 +375,6 @@ var AppOTelLoggerSDK = class {
376
375
  getContext: /* @__PURE__ */ __name(() => ({}), "getContext")
377
376
  };
378
377
  setContextProvider(provider) {
379
- console.log("setContextProvider", provider);
380
378
  this.contextProvider = provider;
381
379
  }
382
380
  start() {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/core/sdk.ts","../../../../node_modules/@opentelemetry/api-logs/src/types/LogRecord.ts","../../../../node_modules/@opentelemetry/api-logs/src/NoopLogger.ts","../../../../node_modules/@opentelemetry/api-logs/src/NoopLoggerProvider.ts","../../../../node_modules/@opentelemetry/api-logs/src/ProxyLogger.ts","../../../../node_modules/@opentelemetry/api-logs/src/ProxyLoggerProvider.ts","../../../../node_modules/@opentelemetry/api-logs/src/platform/node/globalThis.ts","../../../../node_modules/@opentelemetry/api-logs/src/internal/global-utils.ts","../../../../node_modules/@opentelemetry/api-logs/src/api/logs.ts","../../../../node_modules/@opentelemetry/api-logs/src/index.ts","../src/core/resource-detector.ts","../../../../node_modules/@opentelemetry/core/src/ExportResult.ts","../src/core/exporter.ts","../src/utils/generateUUID.ts","../src/utils/hrTimeToNanoString.ts","../src/const.ts"],"sourcesContent":["export { AppOTelLoggerSDK, appSdk } from './core/sdk';\nexport type { ContextProvider } from './type';\n","import { NodeSDK } from '@opentelemetry/sdk-node';\nimport { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs';\nimport { detectResources } from '@opentelemetry/resources';\nimport { logs, SeverityNumber } from '@opentelemetry/api-logs';\nimport { PlatformDetector } from './resource-detector';\nimport type { LogAttributes, ContextProvider } from '../type';\nimport { CustomExporter } from './exporter';\n\n// 桥接型上下文提供者,由上层框架(如 NestJS)注入\n\nexport class AppOTelLoggerSDK {\n private sdk: NodeSDK | null = null;\n private logProcessor: BatchLogRecordProcessor | null = null;\n private contextProvider: ContextProvider = {\n getContext: () => ({}),\n };\n\n setContextProvider(provider: ContextProvider) {\n console.log('setContextProvider', provider);\n this.contextProvider = provider;\n }\n\n start() {\n const resource = detectResources({\n detectors: [new PlatformDetector()],\n });\n\n // 将获取上下文的函数传入 Exporter,保持 SDK 对框架无感\n const logExporter = new CustomExporter(this.contextProvider as ContextProvider);\n \n this.logProcessor = new BatchLogRecordProcessor(logExporter, {\n scheduledDelayMillis: 1000,\n maxExportBatchSize: 1,\n });\n\n this.sdk = new NodeSDK({\n resource,\n logRecordProcessor: this.logProcessor,\n traceExporter: undefined,\n });\n\n this.sdk.start();\n }\n\n /**\n * 用户使用的日志接口\n * 自动合并请求级上下文(由 ContextProvider 提供)\n */\n public log(level: string, message: string, extra: Record<string, unknown> = {}) {\n const logger = logs.getLogger('app-logger');\n const severityNumber = this.mapSeverity(level);\n const severityText = this.mapSeverityText(level);\n\n const ctx = this.contextProvider?.getContext() || {};\n\n const mergedAttributes: LogAttributes = {\n ...(ctx && typeof ctx === 'object' ? (ctx as LogAttributes) : {}),\n ...(extra || {}),\n pid: process.pid,\n };\n\n logger.emit({\n body: message,\n severityNumber,\n severityText,\n attributes: mergedAttributes,\n timestamp: new Date(),\n });\n }\n\n async flush() {\n if (this.logProcessor) {\n await this.logProcessor.forceFlush();\n }\n }\n\n private mapSeverity(level: string): SeverityNumber {\n switch (level.toLowerCase()) {\n case 'trace': return SeverityNumber.TRACE;\n case 'debug': return SeverityNumber.DEBUG;\n case 'info': return SeverityNumber.INFO;\n case 'warn': return SeverityNumber.WARN;\n case 'error': return SeverityNumber.ERROR;\n case 'fatal': return SeverityNumber.FATAL;\n default: return SeverityNumber.INFO;\n }\n }\n\n private mapSeverityText(level: string): string {\n switch (level.toLowerCase()) {\n case 'trace': return 'INFO';\n case 'debug': return 'DEBUG';\n case 'info': return 'INFO';\n case 'warn': return 'WARN';\n case 'error': return 'ERROR';\n case 'fatal': return 'ERROR';\n default: return 'INFO';\n }\n }\n}\n\nexport const appSdk = new AppOTelLoggerSDK();\nexport type { LogAttributes };\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, TimeInput } from '@opentelemetry/api';\nimport { AnyValue, AnyValueMap } from './AnyValue';\n\nexport type LogBody = AnyValue;\nexport type LogAttributes = AnyValueMap;\n\nexport enum SeverityNumber {\n UNSPECIFIED = 0,\n TRACE = 1,\n TRACE2 = 2,\n TRACE3 = 3,\n TRACE4 = 4,\n DEBUG = 5,\n DEBUG2 = 6,\n DEBUG3 = 7,\n DEBUG4 = 8,\n INFO = 9,\n INFO2 = 10,\n INFO3 = 11,\n INFO4 = 12,\n WARN = 13,\n WARN2 = 14,\n WARN3 = 15,\n WARN4 = 16,\n ERROR = 17,\n ERROR2 = 18,\n ERROR3 = 19,\n ERROR4 = 20,\n FATAL = 21,\n FATAL2 = 22,\n FATAL3 = 23,\n FATAL4 = 24,\n}\n\nexport interface LogRecord {\n /**\n * The unique identifier for the log record.\n */\n eventName?: string;\n\n /**\n * The time when the log record occurred as UNIX Epoch time in nanoseconds.\n */\n timestamp?: TimeInput;\n\n /**\n * Time when the event was observed by the collection system.\n */\n observedTimestamp?: TimeInput;\n\n /**\n * Numerical value of the severity.\n */\n severityNumber?: SeverityNumber;\n\n /**\n * The severity text.\n */\n severityText?: string;\n\n /**\n * A value containing the body of the log record.\n */\n body?: LogBody;\n\n /**\n * Attributes that define the log record.\n */\n attributes?: LogAttributes;\n\n /**\n * The Context associated with the LogRecord.\n */\n context?: Context;\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 { Logger } from './types/Logger';\nimport { LogRecord } from './types/LogRecord';\n\nexport class NoopLogger implements Logger {\n emit(_logRecord: LogRecord): void {}\n}\n\nexport const NOOP_LOGGER = new NoopLogger();\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 { LoggerProvider } from './types/LoggerProvider';\nimport { Logger } from './types/Logger';\nimport { LoggerOptions } from './types/LoggerOptions';\nimport { NoopLogger } from './NoopLogger';\n\nexport class NoopLoggerProvider implements LoggerProvider {\n getLogger(\n _name: string,\n _version?: string | undefined,\n _options?: LoggerOptions | undefined\n ): Logger {\n return new NoopLogger();\n }\n}\n\nexport const NOOP_LOGGER_PROVIDER = new NoopLoggerProvider();\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 { NOOP_LOGGER } from './NoopLogger';\nimport { Logger } from './types/Logger';\nimport { LoggerOptions } from './types/LoggerOptions';\nimport { LogRecord } from './types/LogRecord';\n\nexport class ProxyLogger implements Logger {\n // When a real implementation is provided, this will be it\n private _delegate?: Logger;\n\n constructor(\n private _provider: LoggerDelegator,\n public readonly name: string,\n public readonly version?: string | undefined,\n public readonly options?: LoggerOptions | undefined\n ) {}\n\n /**\n * Emit a log record. This method should only be used by log appenders.\n *\n * @param logRecord\n */\n emit(logRecord: LogRecord): void {\n this._getLogger().emit(logRecord);\n }\n\n /**\n * Try to get a logger from the proxy logger provider.\n * If the proxy logger provider has no delegate, return a noop logger.\n */\n private _getLogger() {\n if (this._delegate) {\n return this._delegate;\n }\n const logger = this._provider._getDelegateLogger(\n this.name,\n this.version,\n this.options\n );\n if (!logger) {\n return NOOP_LOGGER;\n }\n this._delegate = logger;\n return this._delegate;\n }\n}\n\nexport interface LoggerDelegator {\n _getDelegateLogger(\n name: string,\n version?: string,\n options?: LoggerOptions\n ): Logger | undefined;\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 { LoggerProvider } from './types/LoggerProvider';\nimport { Logger } from './types/Logger';\nimport { LoggerOptions } from './types/LoggerOptions';\nimport { NOOP_LOGGER_PROVIDER } from './NoopLoggerProvider';\nimport { ProxyLogger } from './ProxyLogger';\n\nexport class ProxyLoggerProvider implements LoggerProvider {\n private _delegate?: LoggerProvider;\n\n getLogger(\n name: string,\n version?: string | undefined,\n options?: LoggerOptions | undefined\n ): Logger {\n return (\n this._getDelegateLogger(name, version, options) ??\n new ProxyLogger(this, name, version, options)\n );\n }\n\n /**\n * Get the delegate logger provider.\n * Used by tests only.\n * @internal\n */\n _getDelegate(): LoggerProvider {\n return this._delegate ?? NOOP_LOGGER_PROVIDER;\n }\n\n /**\n * Set the delegate logger provider\n * @internal\n */\n _setDelegate(delegate: LoggerProvider) {\n this._delegate = delegate;\n }\n\n /**\n * @internal\n */\n _getDelegateLogger(\n name: string,\n version?: string | undefined,\n options?: LoggerOptions | undefined\n ): Logger | undefined {\n return this._delegate?.getLogger(name, version, options);\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\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line n/no-unsupported-features/es-builtins\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\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 { LoggerProvider } from '../types/LoggerProvider';\nimport { _globalThis } from '../platform';\n\nexport const GLOBAL_LOGS_API_KEY = Symbol.for('io.opentelemetry.js.api.logs');\n\ntype Get<T> = (version: number) => T;\ntype OtelGlobal = Partial<{\n [GLOBAL_LOGS_API_KEY]: Get<LoggerProvider>;\n}>;\n\nexport const _global = _globalThis as OtelGlobal;\n\n/**\n * Make a function which accepts a version integer and returns the instance of an API if the version\n * is compatible, or a fallback version (usually NOOP) if it is not.\n *\n * @param requiredVersion Backwards compatibility version which is required to return the instance\n * @param instance Instance which should be returned if the required version is compatible\n * @param fallback Fallback instance, usually NOOP, which will be returned if the required version is not compatible\n */\nexport function makeGetter<T>(\n requiredVersion: number,\n instance: T,\n fallback: T\n): Get<T> {\n return (version: number): T =>\n version === requiredVersion ? instance : fallback;\n}\n\n/**\n * A number which should be incremented each time a backwards incompatible\n * change is made to the API. This number is used when an API package\n * attempts to access the global API to ensure it is getting a compatible\n * version. If the global API is not compatible with the API package\n * attempting to get it, a NOOP API implementation will be returned.\n */\nexport const API_BACKWARDS_COMPATIBILITY_VERSION = 1;\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 API_BACKWARDS_COMPATIBILITY_VERSION,\n GLOBAL_LOGS_API_KEY,\n _global,\n makeGetter,\n} from '../internal/global-utils';\nimport { LoggerProvider } from '../types/LoggerProvider';\nimport { NOOP_LOGGER_PROVIDER } from '../NoopLoggerProvider';\nimport { Logger } from '../types/Logger';\nimport { LoggerOptions } from '../types/LoggerOptions';\nimport { ProxyLoggerProvider } from '../ProxyLoggerProvider';\n\nexport class LogsAPI {\n private static _instance?: LogsAPI;\n\n private _proxyLoggerProvider = new ProxyLoggerProvider();\n\n private constructor() {}\n\n public static getInstance(): LogsAPI {\n if (!this._instance) {\n this._instance = new LogsAPI();\n }\n\n return this._instance;\n }\n\n public setGlobalLoggerProvider(provider: LoggerProvider): LoggerProvider {\n if (_global[GLOBAL_LOGS_API_KEY]) {\n return this.getLoggerProvider();\n }\n\n _global[GLOBAL_LOGS_API_KEY] = makeGetter<LoggerProvider>(\n API_BACKWARDS_COMPATIBILITY_VERSION,\n provider,\n NOOP_LOGGER_PROVIDER\n );\n this._proxyLoggerProvider._setDelegate(provider);\n\n return provider;\n }\n\n /**\n * Returns the global logger provider.\n *\n * @returns LoggerProvider\n */\n public getLoggerProvider(): LoggerProvider {\n return (\n _global[GLOBAL_LOGS_API_KEY]?.(API_BACKWARDS_COMPATIBILITY_VERSION) ??\n this._proxyLoggerProvider\n );\n }\n\n /**\n * Returns a logger from the global logger provider.\n *\n * @returns Logger\n */\n public getLogger(\n name: string,\n version?: string,\n options?: LoggerOptions\n ): Logger {\n return this.getLoggerProvider().getLogger(name, version, options);\n }\n\n /** Remove the global logger provider */\n public disable(): void {\n delete _global[GLOBAL_LOGS_API_KEY];\n this._proxyLoggerProvider = new ProxyLoggerProvider();\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\nexport type { Logger } from './types/Logger';\nexport type { LoggerProvider } from './types/LoggerProvider';\nexport { SeverityNumber } from './types/LogRecord';\nexport type { LogAttributes, LogBody, LogRecord } from './types/LogRecord';\nexport type { LoggerOptions } from './types/LoggerOptions';\nexport type { AnyValue, AnyValueMap } from './types/AnyValue';\nexport { NOOP_LOGGER, NoopLogger } from './NoopLogger';\nexport { ProxyLoggerProvider } from './ProxyLoggerProvider';\n\nimport { LogsAPI } from './api/logs';\nexport const logs = LogsAPI.getInstance();\n","import { ResourceDetector, ResourceDetectionConfig, DetectedResource } from '@opentelemetry/resources';\n\n/**\n * 业务专属资源探测器\n * 负责从环境变量中提取低代码平台特有的元数据 (Tenant, App, Env)\n */\nexport class PlatformDetector implements ResourceDetector {\n \n /**\n * 实现 detect 接口\n * @param config 探测配置 (可选)\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\n detect(config?: ResourceDetectionConfig): DetectedResource {\n // 1. 从环境变量读取平台级资源字段\n const attributes: Record<string, string | number | boolean> = {};\n\n // 2. 清洗数据:移除 undefined/null/空字符串\n const cleanAttributes = Object.entries(attributes).reduce((acc, [key, value]) => {\n if (value !== undefined && value !== null && value !== '') {\n acc[key] = value;\n }\n return acc;\n }, {} as Record<string, string | number | boolean>);\n\n // 3. 返回 Resource 对象\n return {\n attributes: cleanAttributes,\n }\n }\n}\n\nexport const lowCodeDetector = new PlatformDetector();","/*\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","import { LogRecordExporter, ReadableLogRecord,} from '@opentelemetry/sdk-logs';\nimport { ExportResult, ExportResultCode } from '@opentelemetry/core';\nimport { Attributes } from '@opentelemetry/api';\nimport { Injectable } from '@nestjs/common';\n\nimport { idGenerator } from '../utils/generateUUID';\nimport { hrTimeToNanosString } from '../utils/hrTimeToNanoString';\nimport type { ContextProvider } from '../type';\nimport { AppEnv } from '../const';\n@Injectable()\nexport class CustomExporter implements LogRecordExporter {\n private logPrefix: string = \"force-log-prefix\"\n private logSuffix: string = \"force-log-suffix\"\n private requestContextService: ContextProvider;\n constructor(\n contextProvider: ContextProvider,\n ) {\n this.requestContextService = contextProvider;\n }\n\n export(logs: ReadableLogRecord[], resultCallback: (result: ExportResult) => void) {\n const isDev = process.env.NODE_ENV === \"development\";\n if(isDev){\n // todo 开发环境下,不打印日志\n // resultCallback({ code: ExportResultCode.SUCCESS });\n // return;\n }\n const defaultAttributes: Attributes = {\n uuid: idGenerator.generateTraceId(),\n app_env: isDev ? AppEnv.Dev : AppEnv.Prod,\n };\n\n const ctx = this.requestContextService.getContext();\n const contextAttributes: Attributes = ctx ? {\n user_id: ctx.userId as string | undefined,\n tenant_id: ctx.tenantId as string | undefined,\n app_id: ctx.appId as string | undefined,\n method: ctx.method as string ,\n path: ctx.path as string,\n } : {\n user_id: undefined,\n tenant_id: undefined,\n app_id: undefined,\n };\n // 模拟 OTLP 的结构化过程\n const otlpLikeStructure = {\n resourceLogs: logs.map(log => ({\n resource: {\n // 合并 OTel Resource(此处暂留空,真实场景可由 sdk.resource 提供)\n attributes: {}\n },\n logRecords: [{\n timeUnixNano: hrTimeToNanosString(log.hrTime),\n observedTimeUnixNano: hrTimeToNanosString(log.hrTimeObserved),\n severityNumber: log.severityNumber,\n severityText: log.severityText,\n body: log.body,\n attributes:{\n ...defaultAttributes,\n ...contextAttributes,\n // 暂不支持 log 上报 attributes 属性\n // ...(log.attributes ?? {}),\n },\n traceId: log.spanContext?.traceId,\n spanId: log.spanContext?.spanId\n }]\n }))\n };\n\n console.log(this.logPrefix + JSON.stringify(otlpLikeStructure) + this.logSuffix);\n resultCallback({ code: ExportResultCode.SUCCESS });\n }\n\n async shutdown() {}\n}","import { randomBytes } from 'crypto';\n\nexport const idGenerator = {\n /**\n * 生成 TraceId (128-bit / 32-char hex)\n * 符合 W3C Trace Context 标准\n * 示例: \"5b8efff798038103d269b633813fc60c\"\n */\n generateTraceId(): string {\n // 16 字节 = 128 位,转为 hex 就是 32 个字符\n return randomBytes(16).toString('hex');\n },\n\n /**\n * 生成 SpanId (64-bit / 16-char hex)\n * 示例: \"eee19b7ec3c1b174\"\n */\n generateSpanId(): string {\n // 8 字节 = 64 位,转为 hex 就是 16 个字符\n return randomBytes(8).toString('hex');\n }\n};","import type { HrTime } from '@opentelemetry/api';\n/**\n * 将 HrTime 转换为纳秒字符串\n * 使用 BigInt 防止精度丢失\n*/\nexport function hrTimeToNanosString(hrTime: HrTime): string {\n // 将秒转换为 BigInt\n const seconds = BigInt(hrTime[0]);\n // 将纳秒转换为 BigInt\n const nanos = BigInt(hrTime[1]);\n \n // 计算总纳秒数: seconds * 10^9 + nanos\n // 注意:数字后面加 'n' 表示 BigInt 字面量,或者使用 BigInt() 构造函数\n const totalNanos = (seconds * 1_000_000_000n) + nanos;\n \n return totalNanos.toString();\n}","export enum AppEnv {\n Dev = \"preview\",\n Prod = \"runtime\",\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;ACAA,sBAAwB;AACxB,sBAAwC;AACxC,uBAAgC;;;ACoBhC,IAAY;CAAZ,SAAYA,iBAAc;AACxB,EAAAA,gBAAAA,gBAAA,aAAA,IAAA,CAAA,IAAA;AACA,EAAAA,gBAAAA,gBAAA,OAAA,IAAA,CAAA,IAAA;AACA,EAAAA,gBAAAA,gBAAA,QAAA,IAAA,CAAA,IAAA;AACA,EAA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AU,YAAA;AAC9B,UAAMC,iBAAiB,KAAKC,YAAYP,KAAAA;AACxC,UAAMQ,eAAe,KAAKC,gBAAgBT,KAAAA;AAE1C,UAAMU,MAAM,KAAK9B,iBAAiBC,WAAAA,KAAgB,CAAC;AAEnD,UAAM8B,mBAAkC;MACtC,GAAID,OAAO,OAAOA,QAAQ,WAAYA,MAAwB,CAAC;MAC/D,GAAIR,SAAS,CAAC;MACdU,KAAKC,QAAQD;IACf;AAEAT,WAAOW,KAAK;MACVC,MAAMd;MACNK;MACAE;MACAQ,YAAYL;MACZM,WAAW,oBAAIC,KAAAA;IACjB,CAAA;EACF;EAEA,MAAMC,QAAQ;AACZ,QAAI,KAAKxC,cAAc;AACrB,YAAM,KAAKA,aAAayC,WAAU;IACpC;EACF;EAEQb,YAAYP,OAA+B;AACjD,YAAQA,MAAMqB,YAAW,GAAA;MACvB,KAAK;AAAS,eAAOC,eAAeC;MACpC,KAAK;AAAS,eAAOD,eAAeE;MACpC,KAAK;AAAQ,eAAOF,eAAeG;MACnC,KAAK;AAAQ,eAAOH,eAAeI;MACnC,KAAK;AAAS,eAAOJ,eAAeK;MACpC,KAAK;AAAS,eAAOL,eAAeM;MACpC;AAAS,eAAON,eAAeG;IACjC;EACF;EAEUhB,gBAAgBT,OAAuB;AAC/C,YAAQA,MAAMqB,YAAW,GAAA;MACvB,KAAK;AAAS,eAAO;MACrB,KAAK;AAAS,eAAO;MACrB,KAAK;AAAQ,eAAO;MACpB,KAAK;AAAQ,eAAO;MACpB,KAAK;AAAS,eAAO;MACrB,KAAK;AAAS,eAAO;MACrB;AAAS,eAAO;IAClB;EACF;AACF;AAEO,IAAMQ,SAAS,IAAIpD,iBAAAA;","names":["SeverityNumber","PlatformDetector","detect","config","attributes","cleanAttributes","Object","entries","reduce","acc","key","value","undefined","lowCodeDetector","ExportResultCode","idGenerator","generateTraceId","randomBytes","toString","generateSpanId","hrTimeToNanosString","hrTime","seconds","BigInt","nanos","totalNanos","toString","AppEnv","CustomExporter","logPrefix","logSuffix","requestContextService","contextProvider","export","logs","resultCallback","isDev","process","env","NODE_ENV","defaultAttributes","uuid","idGenerator","generateTraceId","app_env","AppEnv","Dev","Prod","ctx","getContext","contextAttributes","user_id","userId","tenant_id","tenantId","app_id","appId","method","path","undefined","otlpLikeStructure","resourceLogs","map","log","resource","attributes","logRecords","timeUnixNano","hrTimeToNanosString","hrTime","observedTimeUnixNano","hrTimeObserved","severityNumber","severityText","body","traceId","spanContext","spanId","console","JSON","stringify","code","ExportResultCode","SUCCESS","shutdown","AppOTelLoggerSDK","sdk","logProcessor","contextProvider","getContext","setContextProvider","provider","console","log","start","resource","detectResources","detectors","PlatformDetector","logExporter","CustomExporter","BatchLogRecordProcessor","scheduledDelayMillis","maxExportBatchSize","NodeSDK","logRecordProcessor","traceExporter","undefined","level","message","extra","logger","logs","getLogger","severityNumber","mapSeverity","severityText","mapSeverityText","ctx","mergedAttributes","pid","process","emit","body","attributes","timestamp","Date","flush","forceFlush","toLowerCase","SeverityNumber","TRACE","DEBUG","INFO","WARN","ERROR","FATAL","appSdk"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/core/sdk.ts","../../../../node_modules/@opentelemetry/api-logs/src/types/LogRecord.ts","../../../../node_modules/@opentelemetry/api-logs/src/NoopLogger.ts","../../../../node_modules/@opentelemetry/api-logs/src/NoopLoggerProvider.ts","../../../../node_modules/@opentelemetry/api-logs/src/ProxyLogger.ts","../../../../node_modules/@opentelemetry/api-logs/src/ProxyLoggerProvider.ts","../../../../node_modules/@opentelemetry/api-logs/src/platform/node/globalThis.ts","../../../../node_modules/@opentelemetry/api-logs/src/internal/global-utils.ts","../../../../node_modules/@opentelemetry/api-logs/src/api/logs.ts","../../../../node_modules/@opentelemetry/api-logs/src/index.ts","../src/core/resource-detector.ts","../../../../node_modules/@opentelemetry/core/src/ExportResult.ts","../src/core/exporter.ts","../src/utils/generateUUID.ts","../src/utils/hrTimeToNanoString.ts","../src/const.ts"],"sourcesContent":["export { AppOTelLoggerSDK, appSdk } from './core/sdk';\nexport type { ContextProvider } from './type';\n","import { NodeSDK } from '@opentelemetry/sdk-node';\nimport { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs';\nimport { detectResources } from '@opentelemetry/resources';\nimport { logs, SeverityNumber } from '@opentelemetry/api-logs';\nimport { PlatformDetector } from './resource-detector';\nimport type { LogAttributes, ContextProvider } from '../type';\nimport { CustomExporter } from './exporter';\n\n// 桥接型上下文提供者,由上层框架(如 NestJS)注入\n\nexport class AppOTelLoggerSDK {\n private sdk: NodeSDK | null = null;\n private logProcessor: BatchLogRecordProcessor | null = null;\n private contextProvider: ContextProvider = {\n getContext: () => ({}),\n };\n\n setContextProvider(provider: ContextProvider) {\n this.contextProvider = provider;\n }\n\n start() {\n const resource = detectResources({\n detectors: [new PlatformDetector()],\n });\n\n // 将获取上下文的函数传入 Exporter,保持 SDK 对框架无感\n const logExporter = new CustomExporter(this.contextProvider as ContextProvider);\n \n this.logProcessor = new BatchLogRecordProcessor(logExporter, {\n scheduledDelayMillis: 1000,\n maxExportBatchSize: 1,\n });\n\n this.sdk = new NodeSDK({\n resource,\n logRecordProcessor: this.logProcessor,\n traceExporter: undefined,\n });\n\n this.sdk.start();\n }\n\n /**\n * 用户使用的日志接口\n * 自动合并请求级上下文(由 ContextProvider 提供)\n */\n public log(level: string, message: string, extra: Record<string, unknown> = {}) {\n const logger = logs.getLogger('app-logger');\n const severityNumber = this.mapSeverity(level);\n const severityText = this.mapSeverityText(level);\n\n const ctx = this.contextProvider?.getContext() || {};\n\n const mergedAttributes: LogAttributes = {\n ...(ctx && typeof ctx === 'object' ? (ctx as LogAttributes) : {}),\n ...(extra || {}),\n pid: process.pid,\n };\n\n logger.emit({\n body: message,\n severityNumber,\n severityText,\n attributes: mergedAttributes,\n timestamp: new Date(),\n });\n }\n\n async flush() {\n if (this.logProcessor) {\n await this.logProcessor.forceFlush();\n }\n }\n\n private mapSeverity(level: string): SeverityNumber {\n switch (level.toLowerCase()) {\n case 'trace': return SeverityNumber.TRACE;\n case 'debug': return SeverityNumber.DEBUG;\n case 'info': return SeverityNumber.INFO;\n case 'warn': return SeverityNumber.WARN;\n case 'error': return SeverityNumber.ERROR;\n case 'fatal': return SeverityNumber.FATAL;\n default: return SeverityNumber.INFO;\n }\n }\n\n private mapSeverityText(level: string): string {\n switch (level.toLowerCase()) {\n case 'trace': return 'INFO';\n case 'debug': return 'DEBUG';\n case 'info': return 'INFO';\n case 'warn': return 'WARN';\n case 'error': return 'ERROR';\n case 'fatal': return 'ERROR';\n default: return 'INFO';\n }\n }\n}\n\nexport const appSdk = new AppOTelLoggerSDK();\nexport type { LogAttributes };\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, TimeInput } from '@opentelemetry/api';\nimport { AnyValue, AnyValueMap } from './AnyValue';\n\nexport type LogBody = AnyValue;\nexport type LogAttributes = AnyValueMap;\n\nexport enum SeverityNumber {\n UNSPECIFIED = 0,\n TRACE = 1,\n TRACE2 = 2,\n TRACE3 = 3,\n TRACE4 = 4,\n DEBUG = 5,\n DEBUG2 = 6,\n DEBUG3 = 7,\n DEBUG4 = 8,\n INFO = 9,\n INFO2 = 10,\n INFO3 = 11,\n INFO4 = 12,\n WARN = 13,\n WARN2 = 14,\n WARN3 = 15,\n WARN4 = 16,\n ERROR = 17,\n ERROR2 = 18,\n ERROR3 = 19,\n ERROR4 = 20,\n FATAL = 21,\n FATAL2 = 22,\n FATAL3 = 23,\n FATAL4 = 24,\n}\n\nexport interface LogRecord {\n /**\n * The unique identifier for the log record.\n */\n eventName?: string;\n\n /**\n * The time when the log record occurred as UNIX Epoch time in nanoseconds.\n */\n timestamp?: TimeInput;\n\n /**\n * Time when the event was observed by the collection system.\n */\n observedTimestamp?: TimeInput;\n\n /**\n * Numerical value of the severity.\n */\n severityNumber?: SeverityNumber;\n\n /**\n * The severity text.\n */\n severityText?: string;\n\n /**\n * A value containing the body of the log record.\n */\n body?: LogBody;\n\n /**\n * Attributes that define the log record.\n */\n attributes?: LogAttributes;\n\n /**\n * The Context associated with the LogRecord.\n */\n context?: Context;\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 { Logger } from './types/Logger';\nimport { LogRecord } from './types/LogRecord';\n\nexport class NoopLogger implements Logger {\n emit(_logRecord: LogRecord): void {}\n}\n\nexport const NOOP_LOGGER = new NoopLogger();\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 { LoggerProvider } from './types/LoggerProvider';\nimport { Logger } from './types/Logger';\nimport { LoggerOptions } from './types/LoggerOptions';\nimport { NoopLogger } from './NoopLogger';\n\nexport class NoopLoggerProvider implements LoggerProvider {\n getLogger(\n _name: string,\n _version?: string | undefined,\n _options?: LoggerOptions | undefined\n ): Logger {\n return new NoopLogger();\n }\n}\n\nexport const NOOP_LOGGER_PROVIDER = new NoopLoggerProvider();\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 { NOOP_LOGGER } from './NoopLogger';\nimport { Logger } from './types/Logger';\nimport { LoggerOptions } from './types/LoggerOptions';\nimport { LogRecord } from './types/LogRecord';\n\nexport class ProxyLogger implements Logger {\n // When a real implementation is provided, this will be it\n private _delegate?: Logger;\n\n constructor(\n private _provider: LoggerDelegator,\n public readonly name: string,\n public readonly version?: string | undefined,\n public readonly options?: LoggerOptions | undefined\n ) {}\n\n /**\n * Emit a log record. This method should only be used by log appenders.\n *\n * @param logRecord\n */\n emit(logRecord: LogRecord): void {\n this._getLogger().emit(logRecord);\n }\n\n /**\n * Try to get a logger from the proxy logger provider.\n * If the proxy logger provider has no delegate, return a noop logger.\n */\n private _getLogger() {\n if (this._delegate) {\n return this._delegate;\n }\n const logger = this._provider._getDelegateLogger(\n this.name,\n this.version,\n this.options\n );\n if (!logger) {\n return NOOP_LOGGER;\n }\n this._delegate = logger;\n return this._delegate;\n }\n}\n\nexport interface LoggerDelegator {\n _getDelegateLogger(\n name: string,\n version?: string,\n options?: LoggerOptions\n ): Logger | undefined;\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 { LoggerProvider } from './types/LoggerProvider';\nimport { Logger } from './types/Logger';\nimport { LoggerOptions } from './types/LoggerOptions';\nimport { NOOP_LOGGER_PROVIDER } from './NoopLoggerProvider';\nimport { ProxyLogger } from './ProxyLogger';\n\nexport class ProxyLoggerProvider implements LoggerProvider {\n private _delegate?: LoggerProvider;\n\n getLogger(\n name: string,\n version?: string | undefined,\n options?: LoggerOptions | undefined\n ): Logger {\n return (\n this._getDelegateLogger(name, version, options) ??\n new ProxyLogger(this, name, version, options)\n );\n }\n\n /**\n * Get the delegate logger provider.\n * Used by tests only.\n * @internal\n */\n _getDelegate(): LoggerProvider {\n return this._delegate ?? NOOP_LOGGER_PROVIDER;\n }\n\n /**\n * Set the delegate logger provider\n * @internal\n */\n _setDelegate(delegate: LoggerProvider) {\n this._delegate = delegate;\n }\n\n /**\n * @internal\n */\n _getDelegateLogger(\n name: string,\n version?: string | undefined,\n options?: LoggerOptions | undefined\n ): Logger | undefined {\n return this._delegate?.getLogger(name, version, options);\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\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line n/no-unsupported-features/es-builtins\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\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 { LoggerProvider } from '../types/LoggerProvider';\nimport { _globalThis } from '../platform';\n\nexport const GLOBAL_LOGS_API_KEY = Symbol.for('io.opentelemetry.js.api.logs');\n\ntype Get<T> = (version: number) => T;\ntype OtelGlobal = Partial<{\n [GLOBAL_LOGS_API_KEY]: Get<LoggerProvider>;\n}>;\n\nexport const _global = _globalThis as OtelGlobal;\n\n/**\n * Make a function which accepts a version integer and returns the instance of an API if the version\n * is compatible, or a fallback version (usually NOOP) if it is not.\n *\n * @param requiredVersion Backwards compatibility version which is required to return the instance\n * @param instance Instance which should be returned if the required version is compatible\n * @param fallback Fallback instance, usually NOOP, which will be returned if the required version is not compatible\n */\nexport function makeGetter<T>(\n requiredVersion: number,\n instance: T,\n fallback: T\n): Get<T> {\n return (version: number): T =>\n version === requiredVersion ? instance : fallback;\n}\n\n/**\n * A number which should be incremented each time a backwards incompatible\n * change is made to the API. This number is used when an API package\n * attempts to access the global API to ensure it is getting a compatible\n * version. If the global API is not compatible with the API package\n * attempting to get it, a NOOP API implementation will be returned.\n */\nexport const API_BACKWARDS_COMPATIBILITY_VERSION = 1;\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 API_BACKWARDS_COMPATIBILITY_VERSION,\n GLOBAL_LOGS_API_KEY,\n _global,\n makeGetter,\n} from '../internal/global-utils';\nimport { LoggerProvider } from '../types/LoggerProvider';\nimport { NOOP_LOGGER_PROVIDER } from '../NoopLoggerProvider';\nimport { Logger } from '../types/Logger';\nimport { LoggerOptions } from '../types/LoggerOptions';\nimport { ProxyLoggerProvider } from '../ProxyLoggerProvider';\n\nexport class LogsAPI {\n private static _instance?: LogsAPI;\n\n private _proxyLoggerProvider = new ProxyLoggerProvider();\n\n private constructor() {}\n\n public static getInstance(): LogsAPI {\n if (!this._instance) {\n this._instance = new LogsAPI();\n }\n\n return this._instance;\n }\n\n public setGlobalLoggerProvider(provider: LoggerProvider): LoggerProvider {\n if (_global[GLOBAL_LOGS_API_KEY]) {\n return this.getLoggerProvider();\n }\n\n _global[GLOBAL_LOGS_API_KEY] = makeGetter<LoggerProvider>(\n API_BACKWARDS_COMPATIBILITY_VERSION,\n provider,\n NOOP_LOGGER_PROVIDER\n );\n this._proxyLoggerProvider._setDelegate(provider);\n\n return provider;\n }\n\n /**\n * Returns the global logger provider.\n *\n * @returns LoggerProvider\n */\n public getLoggerProvider(): LoggerProvider {\n return (\n _global[GLOBAL_LOGS_API_KEY]?.(API_BACKWARDS_COMPATIBILITY_VERSION) ??\n this._proxyLoggerProvider\n );\n }\n\n /**\n * Returns a logger from the global logger provider.\n *\n * @returns Logger\n */\n public getLogger(\n name: string,\n version?: string,\n options?: LoggerOptions\n ): Logger {\n return this.getLoggerProvider().getLogger(name, version, options);\n }\n\n /** Remove the global logger provider */\n public disable(): void {\n delete _global[GLOBAL_LOGS_API_KEY];\n this._proxyLoggerProvider = new ProxyLoggerProvider();\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\nexport type { Logger } from './types/Logger';\nexport type { LoggerProvider } from './types/LoggerProvider';\nexport { SeverityNumber } from './types/LogRecord';\nexport type { LogAttributes, LogBody, LogRecord } from './types/LogRecord';\nexport type { LoggerOptions } from './types/LoggerOptions';\nexport type { AnyValue, AnyValueMap } from './types/AnyValue';\nexport { NOOP_LOGGER, NoopLogger } from './NoopLogger';\nexport { ProxyLoggerProvider } from './ProxyLoggerProvider';\n\nimport { LogsAPI } from './api/logs';\nexport const logs = LogsAPI.getInstance();\n","import { ResourceDetector, ResourceDetectionConfig, DetectedResource } from '@opentelemetry/resources';\n\n/**\n * 业务专属资源探测器\n * 负责从环境变量中提取低代码平台特有的元数据 (Tenant, App, Env)\n */\nexport class PlatformDetector implements ResourceDetector {\n \n /**\n * 实现 detect 接口\n * @param config 探测配置 (可选)\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\n detect(config?: ResourceDetectionConfig): DetectedResource {\n // 1. 从环境变量读取平台级资源字段\n const attributes: Record<string, string | number | boolean> = {};\n\n // 2. 清洗数据:移除 undefined/null/空字符串\n const cleanAttributes = Object.entries(attributes).reduce((acc, [key, value]) => {\n if (value !== undefined && value !== null && value !== '') {\n acc[key] = value;\n }\n return acc;\n }, {} as Record<string, string | number | boolean>);\n\n // 3. 返回 Resource 对象\n return {\n attributes: cleanAttributes,\n }\n }\n}\n\nexport const lowCodeDetector = new PlatformDetector();","/*\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","import { LogRecordExporter, ReadableLogRecord,} from '@opentelemetry/sdk-logs';\nimport { ExportResult, ExportResultCode } from '@opentelemetry/core';\nimport { Attributes } from '@opentelemetry/api';\nimport { Injectable } from '@nestjs/common';\n\nimport { idGenerator } from '../utils/generateUUID';\nimport { hrTimeToNanosString } from '../utils/hrTimeToNanoString';\nimport type { ContextProvider } from '../type';\nimport { AppEnv } from '../const';\n@Injectable()\nexport class CustomExporter implements LogRecordExporter {\n private logPrefix: string = \"force-log-prefix\"\n private logSuffix: string = \"force-log-suffix\"\n private requestContextService: ContextProvider;\n constructor(\n contextProvider: ContextProvider,\n ) {\n this.requestContextService = contextProvider;\n }\n\n export(logs: ReadableLogRecord[], resultCallback: (result: ExportResult) => void) {\n const isDev = process.env.NODE_ENV === \"development\";\n const defaultAttributes: Attributes = {\n uuid: idGenerator.generateTraceId(),\n app_env: isDev ? AppEnv.Dev : AppEnv.Prod,\n };\n\n const ctx = this.requestContextService.getContext();\n const contextAttributes: Attributes = ctx ? {\n user_id: ctx.userId as string | undefined,\n tenant_id: ctx.tenantId as string | undefined,\n app_id: ctx.appId as string | undefined,\n method: ctx.method as string ,\n path: ctx.path as string,\n } : {\n user_id: undefined,\n tenant_id: undefined,\n app_id: undefined,\n };\n // 模拟 OTLP 的结构化过程\n const otlpLikeStructure = {\n resourceLogs: logs.map(log => ({\n resource: {\n // 合并 OTel Resource(此处暂留空,真实场景可由 sdk.resource 提供)\n attributes: {}\n },\n logRecords: [{\n timeUnixNano: hrTimeToNanosString(log.hrTime),\n observedTimeUnixNano: hrTimeToNanosString(log.hrTimeObserved),\n severityNumber: log.severityNumber,\n severityText: log.severityText,\n body: log.body,\n attributes:{\n ...defaultAttributes,\n ...contextAttributes,\n ...(log.attributes ?? {}),\n },\n traceId: log.spanContext?.traceId,\n spanId: log.spanContext?.spanId\n }]\n }))\n };\n\n console.log(this.logPrefix + JSON.stringify(otlpLikeStructure) + this.logSuffix);\n resultCallback({ code: ExportResultCode.SUCCESS });\n }\n\n async shutdown() {}\n}","import { randomBytes } from 'crypto';\n\nexport const idGenerator = {\n /**\n * 生成 TraceId (128-bit / 32-char hex)\n * 符合 W3C Trace Context 标准\n * 示例: \"5b8efff798038103d269b633813fc60c\"\n */\n generateTraceId(): string {\n // 16 字节 = 128 位,转为 hex 就是 32 个字符\n return randomBytes(16).toString('hex');\n },\n\n /**\n * 生成 SpanId (64-bit / 16-char hex)\n * 示例: \"eee19b7ec3c1b174\"\n */\n generateSpanId(): string {\n // 8 字节 = 64 位,转为 hex 就是 16 个字符\n return randomBytes(8).toString('hex');\n }\n};","import type { HrTime } from '@opentelemetry/api';\n/**\n * 将 HrTime 转换为纳秒字符串\n * 使用 BigInt 防止精度丢失\n*/\nexport function hrTimeToNanosString(hrTime: HrTime): string {\n // 将秒转换为 BigInt\n const seconds = BigInt(hrTime[0]);\n // 将纳秒转换为 BigInt\n const nanos = BigInt(hrTime[1]);\n \n // 计算总纳秒数: seconds * 10^9 + nanos\n // 注意:数字后面加 'n' 表示 BigInt 字面量,或者使用 BigInt() 构造函数\n const totalNanos = (seconds * 1_000_000_000n) + nanos;\n \n return totalNanos.toString();\n}","export enum AppEnv {\n Dev = \"preview\",\n Prod = \"runtime\",\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;ACAA,sBAAwB;AACxB,sBAAwC;AACxC,uBAAgC;;;ACoBhC,IAAY;CAAZ,SAAYA,iBAAc;AACxB,EAAAA,gBAAAA,gBAAA,aAAA,IAAA,CAAA,IAAA;AACA,EAAAA,gBAAAA,gBAAA,OAAA,IAAA,CAAA,IAAA;AACA,EAAAA,gBAAAA,gBAAA,QAAA,IAAA,CAAA,IAAA;AACA,EAAAA,gBAAAA,gBAAA,QAAA,IAAA,CAAA,IAAA;AACA,EAAAA,gBAAAA,gBAAA,QAAA,IAAA,CAAA,IAAA;AACA,EAAAA,gBAAAA,gBAAA,OAAA,IAAA,CAAA,IAAA;AACA,EAAAA,gBAAAA,gBAAA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,QAAQ,WAAYA,MAAwB,CAAC;MAC/D,GAAIR,SAAS,CAAC;MACdU,KAAKC,QAAQD;IACf;AAEAT,WAAOW,KAAK;MACVC,MAAMd;MACNK;MACAE;MACAQ,YAAYL;MACZM,WAAW,oBAAIC,KAAAA;IACjB,CAAA;EACF;EAEA,MAAMC,QAAQ;AACZ,QAAI,KAAKvC,cAAc;AACrB,YAAM,KAAKA,aAAawC,WAAU;IACpC;EACF;EAEQb,YAAYP,OAA+B;AACjD,YAAQA,MAAMqB,YAAW,GAAA;MACvB,KAAK;AAAS,eAAOC,eAAeC;MACpC,KAAK;AAAS,eAAOD,eAAeE;MACpC,KAAK;AAAQ,eAAOF,eAAeG;MACnC,KAAK;AAAQ,eAAOH,eAAeI;MACnC,KAAK;AAAS,eAAOJ,eAAeK;MACpC,KAAK;AAAS,eAAOL,eAAeM;MACpC;AAAS,eAAON,eAAeG;IACjC;EACF;EAEUhB,gBAAgBT,OAAuB;AAC/C,YAAQA,MAAMqB,YAAW,GAAA;MACvB,KAAK;AAAS,eAAO;MACrB,KAAK;AAAS,eAAO;MACrB,KAAK;AAAQ,eAAO;MACpB,KAAK;AAAQ,eAAO;MACpB,KAAK;AAAS,eAAO;MACrB,KAAK;AAAS,eAAO;MACrB;AAAS,eAAO;IAClB;EACF;AACF;AAEO,IAAMQ,SAAS,IAAInD,iBAAAA;","names":["SeverityNumber","PlatformDetector","detect","config","attributes","cleanAttributes","Object","entries","reduce","acc","key","value","undefined","lowCodeDetector","ExportResultCode","idGenerator","generateTraceId","randomBytes","toString","generateSpanId","hrTimeToNanosString","hrTime","seconds","BigInt","nanos","totalNanos","toString","AppEnv","CustomExporter","logPrefix","logSuffix","requestContextService","contextProvider","export","logs","resultCallback","isDev","process","env","NODE_ENV","defaultAttributes","uuid","idGenerator","generateTraceId","app_env","AppEnv","Dev","Prod","ctx","getContext","contextAttributes","user_id","userId","tenant_id","tenantId","app_id","appId","method","path","undefined","otlpLikeStructure","resourceLogs","map","log","resource","attributes","logRecords","timeUnixNano","hrTimeToNanosString","hrTime","observedTimeUnixNano","hrTimeObserved","severityNumber","severityText","body","traceId","spanContext","spanId","console","JSON","stringify","code","ExportResultCode","SUCCESS","shutdown","AppOTelLoggerSDK","sdk","logProcessor","contextProvider","getContext","setContextProvider","provider","start","resource","detectResources","detectors","PlatformDetector","logExporter","CustomExporter","BatchLogRecordProcessor","scheduledDelayMillis","maxExportBatchSize","NodeSDK","logRecordProcessor","traceExporter","undefined","log","level","message","extra","logger","logs","getLogger","severityNumber","mapSeverity","severityText","mapSeverityText","ctx","mergedAttributes","pid","process","emit","body","attributes","timestamp","Date","flush","forceFlush","toLowerCase","SeverityNumber","TRACE","DEBUG","INFO","WARN","ERROR","FATAL","appSdk"]}
package/dist/index.js CHANGED
@@ -283,8 +283,6 @@ var CustomExporter = class {
283
283
  }
284
284
  export(logs2, resultCallback) {
285
285
  const isDev = process.env.NODE_ENV === "development";
286
- if (isDev) {
287
- }
288
286
  const defaultAttributes = {
289
287
  uuid: idGenerator.generateTraceId(),
290
288
  app_env: isDev ? AppEnv.Dev : AppEnv.Prod
@@ -316,7 +314,8 @@ var CustomExporter = class {
316
314
  body: log.body,
317
315
  attributes: {
318
316
  ...defaultAttributes,
319
- ...contextAttributes
317
+ ...contextAttributes,
318
+ ...log.attributes ?? {}
320
319
  },
321
320
  traceId: log.spanContext?.traceId,
322
321
  spanId: log.spanContext?.spanId
@@ -351,7 +350,6 @@ var AppOTelLoggerSDK = class {
351
350
  getContext: /* @__PURE__ */ __name(() => ({}), "getContext")
352
351
  };
353
352
  setContextProvider(provider) {
354
- console.log("setContextProvider", provider);
355
353
  this.contextProvider = provider;
356
354
  }
357
355
  start() {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/sdk.ts","../../../../node_modules/@opentelemetry/api-logs/src/types/LogRecord.ts","../../../../node_modules/@opentelemetry/api-logs/src/NoopLogger.ts","../../../../node_modules/@opentelemetry/api-logs/src/NoopLoggerProvider.ts","../../../../node_modules/@opentelemetry/api-logs/src/ProxyLogger.ts","../../../../node_modules/@opentelemetry/api-logs/src/ProxyLoggerProvider.ts","../../../../node_modules/@opentelemetry/api-logs/src/platform/node/globalThis.ts","../../../../node_modules/@opentelemetry/api-logs/src/internal/global-utils.ts","../../../../node_modules/@opentelemetry/api-logs/src/api/logs.ts","../../../../node_modules/@opentelemetry/api-logs/src/index.ts","../src/core/resource-detector.ts","../../../../node_modules/@opentelemetry/core/src/ExportResult.ts","../src/core/exporter.ts","../src/utils/generateUUID.ts","../src/utils/hrTimeToNanoString.ts","../src/const.ts"],"sourcesContent":["import { NodeSDK } from '@opentelemetry/sdk-node';\nimport { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs';\nimport { detectResources } from '@opentelemetry/resources';\nimport { logs, SeverityNumber } from '@opentelemetry/api-logs';\nimport { PlatformDetector } from './resource-detector';\nimport type { LogAttributes, ContextProvider } from '../type';\nimport { CustomExporter } from './exporter';\n\n// 桥接型上下文提供者,由上层框架(如 NestJS)注入\n\nexport class AppOTelLoggerSDK {\n private sdk: NodeSDK | null = null;\n private logProcessor: BatchLogRecordProcessor | null = null;\n private contextProvider: ContextProvider = {\n getContext: () => ({}),\n };\n\n setContextProvider(provider: ContextProvider) {\n console.log('setContextProvider', provider);\n this.contextProvider = provider;\n }\n\n start() {\n const resource = detectResources({\n detectors: [new PlatformDetector()],\n });\n\n // 将获取上下文的函数传入 Exporter,保持 SDK 对框架无感\n const logExporter = new CustomExporter(this.contextProvider as ContextProvider);\n \n this.logProcessor = new BatchLogRecordProcessor(logExporter, {\n scheduledDelayMillis: 1000,\n maxExportBatchSize: 1,\n });\n\n this.sdk = new NodeSDK({\n resource,\n logRecordProcessor: this.logProcessor,\n traceExporter: undefined,\n });\n\n this.sdk.start();\n }\n\n /**\n * 用户使用的日志接口\n * 自动合并请求级上下文(由 ContextProvider 提供)\n */\n public log(level: string, message: string, extra: Record<string, unknown> = {}) {\n const logger = logs.getLogger('app-logger');\n const severityNumber = this.mapSeverity(level);\n const severityText = this.mapSeverityText(level);\n\n const ctx = this.contextProvider?.getContext() || {};\n\n const mergedAttributes: LogAttributes = {\n ...(ctx && typeof ctx === 'object' ? (ctx as LogAttributes) : {}),\n ...(extra || {}),\n pid: process.pid,\n };\n\n logger.emit({\n body: message,\n severityNumber,\n severityText,\n attributes: mergedAttributes,\n timestamp: new Date(),\n });\n }\n\n async flush() {\n if (this.logProcessor) {\n await this.logProcessor.forceFlush();\n }\n }\n\n private mapSeverity(level: string): SeverityNumber {\n switch (level.toLowerCase()) {\n case 'trace': return SeverityNumber.TRACE;\n case 'debug': return SeverityNumber.DEBUG;\n case 'info': return SeverityNumber.INFO;\n case 'warn': return SeverityNumber.WARN;\n case 'error': return SeverityNumber.ERROR;\n case 'fatal': return SeverityNumber.FATAL;\n default: return SeverityNumber.INFO;\n }\n }\n\n private mapSeverityText(level: string): string {\n switch (level.toLowerCase()) {\n case 'trace': return 'INFO';\n case 'debug': return 'DEBUG';\n case 'info': return 'INFO';\n case 'warn': return 'WARN';\n case 'error': return 'ERROR';\n case 'fatal': return 'ERROR';\n default: return 'INFO';\n }\n }\n}\n\nexport const appSdk = new AppOTelLoggerSDK();\nexport type { LogAttributes };\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, TimeInput } from '@opentelemetry/api';\nimport { AnyValue, AnyValueMap } from './AnyValue';\n\nexport type LogBody = AnyValue;\nexport type LogAttributes = AnyValueMap;\n\nexport enum SeverityNumber {\n UNSPECIFIED = 0,\n TRACE = 1,\n TRACE2 = 2,\n TRACE3 = 3,\n TRACE4 = 4,\n DEBUG = 5,\n DEBUG2 = 6,\n DEBUG3 = 7,\n DEBUG4 = 8,\n INFO = 9,\n INFO2 = 10,\n INFO3 = 11,\n INFO4 = 12,\n WARN = 13,\n WARN2 = 14,\n WARN3 = 15,\n WARN4 = 16,\n ERROR = 17,\n ERROR2 = 18,\n ERROR3 = 19,\n ERROR4 = 20,\n FATAL = 21,\n FATAL2 = 22,\n FATAL3 = 23,\n FATAL4 = 24,\n}\n\nexport interface LogRecord {\n /**\n * The unique identifier for the log record.\n */\n eventName?: string;\n\n /**\n * The time when the log record occurred as UNIX Epoch time in nanoseconds.\n */\n timestamp?: TimeInput;\n\n /**\n * Time when the event was observed by the collection system.\n */\n observedTimestamp?: TimeInput;\n\n /**\n * Numerical value of the severity.\n */\n severityNumber?: SeverityNumber;\n\n /**\n * The severity text.\n */\n severityText?: string;\n\n /**\n * A value containing the body of the log record.\n */\n body?: LogBody;\n\n /**\n * Attributes that define the log record.\n */\n attributes?: LogAttributes;\n\n /**\n * The Context associated with the LogRecord.\n */\n context?: Context;\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 { Logger } from './types/Logger';\nimport { LogRecord } from './types/LogRecord';\n\nexport class NoopLogger implements Logger {\n emit(_logRecord: LogRecord): void {}\n}\n\nexport const NOOP_LOGGER = new NoopLogger();\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 { LoggerProvider } from './types/LoggerProvider';\nimport { Logger } from './types/Logger';\nimport { LoggerOptions } from './types/LoggerOptions';\nimport { NoopLogger } from './NoopLogger';\n\nexport class NoopLoggerProvider implements LoggerProvider {\n getLogger(\n _name: string,\n _version?: string | undefined,\n _options?: LoggerOptions | undefined\n ): Logger {\n return new NoopLogger();\n }\n}\n\nexport const NOOP_LOGGER_PROVIDER = new NoopLoggerProvider();\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 { NOOP_LOGGER } from './NoopLogger';\nimport { Logger } from './types/Logger';\nimport { LoggerOptions } from './types/LoggerOptions';\nimport { LogRecord } from './types/LogRecord';\n\nexport class ProxyLogger implements Logger {\n // When a real implementation is provided, this will be it\n private _delegate?: Logger;\n\n constructor(\n private _provider: LoggerDelegator,\n public readonly name: string,\n public readonly version?: string | undefined,\n public readonly options?: LoggerOptions | undefined\n ) {}\n\n /**\n * Emit a log record. This method should only be used by log appenders.\n *\n * @param logRecord\n */\n emit(logRecord: LogRecord): void {\n this._getLogger().emit(logRecord);\n }\n\n /**\n * Try to get a logger from the proxy logger provider.\n * If the proxy logger provider has no delegate, return a noop logger.\n */\n private _getLogger() {\n if (this._delegate) {\n return this._delegate;\n }\n const logger = this._provider._getDelegateLogger(\n this.name,\n this.version,\n this.options\n );\n if (!logger) {\n return NOOP_LOGGER;\n }\n this._delegate = logger;\n return this._delegate;\n }\n}\n\nexport interface LoggerDelegator {\n _getDelegateLogger(\n name: string,\n version?: string,\n options?: LoggerOptions\n ): Logger | undefined;\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 { LoggerProvider } from './types/LoggerProvider';\nimport { Logger } from './types/Logger';\nimport { LoggerOptions } from './types/LoggerOptions';\nimport { NOOP_LOGGER_PROVIDER } from './NoopLoggerProvider';\nimport { ProxyLogger } from './ProxyLogger';\n\nexport class ProxyLoggerProvider implements LoggerProvider {\n private _delegate?: LoggerProvider;\n\n getLogger(\n name: string,\n version?: string | undefined,\n options?: LoggerOptions | undefined\n ): Logger {\n return (\n this._getDelegateLogger(name, version, options) ??\n new ProxyLogger(this, name, version, options)\n );\n }\n\n /**\n * Get the delegate logger provider.\n * Used by tests only.\n * @internal\n */\n _getDelegate(): LoggerProvider {\n return this._delegate ?? NOOP_LOGGER_PROVIDER;\n }\n\n /**\n * Set the delegate logger provider\n * @internal\n */\n _setDelegate(delegate: LoggerProvider) {\n this._delegate = delegate;\n }\n\n /**\n * @internal\n */\n _getDelegateLogger(\n name: string,\n version?: string | undefined,\n options?: LoggerOptions | undefined\n ): Logger | undefined {\n return this._delegate?.getLogger(name, version, options);\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\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line n/no-unsupported-features/es-builtins\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\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 { LoggerProvider } from '../types/LoggerProvider';\nimport { _globalThis } from '../platform';\n\nexport const GLOBAL_LOGS_API_KEY = Symbol.for('io.opentelemetry.js.api.logs');\n\ntype Get<T> = (version: number) => T;\ntype OtelGlobal = Partial<{\n [GLOBAL_LOGS_API_KEY]: Get<LoggerProvider>;\n}>;\n\nexport const _global = _globalThis as OtelGlobal;\n\n/**\n * Make a function which accepts a version integer and returns the instance of an API if the version\n * is compatible, or a fallback version (usually NOOP) if it is not.\n *\n * @param requiredVersion Backwards compatibility version which is required to return the instance\n * @param instance Instance which should be returned if the required version is compatible\n * @param fallback Fallback instance, usually NOOP, which will be returned if the required version is not compatible\n */\nexport function makeGetter<T>(\n requiredVersion: number,\n instance: T,\n fallback: T\n): Get<T> {\n return (version: number): T =>\n version === requiredVersion ? instance : fallback;\n}\n\n/**\n * A number which should be incremented each time a backwards incompatible\n * change is made to the API. This number is used when an API package\n * attempts to access the global API to ensure it is getting a compatible\n * version. If the global API is not compatible with the API package\n * attempting to get it, a NOOP API implementation will be returned.\n */\nexport const API_BACKWARDS_COMPATIBILITY_VERSION = 1;\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 API_BACKWARDS_COMPATIBILITY_VERSION,\n GLOBAL_LOGS_API_KEY,\n _global,\n makeGetter,\n} from '../internal/global-utils';\nimport { LoggerProvider } from '../types/LoggerProvider';\nimport { NOOP_LOGGER_PROVIDER } from '../NoopLoggerProvider';\nimport { Logger } from '../types/Logger';\nimport { LoggerOptions } from '../types/LoggerOptions';\nimport { ProxyLoggerProvider } from '../ProxyLoggerProvider';\n\nexport class LogsAPI {\n private static _instance?: LogsAPI;\n\n private _proxyLoggerProvider = new ProxyLoggerProvider();\n\n private constructor() {}\n\n public static getInstance(): LogsAPI {\n if (!this._instance) {\n this._instance = new LogsAPI();\n }\n\n return this._instance;\n }\n\n public setGlobalLoggerProvider(provider: LoggerProvider): LoggerProvider {\n if (_global[GLOBAL_LOGS_API_KEY]) {\n return this.getLoggerProvider();\n }\n\n _global[GLOBAL_LOGS_API_KEY] = makeGetter<LoggerProvider>(\n API_BACKWARDS_COMPATIBILITY_VERSION,\n provider,\n NOOP_LOGGER_PROVIDER\n );\n this._proxyLoggerProvider._setDelegate(provider);\n\n return provider;\n }\n\n /**\n * Returns the global logger provider.\n *\n * @returns LoggerProvider\n */\n public getLoggerProvider(): LoggerProvider {\n return (\n _global[GLOBAL_LOGS_API_KEY]?.(API_BACKWARDS_COMPATIBILITY_VERSION) ??\n this._proxyLoggerProvider\n );\n }\n\n /**\n * Returns a logger from the global logger provider.\n *\n * @returns Logger\n */\n public getLogger(\n name: string,\n version?: string,\n options?: LoggerOptions\n ): Logger {\n return this.getLoggerProvider().getLogger(name, version, options);\n }\n\n /** Remove the global logger provider */\n public disable(): void {\n delete _global[GLOBAL_LOGS_API_KEY];\n this._proxyLoggerProvider = new ProxyLoggerProvider();\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\nexport type { Logger } from './types/Logger';\nexport type { LoggerProvider } from './types/LoggerProvider';\nexport { SeverityNumber } from './types/LogRecord';\nexport type { LogAttributes, LogBody, LogRecord } from './types/LogRecord';\nexport type { LoggerOptions } from './types/LoggerOptions';\nexport type { AnyValue, AnyValueMap } from './types/AnyValue';\nexport { NOOP_LOGGER, NoopLogger } from './NoopLogger';\nexport { ProxyLoggerProvider } from './ProxyLoggerProvider';\n\nimport { LogsAPI } from './api/logs';\nexport const logs = LogsAPI.getInstance();\n","import { ResourceDetector, ResourceDetectionConfig, DetectedResource } from '@opentelemetry/resources';\n\n/**\n * 业务专属资源探测器\n * 负责从环境变量中提取低代码平台特有的元数据 (Tenant, App, Env)\n */\nexport class PlatformDetector implements ResourceDetector {\n \n /**\n * 实现 detect 接口\n * @param config 探测配置 (可选)\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\n detect(config?: ResourceDetectionConfig): DetectedResource {\n // 1. 从环境变量读取平台级资源字段\n const attributes: Record<string, string | number | boolean> = {};\n\n // 2. 清洗数据:移除 undefined/null/空字符串\n const cleanAttributes = Object.entries(attributes).reduce((acc, [key, value]) => {\n if (value !== undefined && value !== null && value !== '') {\n acc[key] = value;\n }\n return acc;\n }, {} as Record<string, string | number | boolean>);\n\n // 3. 返回 Resource 对象\n return {\n attributes: cleanAttributes,\n }\n }\n}\n\nexport const lowCodeDetector = new PlatformDetector();","/*\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","import { LogRecordExporter, ReadableLogRecord,} from '@opentelemetry/sdk-logs';\nimport { ExportResult, ExportResultCode } from '@opentelemetry/core';\nimport { Attributes } from '@opentelemetry/api';\nimport { Injectable } from '@nestjs/common';\n\nimport { idGenerator } from '../utils/generateUUID';\nimport { hrTimeToNanosString } from '../utils/hrTimeToNanoString';\nimport type { ContextProvider } from '../type';\nimport { AppEnv } from '../const';\n@Injectable()\nexport class CustomExporter implements LogRecordExporter {\n private logPrefix: string = \"force-log-prefix\"\n private logSuffix: string = \"force-log-suffix\"\n private requestContextService: ContextProvider;\n constructor(\n contextProvider: ContextProvider,\n ) {\n this.requestContextService = contextProvider;\n }\n\n export(logs: ReadableLogRecord[], resultCallback: (result: ExportResult) => void) {\n const isDev = process.env.NODE_ENV === \"development\";\n if(isDev){\n // todo 开发环境下,不打印日志\n // resultCallback({ code: ExportResultCode.SUCCESS });\n // return;\n }\n const defaultAttributes: Attributes = {\n uuid: idGenerator.generateTraceId(),\n app_env: isDev ? AppEnv.Dev : AppEnv.Prod,\n };\n\n const ctx = this.requestContextService.getContext();\n const contextAttributes: Attributes = ctx ? {\n user_id: ctx.userId as string | undefined,\n tenant_id: ctx.tenantId as string | undefined,\n app_id: ctx.appId as string | undefined,\n method: ctx.method as string ,\n path: ctx.path as string,\n } : {\n user_id: undefined,\n tenant_id: undefined,\n app_id: undefined,\n };\n // 模拟 OTLP 的结构化过程\n const otlpLikeStructure = {\n resourceLogs: logs.map(log => ({\n resource: {\n // 合并 OTel Resource(此处暂留空,真实场景可由 sdk.resource 提供)\n attributes: {}\n },\n logRecords: [{\n timeUnixNano: hrTimeToNanosString(log.hrTime),\n observedTimeUnixNano: hrTimeToNanosString(log.hrTimeObserved),\n severityNumber: log.severityNumber,\n severityText: log.severityText,\n body: log.body,\n attributes:{\n ...defaultAttributes,\n ...contextAttributes,\n // 暂不支持 log 上报 attributes 属性\n // ...(log.attributes ?? {}),\n },\n traceId: log.spanContext?.traceId,\n spanId: log.spanContext?.spanId\n }]\n }))\n };\n\n console.log(this.logPrefix + JSON.stringify(otlpLikeStructure) + this.logSuffix);\n resultCallback({ code: ExportResultCode.SUCCESS });\n }\n\n async shutdown() {}\n}","import { randomBytes } from 'crypto';\n\nexport const idGenerator = {\n /**\n * 生成 TraceId (128-bit / 32-char hex)\n * 符合 W3C Trace Context 标准\n * 示例: \"5b8efff798038103d269b633813fc60c\"\n */\n generateTraceId(): string {\n // 16 字节 = 128 位,转为 hex 就是 32 个字符\n return randomBytes(16).toString('hex');\n },\n\n /**\n * 生成 SpanId (64-bit / 16-char hex)\n * 示例: \"eee19b7ec3c1b174\"\n */\n generateSpanId(): string {\n // 8 字节 = 64 位,转为 hex 就是 16 个字符\n return randomBytes(8).toString('hex');\n }\n};","import type { HrTime } from '@opentelemetry/api';\n/**\n * 将 HrTime 转换为纳秒字符串\n * 使用 BigInt 防止精度丢失\n*/\nexport function hrTimeToNanosString(hrTime: HrTime): string {\n // 将秒转换为 BigInt\n const seconds = BigInt(hrTime[0]);\n // 将纳秒转换为 BigInt\n const nanos = BigInt(hrTime[1]);\n \n // 计算总纳秒数: seconds * 10^9 + nanos\n // 注意:数字后面加 'n' 表示 BigInt 字面量,或者使用 BigInt() 构造函数\n const totalNanos = (seconds * 1_000_000_000n) + nanos;\n \n return totalNanos.toString();\n}","export enum AppEnv {\n Dev = \"preview\",\n Prod = \"runtime\",\n}\n"],"mappings":";;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B,KAAK;AAAS,eAAO;MACrB;AAAS,eAAO;IAClB;EACF;AACF;AAEO,IAAMQ,SAAS,IAAIpD,iBAAAA;","names":["NodeSDK","BatchLogRecordProcessor","detectResources","SeverityNumber","PlatformDetector","detect","config","attributes","cleanAttributes","Object","entries","reduce","acc","key","value","undefined","lowCodeDetector","ExportResultCode","Injectable","randomBytes","idGenerator","generateTraceId","toString","generateSpanId","hrTimeToNanosString","hrTime","seconds","BigInt","nanos","totalNanos","toString","AppEnv","CustomExporter","logPrefix","logSuffix","requestContextService","contextProvider","export","logs","resultCallback","isDev","process","env","NODE_ENV","defaultAttributes","uuid","idGenerator","generateTraceId","app_env","AppEnv","Dev","Prod","ctx","getContext","contextAttributes","user_id","userId","tenant_id","tenantId","app_id","appId","method","path","undefined","otlpLikeStructure","resourceLogs","map","log","resource","attributes","logRecords","timeUnixNano","hrTimeToNanosString","hrTime","observedTimeUnixNano","hrTimeObserved","severityNumber","severityText","body","traceId","spanContext","spanId","console","JSON","stringify","code","ExportResultCode","SUCCESS","shutdown","AppOTelLoggerSDK","sdk","logProcessor","contextProvider","getContext","setContextProvider","provider","console","log","start","resource","detectResources","detectors","PlatformDetector","logExporter","CustomExporter","BatchLogRecordProcessor","scheduledDelayMillis","maxExportBatchSize","NodeSDK","logRecordProcessor","traceExporter","undefined","level","message","extra","logger","logs","getLogger","severityNumber","mapSeverity","severityText","mapSeverityText","ctx","mergedAttributes","pid","process","emit","body","attributes","timestamp","Date","flush","forceFlush","toLowerCase","SeverityNumber","TRACE","DEBUG","INFO","WARN","ERROR","FATAL","appSdk"]}
1
+ {"version":3,"sources":["../src/core/sdk.ts","../../../../node_modules/@opentelemetry/api-logs/src/types/LogRecord.ts","../../../../node_modules/@opentelemetry/api-logs/src/NoopLogger.ts","../../../../node_modules/@opentelemetry/api-logs/src/NoopLoggerProvider.ts","../../../../node_modules/@opentelemetry/api-logs/src/ProxyLogger.ts","../../../../node_modules/@opentelemetry/api-logs/src/ProxyLoggerProvider.ts","../../../../node_modules/@opentelemetry/api-logs/src/platform/node/globalThis.ts","../../../../node_modules/@opentelemetry/api-logs/src/internal/global-utils.ts","../../../../node_modules/@opentelemetry/api-logs/src/api/logs.ts","../../../../node_modules/@opentelemetry/api-logs/src/index.ts","../src/core/resource-detector.ts","../../../../node_modules/@opentelemetry/core/src/ExportResult.ts","../src/core/exporter.ts","../src/utils/generateUUID.ts","../src/utils/hrTimeToNanoString.ts","../src/const.ts"],"sourcesContent":["import { NodeSDK } from '@opentelemetry/sdk-node';\nimport { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs';\nimport { detectResources } from '@opentelemetry/resources';\nimport { logs, SeverityNumber } from '@opentelemetry/api-logs';\nimport { PlatformDetector } from './resource-detector';\nimport type { LogAttributes, ContextProvider } from '../type';\nimport { CustomExporter } from './exporter';\n\n// 桥接型上下文提供者,由上层框架(如 NestJS)注入\n\nexport class AppOTelLoggerSDK {\n private sdk: NodeSDK | null = null;\n private logProcessor: BatchLogRecordProcessor | null = null;\n private contextProvider: ContextProvider = {\n getContext: () => ({}),\n };\n\n setContextProvider(provider: ContextProvider) {\n this.contextProvider = provider;\n }\n\n start() {\n const resource = detectResources({\n detectors: [new PlatformDetector()],\n });\n\n // 将获取上下文的函数传入 Exporter,保持 SDK 对框架无感\n const logExporter = new CustomExporter(this.contextProvider as ContextProvider);\n \n this.logProcessor = new BatchLogRecordProcessor(logExporter, {\n scheduledDelayMillis: 1000,\n maxExportBatchSize: 1,\n });\n\n this.sdk = new NodeSDK({\n resource,\n logRecordProcessor: this.logProcessor,\n traceExporter: undefined,\n });\n\n this.sdk.start();\n }\n\n /**\n * 用户使用的日志接口\n * 自动合并请求级上下文(由 ContextProvider 提供)\n */\n public log(level: string, message: string, extra: Record<string, unknown> = {}) {\n const logger = logs.getLogger('app-logger');\n const severityNumber = this.mapSeverity(level);\n const severityText = this.mapSeverityText(level);\n\n const ctx = this.contextProvider?.getContext() || {};\n\n const mergedAttributes: LogAttributes = {\n ...(ctx && typeof ctx === 'object' ? (ctx as LogAttributes) : {}),\n ...(extra || {}),\n pid: process.pid,\n };\n\n logger.emit({\n body: message,\n severityNumber,\n severityText,\n attributes: mergedAttributes,\n timestamp: new Date(),\n });\n }\n\n async flush() {\n if (this.logProcessor) {\n await this.logProcessor.forceFlush();\n }\n }\n\n private mapSeverity(level: string): SeverityNumber {\n switch (level.toLowerCase()) {\n case 'trace': return SeverityNumber.TRACE;\n case 'debug': return SeverityNumber.DEBUG;\n case 'info': return SeverityNumber.INFO;\n case 'warn': return SeverityNumber.WARN;\n case 'error': return SeverityNumber.ERROR;\n case 'fatal': return SeverityNumber.FATAL;\n default: return SeverityNumber.INFO;\n }\n }\n\n private mapSeverityText(level: string): string {\n switch (level.toLowerCase()) {\n case 'trace': return 'INFO';\n case 'debug': return 'DEBUG';\n case 'info': return 'INFO';\n case 'warn': return 'WARN';\n case 'error': return 'ERROR';\n case 'fatal': return 'ERROR';\n default: return 'INFO';\n }\n }\n}\n\nexport const appSdk = new AppOTelLoggerSDK();\nexport type { LogAttributes };\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, TimeInput } from '@opentelemetry/api';\nimport { AnyValue, AnyValueMap } from './AnyValue';\n\nexport type LogBody = AnyValue;\nexport type LogAttributes = AnyValueMap;\n\nexport enum SeverityNumber {\n UNSPECIFIED = 0,\n TRACE = 1,\n TRACE2 = 2,\n TRACE3 = 3,\n TRACE4 = 4,\n DEBUG = 5,\n DEBUG2 = 6,\n DEBUG3 = 7,\n DEBUG4 = 8,\n INFO = 9,\n INFO2 = 10,\n INFO3 = 11,\n INFO4 = 12,\n WARN = 13,\n WARN2 = 14,\n WARN3 = 15,\n WARN4 = 16,\n ERROR = 17,\n ERROR2 = 18,\n ERROR3 = 19,\n ERROR4 = 20,\n FATAL = 21,\n FATAL2 = 22,\n FATAL3 = 23,\n FATAL4 = 24,\n}\n\nexport interface LogRecord {\n /**\n * The unique identifier for the log record.\n */\n eventName?: string;\n\n /**\n * The time when the log record occurred as UNIX Epoch time in nanoseconds.\n */\n timestamp?: TimeInput;\n\n /**\n * Time when the event was observed by the collection system.\n */\n observedTimestamp?: TimeInput;\n\n /**\n * Numerical value of the severity.\n */\n severityNumber?: SeverityNumber;\n\n /**\n * The severity text.\n */\n severityText?: string;\n\n /**\n * A value containing the body of the log record.\n */\n body?: LogBody;\n\n /**\n * Attributes that define the log record.\n */\n attributes?: LogAttributes;\n\n /**\n * The Context associated with the LogRecord.\n */\n context?: Context;\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 { Logger } from './types/Logger';\nimport { LogRecord } from './types/LogRecord';\n\nexport class NoopLogger implements Logger {\n emit(_logRecord: LogRecord): void {}\n}\n\nexport const NOOP_LOGGER = new NoopLogger();\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 { LoggerProvider } from './types/LoggerProvider';\nimport { Logger } from './types/Logger';\nimport { LoggerOptions } from './types/LoggerOptions';\nimport { NoopLogger } from './NoopLogger';\n\nexport class NoopLoggerProvider implements LoggerProvider {\n getLogger(\n _name: string,\n _version?: string | undefined,\n _options?: LoggerOptions | undefined\n ): Logger {\n return new NoopLogger();\n }\n}\n\nexport const NOOP_LOGGER_PROVIDER = new NoopLoggerProvider();\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 { NOOP_LOGGER } from './NoopLogger';\nimport { Logger } from './types/Logger';\nimport { LoggerOptions } from './types/LoggerOptions';\nimport { LogRecord } from './types/LogRecord';\n\nexport class ProxyLogger implements Logger {\n // When a real implementation is provided, this will be it\n private _delegate?: Logger;\n\n constructor(\n private _provider: LoggerDelegator,\n public readonly name: string,\n public readonly version?: string | undefined,\n public readonly options?: LoggerOptions | undefined\n ) {}\n\n /**\n * Emit a log record. This method should only be used by log appenders.\n *\n * @param logRecord\n */\n emit(logRecord: LogRecord): void {\n this._getLogger().emit(logRecord);\n }\n\n /**\n * Try to get a logger from the proxy logger provider.\n * If the proxy logger provider has no delegate, return a noop logger.\n */\n private _getLogger() {\n if (this._delegate) {\n return this._delegate;\n }\n const logger = this._provider._getDelegateLogger(\n this.name,\n this.version,\n this.options\n );\n if (!logger) {\n return NOOP_LOGGER;\n }\n this._delegate = logger;\n return this._delegate;\n }\n}\n\nexport interface LoggerDelegator {\n _getDelegateLogger(\n name: string,\n version?: string,\n options?: LoggerOptions\n ): Logger | undefined;\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 { LoggerProvider } from './types/LoggerProvider';\nimport { Logger } from './types/Logger';\nimport { LoggerOptions } from './types/LoggerOptions';\nimport { NOOP_LOGGER_PROVIDER } from './NoopLoggerProvider';\nimport { ProxyLogger } from './ProxyLogger';\n\nexport class ProxyLoggerProvider implements LoggerProvider {\n private _delegate?: LoggerProvider;\n\n getLogger(\n name: string,\n version?: string | undefined,\n options?: LoggerOptions | undefined\n ): Logger {\n return (\n this._getDelegateLogger(name, version, options) ??\n new ProxyLogger(this, name, version, options)\n );\n }\n\n /**\n * Get the delegate logger provider.\n * Used by tests only.\n * @internal\n */\n _getDelegate(): LoggerProvider {\n return this._delegate ?? NOOP_LOGGER_PROVIDER;\n }\n\n /**\n * Set the delegate logger provider\n * @internal\n */\n _setDelegate(delegate: LoggerProvider) {\n this._delegate = delegate;\n }\n\n /**\n * @internal\n */\n _getDelegateLogger(\n name: string,\n version?: string | undefined,\n options?: LoggerOptions | undefined\n ): Logger | undefined {\n return this._delegate?.getLogger(name, version, options);\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\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line n/no-unsupported-features/es-builtins\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\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 { LoggerProvider } from '../types/LoggerProvider';\nimport { _globalThis } from '../platform';\n\nexport const GLOBAL_LOGS_API_KEY = Symbol.for('io.opentelemetry.js.api.logs');\n\ntype Get<T> = (version: number) => T;\ntype OtelGlobal = Partial<{\n [GLOBAL_LOGS_API_KEY]: Get<LoggerProvider>;\n}>;\n\nexport const _global = _globalThis as OtelGlobal;\n\n/**\n * Make a function which accepts a version integer and returns the instance of an API if the version\n * is compatible, or a fallback version (usually NOOP) if it is not.\n *\n * @param requiredVersion Backwards compatibility version which is required to return the instance\n * @param instance Instance which should be returned if the required version is compatible\n * @param fallback Fallback instance, usually NOOP, which will be returned if the required version is not compatible\n */\nexport function makeGetter<T>(\n requiredVersion: number,\n instance: T,\n fallback: T\n): Get<T> {\n return (version: number): T =>\n version === requiredVersion ? instance : fallback;\n}\n\n/**\n * A number which should be incremented each time a backwards incompatible\n * change is made to the API. This number is used when an API package\n * attempts to access the global API to ensure it is getting a compatible\n * version. If the global API is not compatible with the API package\n * attempting to get it, a NOOP API implementation will be returned.\n */\nexport const API_BACKWARDS_COMPATIBILITY_VERSION = 1;\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 API_BACKWARDS_COMPATIBILITY_VERSION,\n GLOBAL_LOGS_API_KEY,\n _global,\n makeGetter,\n} from '../internal/global-utils';\nimport { LoggerProvider } from '../types/LoggerProvider';\nimport { NOOP_LOGGER_PROVIDER } from '../NoopLoggerProvider';\nimport { Logger } from '../types/Logger';\nimport { LoggerOptions } from '../types/LoggerOptions';\nimport { ProxyLoggerProvider } from '../ProxyLoggerProvider';\n\nexport class LogsAPI {\n private static _instance?: LogsAPI;\n\n private _proxyLoggerProvider = new ProxyLoggerProvider();\n\n private constructor() {}\n\n public static getInstance(): LogsAPI {\n if (!this._instance) {\n this._instance = new LogsAPI();\n }\n\n return this._instance;\n }\n\n public setGlobalLoggerProvider(provider: LoggerProvider): LoggerProvider {\n if (_global[GLOBAL_LOGS_API_KEY]) {\n return this.getLoggerProvider();\n }\n\n _global[GLOBAL_LOGS_API_KEY] = makeGetter<LoggerProvider>(\n API_BACKWARDS_COMPATIBILITY_VERSION,\n provider,\n NOOP_LOGGER_PROVIDER\n );\n this._proxyLoggerProvider._setDelegate(provider);\n\n return provider;\n }\n\n /**\n * Returns the global logger provider.\n *\n * @returns LoggerProvider\n */\n public getLoggerProvider(): LoggerProvider {\n return (\n _global[GLOBAL_LOGS_API_KEY]?.(API_BACKWARDS_COMPATIBILITY_VERSION) ??\n this._proxyLoggerProvider\n );\n }\n\n /**\n * Returns a logger from the global logger provider.\n *\n * @returns Logger\n */\n public getLogger(\n name: string,\n version?: string,\n options?: LoggerOptions\n ): Logger {\n return this.getLoggerProvider().getLogger(name, version, options);\n }\n\n /** Remove the global logger provider */\n public disable(): void {\n delete _global[GLOBAL_LOGS_API_KEY];\n this._proxyLoggerProvider = new ProxyLoggerProvider();\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\nexport type { Logger } from './types/Logger';\nexport type { LoggerProvider } from './types/LoggerProvider';\nexport { SeverityNumber } from './types/LogRecord';\nexport type { LogAttributes, LogBody, LogRecord } from './types/LogRecord';\nexport type { LoggerOptions } from './types/LoggerOptions';\nexport type { AnyValue, AnyValueMap } from './types/AnyValue';\nexport { NOOP_LOGGER, NoopLogger } from './NoopLogger';\nexport { ProxyLoggerProvider } from './ProxyLoggerProvider';\n\nimport { LogsAPI } from './api/logs';\nexport const logs = LogsAPI.getInstance();\n","import { ResourceDetector, ResourceDetectionConfig, DetectedResource } from '@opentelemetry/resources';\n\n/**\n * 业务专属资源探测器\n * 负责从环境变量中提取低代码平台特有的元数据 (Tenant, App, Env)\n */\nexport class PlatformDetector implements ResourceDetector {\n \n /**\n * 实现 detect 接口\n * @param config 探测配置 (可选)\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\n detect(config?: ResourceDetectionConfig): DetectedResource {\n // 1. 从环境变量读取平台级资源字段\n const attributes: Record<string, string | number | boolean> = {};\n\n // 2. 清洗数据:移除 undefined/null/空字符串\n const cleanAttributes = Object.entries(attributes).reduce((acc, [key, value]) => {\n if (value !== undefined && value !== null && value !== '') {\n acc[key] = value;\n }\n return acc;\n }, {} as Record<string, string | number | boolean>);\n\n // 3. 返回 Resource 对象\n return {\n attributes: cleanAttributes,\n }\n }\n}\n\nexport const lowCodeDetector = new PlatformDetector();","/*\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","import { LogRecordExporter, ReadableLogRecord,} from '@opentelemetry/sdk-logs';\nimport { ExportResult, ExportResultCode } from '@opentelemetry/core';\nimport { Attributes } from '@opentelemetry/api';\nimport { Injectable } from '@nestjs/common';\n\nimport { idGenerator } from '../utils/generateUUID';\nimport { hrTimeToNanosString } from '../utils/hrTimeToNanoString';\nimport type { ContextProvider } from '../type';\nimport { AppEnv } from '../const';\n@Injectable()\nexport class CustomExporter implements LogRecordExporter {\n private logPrefix: string = \"force-log-prefix\"\n private logSuffix: string = \"force-log-suffix\"\n private requestContextService: ContextProvider;\n constructor(\n contextProvider: ContextProvider,\n ) {\n this.requestContextService = contextProvider;\n }\n\n export(logs: ReadableLogRecord[], resultCallback: (result: ExportResult) => void) {\n const isDev = process.env.NODE_ENV === \"development\";\n const defaultAttributes: Attributes = {\n uuid: idGenerator.generateTraceId(),\n app_env: isDev ? AppEnv.Dev : AppEnv.Prod,\n };\n\n const ctx = this.requestContextService.getContext();\n const contextAttributes: Attributes = ctx ? {\n user_id: ctx.userId as string | undefined,\n tenant_id: ctx.tenantId as string | undefined,\n app_id: ctx.appId as string | undefined,\n method: ctx.method as string ,\n path: ctx.path as string,\n } : {\n user_id: undefined,\n tenant_id: undefined,\n app_id: undefined,\n };\n // 模拟 OTLP 的结构化过程\n const otlpLikeStructure = {\n resourceLogs: logs.map(log => ({\n resource: {\n // 合并 OTel Resource(此处暂留空,真实场景可由 sdk.resource 提供)\n attributes: {}\n },\n logRecords: [{\n timeUnixNano: hrTimeToNanosString(log.hrTime),\n observedTimeUnixNano: hrTimeToNanosString(log.hrTimeObserved),\n severityNumber: log.severityNumber,\n severityText: log.severityText,\n body: log.body,\n attributes:{\n ...defaultAttributes,\n ...contextAttributes,\n ...(log.attributes ?? {}),\n },\n traceId: log.spanContext?.traceId,\n spanId: log.spanContext?.spanId\n }]\n }))\n };\n\n console.log(this.logPrefix + JSON.stringify(otlpLikeStructure) + this.logSuffix);\n resultCallback({ code: ExportResultCode.SUCCESS });\n }\n\n async shutdown() {}\n}","import { randomBytes } from 'crypto';\n\nexport const idGenerator = {\n /**\n * 生成 TraceId (128-bit / 32-char hex)\n * 符合 W3C Trace Context 标准\n * 示例: \"5b8efff798038103d269b633813fc60c\"\n */\n generateTraceId(): string {\n // 16 字节 = 128 位,转为 hex 就是 32 个字符\n return randomBytes(16).toString('hex');\n },\n\n /**\n * 生成 SpanId (64-bit / 16-char hex)\n * 示例: \"eee19b7ec3c1b174\"\n */\n generateSpanId(): string {\n // 8 字节 = 64 位,转为 hex 就是 16 个字符\n return randomBytes(8).toString('hex');\n }\n};","import type { HrTime } from '@opentelemetry/api';\n/**\n * 将 HrTime 转换为纳秒字符串\n * 使用 BigInt 防止精度丢失\n*/\nexport function hrTimeToNanosString(hrTime: HrTime): string {\n // 将秒转换为 BigInt\n const seconds = BigInt(hrTime[0]);\n // 将纳秒转换为 BigInt\n const nanos = BigInt(hrTime[1]);\n \n // 计算总纳秒数: seconds * 10^9 + nanos\n // 注意:数字后面加 'n' 表示 BigInt 字面量,或者使用 BigInt() 构造函数\n const totalNanos = (seconds * 1_000_000_000n) + nanos;\n \n return totalNanos.toString();\n}","export enum AppEnv {\n Dev = \"preview\",\n Prod = \"runtime\",\n}\n"],"mappings":";;;;AAAA,SAASA,eAAe;AACxB,SAASC,+BAA+B;AACxC,SAASC,uBAAuB;;;ACoBhC,IAAY;CAAZ,SAAYC,iBAAc;AACxB,EAAAA,gBAAAA,gBAAA,aAAA,IAAA,CAAA,IAAA;AACA,EAAAA,gBAAAA,gBAAA,OAAA,IAAA,CAAA,IAAA;AACA,EAAA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C9E,UAAMC,SAASC,KAAKC,UAAU,YAAA;AAC9B,UAAMC,iBAAiB,KAAKC,YAAYP,KAAAA;AACxC,UAAMQ,eAAe,KAAKC,gBAAgBT,KAAAA;AAE1C,UAAMU,MAAM,KAAK7B,iBAAiBC,WAAAA,KAAgB,CAAC;AAEnD,UAAM6B,mBAAkC;MACtC,GAAID,OAAO,OAAOA,QAAQ,WAAYA,MAAwB,CAAC;MAC/D,GAAIR,SAAS,CAAC;MACdU,KAAKC,QAAQD;IACf;AAEAT,WAAOW,KAAK;MACVC,MAAMd;MACNK;MACAE;MACAQ,YAAYL;MACZM,WAAW,oBAAIC,KAAAA;IACjB,CAAA;EACF;EAEA,MAAMC,QAAQ;AACZ,QAAI,KAAKvC,cAAc;AACrB,YAAM,KAAKA,aAAawC,WAAU;IACpC;EACF;EAEQb,YAAYP,OAA+B;AACjD,YAAQA,MAAMqB,YAAW,GAAA;MACvB,KAAK;AAAS,eAAOC,eAAeC;MACpC,KAAK;AAAS,eAAOD,eAAeE;MACpC,KAAK;AAAQ,eAAOF,eAAeG;MACnC,KAAK;AAAQ,eAAOH,eAAeI;MACnC,KAAK;AAAS,eAAOJ,eAAeK;MACpC,KAAK;AAAS,eAAOL,eAAeM;MACpC;AAAS,eAAON,eAAeG;IACjC;EACF;EAEUhB,gBAAgBT,OAAuB;AAC/C,YAAQA,MAAMqB,YAAW,GAAA;MACvB,KAAK;AAAS,eAAO;MACrB,KAAK;AAAS,eAAO;MACrB,KAAK;AAAQ,eAAO;MACpB,KAAK;AAAQ,eAAO;MACpB,KAAK;AAAS,eAAO;MACrB,KAAK;AAAS,eAAO;MACrB;AAAS,eAAO;IAClB;EACF;AACF;AAEO,IAAMQ,SAAS,IAAInD,iBAAAA;","names":["NodeSDK","BatchLogRecordProcessor","detectResources","SeverityNumber","PlatformDetector","detect","config","attributes","cleanAttributes","Object","entries","reduce","acc","key","value","undefined","lowCodeDetector","ExportResultCode","Injectable","randomBytes","idGenerator","generateTraceId","toString","generateSpanId","hrTimeToNanosString","hrTime","seconds","BigInt","nanos","totalNanos","toString","AppEnv","CustomExporter","logPrefix","logSuffix","requestContextService","contextProvider","export","logs","resultCallback","isDev","process","env","NODE_ENV","defaultAttributes","uuid","idGenerator","generateTraceId","app_env","AppEnv","Dev","Prod","ctx","getContext","contextAttributes","user_id","userId","tenant_id","tenantId","app_id","appId","method","path","undefined","otlpLikeStructure","resourceLogs","map","log","resource","attributes","logRecords","timeUnixNano","hrTimeToNanosString","hrTime","observedTimeUnixNano","hrTimeObserved","severityNumber","severityText","body","traceId","spanContext","spanId","console","JSON","stringify","code","ExportResultCode","SUCCESS","shutdown","AppOTelLoggerSDK","sdk","logProcessor","contextProvider","getContext","setContextProvider","provider","start","resource","detectResources","detectors","PlatformDetector","logExporter","CustomExporter","BatchLogRecordProcessor","scheduledDelayMillis","maxExportBatchSize","NodeSDK","logRecordProcessor","traceExporter","undefined","log","level","message","extra","logger","logs","getLogger","severityNumber","mapSeverity","severityText","mapSeverityText","ctx","mergedAttributes","pid","process","emit","body","attributes","timestamp","Date","flush","forceFlush","toLowerCase","SeverityNumber","TRACE","DEBUG","INFO","WARN","ERROR","FATAL","appSdk"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-apaas/observable",
3
- "version": "1.0.1-alpha.13",
3
+ "version": "1.0.1-alpha.14",
4
4
  "description": "Observable SDK",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",