feat: Complete zCode CLI X with Telegram bot integration

- Add full Telegram bot functionality with Z.AI API integration
- Implement 4 tools: Bash, FileEdit, WebSearch, Git
- Add 3 agents: Code Reviewer, Architect, DevOps Engineer
- Add 6 skills for common coding tasks
- Add systemd service file for 24/7 operation
- Add nginx configuration for HTTPS webhook
- Add comprehensive documentation
- Implement WebSocket server for real-time updates
- Add logging system with Winston
- Add environment validation

🤖 zCode CLI X - Agentic coder with Z.AI + Telegram integration
This commit is contained in:
admin
2026-05-05 09:01:26 +00:00
Unverified
parent 4a7035dd92
commit 875c7f9b91
24688 changed files with 3224957 additions and 221 deletions

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,200 @@
# OpenTelemetry Logs SDK
[![NPM Published Version][npm-img]][npm-url]
[![Apache License][license-image]][license-image]
**Note: This is an experimental package under active development. New releases may include breaking changes.**
OpenTelemetry logs module contains the foundation for all logs SDKs of [opentelemetry-js](https://github.com/open-telemetry/opentelemetry-js).
Used standalone, this module provides methods for manual instrumentation of code, offering full control over recording logs for client-side JavaScript (browser) and Node.js.
It does **not** provide automated instrumentation of known libraries or host environment logs out-of-the-box.
## Installation
```bash
npm install --save @opentelemetry/api-logs
npm install --save @opentelemetry/sdk-logs
```
## Usage
The basic setup of the SDK can be seen as followings:
```js
const logsAPI = require('@opentelemetry/api-logs');
const {
LoggerProvider,
SimpleLogRecordProcessor,
ConsoleLogRecordExporter,
} = require('@opentelemetry/sdk-logs');
// To start a logger, you first need to initialize the Logger provider.
// and add a processor to export log record
const loggerProvider = new LoggerProvider({
processors: [new SimpleLogRecordProcessor(new ConsoleLogRecordExporter())]
});
// To create a log record, you first need to get a Logger instance
const logger = loggerProvider.getLogger('default');
// You can also use global singleton
logsAPI.logs.setGlobalLoggerProvider(loggerProvider);
const logger = logsAPI.logs.getLogger('default');
// emit a log record
logger.emit({
severityNumber: logsAPI.SeverityNumber.INFO,
severityText: 'INFO',
body: 'this is a log record body',
attributes: { 'log.type': 'LogRecord' },
});
```
## Config
Logs configuration is a merge of both the user supplied configuration and the default
configuration as specified in [config.ts](./src/config.ts)
## Logger Configuration
The SDK supports advanced logger configuration through the `LoggerConfigurator` API, which allows you to:
- **Filter logs by minimum severity level** - Drop logs below a configured severity threshold
- **Filter logs by trace sampling status** - Drop logs associated with unsampled traces
- **Configure per-logger patterns** - Apply different configurations to different loggers using wildcard patterns
### Minimum Severity Filtering
Filter logs based on their severity level. Logs with severity below the configured minimum will be dropped before reaching the processor/exporter.
```js
const { LoggerProvider, createLoggerConfigurator } = require('@opentelemetry/sdk-logs');
const { SeverityNumber } = require('@opentelemetry/api-logs');
const loggerProvider = new LoggerProvider({
loggerConfigurator: createLoggerConfigurator([
{
pattern: '*', // Match all loggers
config: {
minimumSeverity: SeverityNumber.WARN // Only WARN, ERROR, and FATAL logs
}
}
]),
processors: [new SimpleLogRecordProcessor(exporter)]
});
```
**Behavior:**
- Logs with `severityNumber >= minimumSeverity` are exported
- Logs with `severityNumber = UNSPECIFIED` (0) or undefined always bypass the filter
- Default minimum severity is `UNSPECIFIED` (no filtering)
### Trace-Based Filtering
Filter logs based on their associated trace's sampling status. Logs from unsampled traces can be dropped to reduce volume while keeping sampled trace logs.
```js
const loggerProvider = new LoggerProvider({
loggerConfigurator: createLoggerConfigurator([
{
pattern: '*',
config: {
traceBased: true // Drop logs from unsampled traces
}
}
]),
processors: [new SimpleLogRecordProcessor(exporter)]
});
```
**Behavior:**
- Logs associated with **sampled traces** (TraceFlags.SAMPLED set) are exported
- Logs associated with **unsampled traces** (TraceFlags.SAMPLED not set) are dropped
- Logs **without trace context** bypass the filter and are exported
- Default is `false` (no trace-based filtering)
### Combined Filtering
Both filters can be combined. A log must pass **both** filters to be exported.
```js
const loggerProvider = new LoggerProvider({
loggerConfigurator: createLoggerConfigurator([
{
pattern: '*',
config: {
minimumSeverity: SeverityNumber.WARN, // Filter by severity
traceBased: true // AND filter by trace sampling
}
}
]),
processors: [new SimpleLogRecordProcessor(exporter)]
});
```
### Per-Logger Configuration
Use pattern matching to configure different loggers differently. Patterns are matched in order, and the first match is used.
```js
const loggerProvider = new LoggerProvider({
loggerConfigurator: createLoggerConfigurator([
{
pattern: 'critical-service', // Exact match
config: { minimumSeverity: SeverityNumber.ERROR }
},
{
pattern: 'debug-*', // Wildcard match
config: { minimumSeverity: SeverityNumber.DEBUG }
},
{
pattern: '*', // Default for all other loggers
config: { minimumSeverity: SeverityNumber.WARN }
}
])
});
// Different loggers get different configurations
const criticalLogger = loggerProvider.getLogger('critical-service'); // ERROR+
const debugLogger = loggerProvider.getLogger('debug-api'); // DEBUG+
const defaultLogger = loggerProvider.getLogger('my-service'); // WARN+
```
### Configuration Options
```typescript
interface LoggerConfig {
/** Drop logs with severity below this level (default: UNSPECIFIED = no filtering) */
minimumSeverity?: SeverityNumber;
/** Drop logs from unsampled traces (default: false) */
traceBased?: boolean;
/** Disable this logger completely (default: false) */
disabled?: boolean;
}
```
## Example
See [examples/logs](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/examples/logs)
## Useful links
- For more information on OpenTelemetry, visit: <https://opentelemetry.io/>
- For more about OpenTelemetry JavaScript: <https://github.com/open-telemetry/opentelemetry-js>
- For help or feedback on this project, join us in [GitHub Discussions][discussions-url]
## License
Apache 2.0 - See [LICENSE][license-url] for more information.
[discussions-url]: https://github.com/open-telemetry/opentelemetry-js/discussions
[license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/main/LICENSE
[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat
[npm-url]: https://www.npmjs.com/package/@opentelemetry/sdk-logs
[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fsdk%2Dlogs.svg

View File

@@ -0,0 +1,49 @@
import type { AnyValue, LogAttributes, LogBody, LogRecord, SeverityNumber } from '@opentelemetry/api-logs';
import * as api from '@opentelemetry/api';
import type { InstrumentationScope } from '@opentelemetry/core';
import type { Resource } from '@opentelemetry/resources';
import type { ReadableLogRecord } from './export/ReadableLogRecord';
import type { LoggerProviderSharedState } from './internal/LoggerProviderSharedState';
export declare class LogRecordImpl implements ReadableLogRecord {
readonly hrTime: api.HrTime;
readonly hrTimeObserved: api.HrTime;
readonly spanContext?: api.SpanContext;
readonly resource: Resource;
readonly instrumentationScope: InstrumentationScope;
readonly attributes: LogAttributes;
private _severityText?;
private _severityNumber?;
private _body?;
private _eventName?;
private _attributesCount;
private _droppedAttributesCount;
private _isReadonly;
private readonly _logRecordLimits;
set severityText(severityText: string | undefined);
get severityText(): string | undefined;
set severityNumber(severityNumber: SeverityNumber | undefined);
get severityNumber(): SeverityNumber | undefined;
set body(body: LogBody | undefined);
get body(): LogBody | undefined;
get eventName(): string | undefined;
set eventName(eventName: string | undefined);
get droppedAttributesCount(): number;
constructor(_sharedState: LoggerProviderSharedState, instrumentationScope: InstrumentationScope, logRecord: LogRecord);
setAttribute(key: string, value?: AnyValue): this;
setAttributes(attributes: LogAttributes): this;
setBody(body: LogBody): this;
setEventName(eventName: string): this;
setSeverityNumber(severityNumber: SeverityNumber): this;
setSeverityText(severityText: string): this;
/**
* @internal
* A LogRecordProcessor may freely modify logRecord for the duration of the OnEmit call.
* If logRecord is needed after OnEmit returns (i.e. for asynchronous processing) only reads are permitted.
*/
_makeReadonly(): void;
private _truncateToSize;
private _setException;
private _truncateToLimitUtil;
private _isLogRecordReadonly;
}
//# sourceMappingURL=LogRecordImpl.d.ts.map

View File

@@ -0,0 +1,231 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import * as api from '@opentelemetry/api';
import { timeInputToHrTime } from '@opentelemetry/core';
import { ATTR_EXCEPTION_MESSAGE, ATTR_EXCEPTION_STACKTRACE, ATTR_EXCEPTION_TYPE, } from '@opentelemetry/semantic-conventions';
import { isLogAttributeValue } from './utils/validation';
export class LogRecordImpl {
hrTime;
hrTimeObserved;
spanContext;
resource;
instrumentationScope;
attributes = {};
_severityText;
_severityNumber;
_body;
_eventName;
_attributesCount = 0;
_droppedAttributesCount = 0;
_isReadonly = false;
_logRecordLimits;
set severityText(severityText) {
if (this._isLogRecordReadonly()) {
return;
}
this._severityText = severityText;
}
get severityText() {
return this._severityText;
}
set severityNumber(severityNumber) {
if (this._isLogRecordReadonly()) {
return;
}
this._severityNumber = severityNumber;
}
get severityNumber() {
return this._severityNumber;
}
set body(body) {
if (this._isLogRecordReadonly()) {
return;
}
this._body = body;
}
get body() {
return this._body;
}
get eventName() {
return this._eventName;
}
set eventName(eventName) {
if (this._isLogRecordReadonly()) {
return;
}
this._eventName = eventName;
}
get droppedAttributesCount() {
return this._droppedAttributesCount;
}
constructor(_sharedState, instrumentationScope, logRecord) {
const { timestamp, observedTimestamp, eventName, severityNumber, severityText, body, attributes = {}, exception, context, } = logRecord;
const now = Date.now();
this.hrTime = timeInputToHrTime(timestamp ?? now);
this.hrTimeObserved = timeInputToHrTime(observedTimestamp ?? now);
if (context) {
const spanContext = api.trace.getSpanContext(context);
if (spanContext && api.isSpanContextValid(spanContext)) {
this.spanContext = spanContext;
}
}
this.severityNumber = severityNumber;
this.severityText = severityText;
this.body = body;
this.resource = _sharedState.resource;
this.instrumentationScope = instrumentationScope;
this._logRecordLimits = _sharedState.logRecordLimits;
this._eventName = eventName;
this.setAttributes(attributes);
if (exception != null) {
this._setException(exception);
}
}
setAttribute(key, value) {
if (this._isLogRecordReadonly()) {
return this;
}
if (key.length === 0) {
api.diag.warn(`Invalid attribute key: ${key}`);
return this;
}
if (!isLogAttributeValue(value)) {
api.diag.warn(`Invalid attribute value set for key: ${key}`);
return this;
}
const isNewKey = !Object.prototype.hasOwnProperty.call(this.attributes, key);
if (isNewKey &&
this._attributesCount >= this._logRecordLimits.attributeCountLimit) {
this._droppedAttributesCount++;
// Only warn once per LogRecord to avoid log spam
if (this._droppedAttributesCount === 1) {
api.diag.warn('Dropping extra attributes.');
}
return this;
}
this.attributes[key] = this._truncateToSize(value);
if (isNewKey) {
this._attributesCount++;
}
return this;
}
setAttributes(attributes) {
for (const [k, v] of Object.entries(attributes)) {
this.setAttribute(k, v);
}
return this;
}
setBody(body) {
this.body = body;
return this;
}
setEventName(eventName) {
this.eventName = eventName;
return this;
}
setSeverityNumber(severityNumber) {
this.severityNumber = severityNumber;
return this;
}
setSeverityText(severityText) {
this.severityText = severityText;
return this;
}
/**
* @internal
* A LogRecordProcessor may freely modify logRecord for the duration of the OnEmit call.
* If logRecord is needed after OnEmit returns (i.e. for asynchronous processing) only reads are permitted.
*/
_makeReadonly() {
this._isReadonly = true;
}
_truncateToSize(value) {
const limit = this._logRecordLimits.attributeValueLengthLimit;
// Check limit
if (limit <= 0) {
// Negative values are invalid, so do not truncate
api.diag.warn(`Attribute value limit must be positive, got ${limit}`);
return value;
}
// null/undefined - no truncation needed
if (value == null) {
return value;
}
// String
if (typeof value === 'string') {
return this._truncateToLimitUtil(value, limit);
}
// Byte arrays - no truncation needed
if (value instanceof Uint8Array) {
return value;
}
// Arrays (can contain any AnyValue types)
if (Array.isArray(value)) {
return value.map(val => this._truncateToSize(val));
}
// Objects/Maps - recursively truncate nested values
if (typeof value === 'object') {
const truncatedObj = {};
for (const [k, v] of Object.entries(value)) {
truncatedObj[k] = this._truncateToSize(v);
}
return truncatedObj;
}
// Other types (number, boolean), no need to apply value length limit
return value;
}
_setException(exception) {
let hasMinimumAttributes = false;
if (typeof exception === 'string' || typeof exception === 'number') {
if (!Object.hasOwn(this.attributes, ATTR_EXCEPTION_MESSAGE)) {
this.setAttribute(ATTR_EXCEPTION_MESSAGE, String(exception));
}
hasMinimumAttributes = true;
}
else if (exception && typeof exception === 'object') {
const exceptionObj = exception;
if (exceptionObj.code) {
if (!Object.hasOwn(this.attributes, ATTR_EXCEPTION_TYPE)) {
this.setAttribute(ATTR_EXCEPTION_TYPE, exceptionObj.code.toString());
}
hasMinimumAttributes = true;
}
else if (exceptionObj.name) {
if (!Object.hasOwn(this.attributes, ATTR_EXCEPTION_TYPE)) {
this.setAttribute(ATTR_EXCEPTION_TYPE, exceptionObj.name);
}
hasMinimumAttributes = true;
}
if (exceptionObj.message) {
if (!Object.hasOwn(this.attributes, ATTR_EXCEPTION_MESSAGE)) {
this.setAttribute(ATTR_EXCEPTION_MESSAGE, exceptionObj.message);
}
hasMinimumAttributes = true;
}
if (exceptionObj.stack) {
if (!Object.hasOwn(this.attributes, ATTR_EXCEPTION_STACKTRACE)) {
this.setAttribute(ATTR_EXCEPTION_STACKTRACE, exceptionObj.stack);
}
hasMinimumAttributes = true;
}
}
if (!hasMinimumAttributes) {
api.diag.warn(`Failed to record an exception ${exception}`);
}
}
_truncateToLimitUtil(value, limit) {
if (value.length <= limit) {
return value;
}
return value.substring(0, limit);
}
_isLogRecordReadonly() {
if (this._isReadonly) {
api.diag.warn('Can not execute the operation on emitted log record');
}
return this._isReadonly;
}
}
//# sourceMappingURL=LogRecordImpl.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,20 @@
import type { Context } from '@opentelemetry/api';
import type { SdkLogRecord } from './export/SdkLogRecord';
export interface LogRecordProcessor {
/**
* Forces to export all finished log records
*/
forceFlush(): Promise<void>;
/**
* Called when a {@link LogRecord} is emit
* @param logRecord the ReadWriteLogRecord that just emitted.
* @param context the current Context, or an empty Context if the Logger was obtained with include_trace_context=false
*/
onEmit(logRecord: SdkLogRecord, context?: Context): void;
/**
* Shuts down the processor. Called when SDK is shut down. This is an
* opportunity for processor to do any cleanup required.
*/
shutdown(): Promise<void>;
}
//# sourceMappingURL=LogRecordProcessor.d.ts.map

View File

@@ -0,0 +1,6 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=LogRecordProcessor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"LogRecordProcessor.js","sourceRoot":"","sources":["../../src/LogRecordProcessor.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\n\nimport type { SdkLogRecord } from './export/SdkLogRecord';\n\nexport interface LogRecordProcessor {\n /**\n * Forces to export all finished log records\n */\n forceFlush(): Promise<void>;\n\n /**\n * Called when a {@link LogRecord} is emit\n * @param logRecord the ReadWriteLogRecord that just emitted.\n * @param context the current Context, or an empty Context if the Logger was obtained with include_trace_context=false\n */\n onEmit(logRecord: SdkLogRecord, context?: Context): void;\n\n /**\n * Shuts down the processor. Called when SDK is shut down. This is an\n * opportunity for processor to do any cleanup required.\n */\n shutdown(): Promise<void>;\n}\n"]}

View File

@@ -0,0 +1,11 @@
import type * as logsAPI from '@opentelemetry/api-logs';
import type { InstrumentationScope } from '@opentelemetry/core';
import type { LoggerProviderSharedState } from './internal/LoggerProviderSharedState';
export declare class Logger implements logsAPI.Logger {
readonly instrumentationScope: InstrumentationScope;
private _sharedState;
private readonly _loggerConfig;
constructor(instrumentationScope: InstrumentationScope, sharedState: LoggerProviderSharedState);
emit(logRecord: logsAPI.LogRecord): void;
}
//# sourceMappingURL=Logger.d.ts.map

View File

@@ -0,0 +1,69 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { SeverityNumber } from '@opentelemetry/api-logs';
import { context, trace, TraceFlags, isSpanContextValid, } from '@opentelemetry/api';
import { LogRecordImpl } from './LogRecordImpl';
export class Logger {
instrumentationScope;
_sharedState;
_loggerConfig;
constructor(instrumentationScope, sharedState) {
this.instrumentationScope = instrumentationScope;
this._sharedState = sharedState;
// Cache the logger configuration at construction time
// Since we don't support re-configuration, this avoids map lookups
// and string allocations on each emit() call
this._loggerConfig = this._sharedState.getLoggerConfig(this.instrumentationScope);
}
emit(logRecord) {
const loggerConfig = this._loggerConfig;
const currentContext = logRecord.context || context.active();
// Apply minimum severity filtering
const recordSeverity = logRecord.severityNumber ?? SeverityNumber.UNSPECIFIED;
// 1. Minimum severity: If the log record's SeverityNumber is specified
// (i.e. not 0) and is less than the configured minimum_severity,
// the log record MUST be dropped.
if (recordSeverity !== SeverityNumber.UNSPECIFIED &&
recordSeverity < loggerConfig.minimumSeverity) {
// Log record is dropped due to minimum severity filter
return;
}
// 2. Trace-based: If trace_based is true, and if the log record has a
// SpanId and the TraceFlags SAMPLED flag is unset, the log record MUST be dropped.
if (loggerConfig.traceBased) {
const spanContext = trace.getSpanContext(currentContext);
if (spanContext && isSpanContextValid(spanContext)) {
// Check if the trace is unsampled (SAMPLED flag is unset)
const isSampled = (spanContext.traceFlags & TraceFlags.SAMPLED) === TraceFlags.SAMPLED;
if (!isSampled) {
// Log record is dropped due to trace-based filter
return;
}
}
// If there's no valid span context, the log record is not associated with a trace
// and therefore bypasses trace-based filtering (as per spec)
}
/**
* If a Logger was obtained with include_trace_context=true,
* the LogRecords it emits MUST automatically include the Trace Context from the active Context,
* if Context has not been explicitly set.
*/
const logRecordInstance = new LogRecordImpl(this._sharedState, this.instrumentationScope, {
context: currentContext,
...logRecord,
});
/**
* the explicitly passed Context,
* the current Context, or an empty Context if the Logger was obtained with include_trace_context=false
*/
this._sharedState.activeProcessor.onEmit(logRecordInstance, currentContext);
/**
* A LogRecordProcessor may freely modify logRecord for the duration of the OnEmit call.
* If logRecord is needed after OnEmit returns (i.e. for asynchronous processing) only reads are permitted.
*/
logRecordInstance._makeReadonly();
}
}
//# sourceMappingURL=Logger.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,27 @@
import type * as logsAPI from '@opentelemetry/api-logs';
import type { LoggerProviderConfig } from './types';
export declare const DEFAULT_LOGGER_NAME = "unknown";
export declare class LoggerProvider implements logsAPI.LoggerProvider {
private _shutdownOnce;
private readonly _sharedState;
constructor(config?: LoggerProviderConfig);
/**
* Get a logger with the configuration of the LoggerProvider.
*/
getLogger(name: string, version?: string, options?: logsAPI.LoggerOptions): logsAPI.Logger;
/**
* Notifies all registered LogRecordProcessor to flush any buffered data.
*
* Returns a promise which is resolved when all flushes are complete.
*/
forceFlush(): Promise<void>;
/**
* Flush all buffered data and shut down the LoggerProvider and all registered
* LogRecordProcessor.
*
* Returns a promise which is resolved when all flushes are complete.
*/
shutdown(): Promise<void>;
private _shutdown;
}
//# sourceMappingURL=LoggerProvider.d.ts.map

View File

@@ -0,0 +1,78 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { diag } from '@opentelemetry/api';
import { NOOP_LOGGER } from '@opentelemetry/api-logs';
import { defaultResource } from '@opentelemetry/resources';
import { BindOnceFuture } from '@opentelemetry/core';
import { Logger } from './Logger';
import { DEFAULT_LOGGER_CONFIGURATOR, LoggerProviderSharedState, } from './internal/LoggerProviderSharedState';
export const DEFAULT_LOGGER_NAME = 'unknown';
export class LoggerProvider {
_shutdownOnce;
_sharedState;
constructor(config = {}) {
const mergedConfig = {
resource: config.resource ?? defaultResource(),
forceFlushTimeoutMillis: config.forceFlushTimeoutMillis ?? 30000,
logRecordLimits: {
attributeCountLimit: config.logRecordLimits?.attributeCountLimit ?? 128,
attributeValueLengthLimit: config.logRecordLimits?.attributeValueLengthLimit ?? Infinity,
},
loggerConfigurator: config.loggerConfigurator ?? DEFAULT_LOGGER_CONFIGURATOR,
processors: config.processors ?? [],
};
this._sharedState = new LoggerProviderSharedState(mergedConfig.resource, mergedConfig.forceFlushTimeoutMillis, mergedConfig.logRecordLimits, mergedConfig.processors, mergedConfig.loggerConfigurator);
this._shutdownOnce = new BindOnceFuture(this._shutdown, this);
}
/**
* Get a logger with the configuration of the LoggerProvider.
*/
getLogger(name, version, options) {
if (this._shutdownOnce.isCalled) {
diag.warn('A shutdown LoggerProvider cannot provide a Logger');
return NOOP_LOGGER;
}
if (!name) {
diag.warn('Logger requested without instrumentation scope name.');
}
const loggerName = name || DEFAULT_LOGGER_NAME;
const key = `${loggerName}@${version || ''}:${options?.schemaUrl || ''}`;
if (!this._sharedState.loggers.has(key)) {
this._sharedState.loggers.set(key, new Logger({ name: loggerName, version, schemaUrl: options?.schemaUrl }, this._sharedState));
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this._sharedState.loggers.get(key);
}
/**
* Notifies all registered LogRecordProcessor to flush any buffered data.
*
* Returns a promise which is resolved when all flushes are complete.
*/
forceFlush() {
// do not flush after shutdown
if (this._shutdownOnce.isCalled) {
diag.warn('invalid attempt to force flush after LoggerProvider shutdown');
return this._shutdownOnce.promise;
}
return this._sharedState.activeProcessor.forceFlush();
}
/**
* Flush all buffered data and shut down the LoggerProvider and all registered
* LogRecordProcessor.
*
* Returns a promise which is resolved when all flushes are complete.
*/
shutdown() {
if (this._shutdownOnce.isCalled) {
diag.warn('shutdown may only be called once per LoggerProvider');
return this._shutdownOnce.promise;
}
return this._shutdownOnce.call();
}
_shutdown() {
return this._sharedState.activeProcessor.shutdown();
}
}
//# sourceMappingURL=LoggerProvider.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,16 @@
import type { Context } from '@opentelemetry/api';
import type { LogRecordProcessor } from './LogRecordProcessor';
import type { SdkLogRecord } from './export/SdkLogRecord';
/**
* Implementation of the {@link LogRecordProcessor} that simply forwards all
* received events to a list of {@link LogRecordProcessor}s.
*/
export declare class MultiLogRecordProcessor implements LogRecordProcessor {
readonly processors: LogRecordProcessor[];
readonly forceFlushTimeoutMillis: number;
constructor(processors: LogRecordProcessor[], forceFlushTimeoutMillis: number);
forceFlush(): Promise<void>;
onEmit(logRecord: SdkLogRecord, context?: Context): void;
shutdown(): Promise<void>;
}
//# sourceMappingURL=MultiLogRecordProcessor.d.ts.map

View File

@@ -0,0 +1,28 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { callWithTimeout } from '@opentelemetry/core';
/**
* Implementation of the {@link LogRecordProcessor} that simply forwards all
* received events to a list of {@link LogRecordProcessor}s.
*/
export class MultiLogRecordProcessor {
processors;
forceFlushTimeoutMillis;
constructor(processors, forceFlushTimeoutMillis) {
this.processors = processors;
this.forceFlushTimeoutMillis = forceFlushTimeoutMillis;
}
async forceFlush() {
const timeout = this.forceFlushTimeoutMillis;
await Promise.all(this.processors.map(processor => callWithTimeout(processor.forceFlush(), timeout)));
}
onEmit(logRecord, context) {
this.processors.forEach(processors => processors.onEmit(logRecord, context));
}
async shutdown() {
await Promise.all(this.processors.map(processor => processor.shutdown()));
}
}
//# sourceMappingURL=MultiLogRecordProcessor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"MultiLogRecordProcessor.js","sourceRoot":"","sources":["../../src/MultiLogRecordProcessor.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAKtD;;;GAGG;AACH,MAAM,OAAO,uBAAuB;IAClB,UAAU,CAAuB;IACjC,uBAAuB,CAAS;IAChD,YACE,UAAgC,EAChC,uBAA+B;QAE/B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,uBAAuB,GAAG,uBAAuB,CAAC;IACzD,CAAC;IAEM,KAAK,CAAC,UAAU;QACrB,MAAM,OAAO,GAAG,IAAI,CAAC,uBAAuB,CAAC;QAC7C,MAAM,OAAO,CAAC,GAAG,CACf,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAC9B,eAAe,CAAC,SAAS,CAAC,UAAU,EAAE,EAAE,OAAO,CAAC,CACjD,CACF,CAAC;IACJ,CAAC;IAEM,MAAM,CAAC,SAAuB,EAAE,OAAiB;QACtD,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,CACnC,UAAU,CAAC,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,CACtC,CAAC;IACJ,CAAC;IAEM,KAAK,CAAC,QAAQ;QACnB,MAAM,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;IAC5E,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { callWithTimeout } from '@opentelemetry/core';\nimport type { Context } from '@opentelemetry/api';\nimport type { LogRecordProcessor } from './LogRecordProcessor';\nimport type { SdkLogRecord } from './export/SdkLogRecord';\n\n/**\n * Implementation of the {@link LogRecordProcessor} that simply forwards all\n * received events to a list of {@link LogRecordProcessor}s.\n */\nexport class MultiLogRecordProcessor implements LogRecordProcessor {\n public readonly processors: LogRecordProcessor[];\n public readonly forceFlushTimeoutMillis: number;\n constructor(\n processors: LogRecordProcessor[],\n forceFlushTimeoutMillis: number\n ) {\n this.processors = processors;\n this.forceFlushTimeoutMillis = forceFlushTimeoutMillis;\n }\n\n public async forceFlush(): Promise<void> {\n const timeout = this.forceFlushTimeoutMillis;\n await Promise.all(\n this.processors.map(processor =>\n callWithTimeout(processor.forceFlush(), timeout)\n )\n );\n }\n\n public onEmit(logRecord: SdkLogRecord, context?: Context): void {\n this.processors.forEach(processors =>\n processors.onEmit(logRecord, context)\n );\n }\n\n public async shutdown(): Promise<void> {\n await Promise.all(this.processors.map(processor => processor.shutdown()));\n }\n}\n"]}

View File

@@ -0,0 +1,45 @@
import type { LoggerConfig, LoggerConfigurator } from '../types';
/**
* Configuration for a specific logger pattern
*
* @experimental This feature is in development as per the OpenTelemetry specification.
*/
export interface LoggerPattern {
/**
* The logger name or pattern to match.
* Use '*' for wildcard matching.
*
* @experimental This feature is in development as per the OpenTelemetry specification.
*/
pattern: string;
/**
* The configuration to apply to matching loggers.
* Partial config is allowed; unspecified properties will use defaults.
*
* @experimental This feature is in development as per the OpenTelemetry specification.
*/
config: LoggerConfig;
}
/**
* Creates a LoggerConfigurator from an array of logger patterns.
* Patterns are evaluated in order, and the first matching pattern's config is used.
* Supports exact matching and simple wildcard patterns with '*'.
*
* The returned configurator computes a complete LoggerConfig by merging the matched
* pattern's config with default values for any unspecified properties.
*
* @param patterns - Array of logger patterns with their configurations
* @returns A LoggerConfigurator function that computes complete LoggerConfig
* @experimental This feature is in development as per the OpenTelemetry specification.
*
* @example
* ```typescript
* const configurator = createLoggerConfigurator([
* { pattern: 'debug-logger', config: { minimumSeverity: SeverityNumber.DEBUG } },
* { pattern: 'prod-*', config: { minimumSeverity: SeverityNumber.WARN } },
* { pattern: '*', config: { minimumSeverity: SeverityNumber.INFO } },
* ]);
* ```
*/
export declare function createLoggerConfigurator(patterns: LoggerPattern[]): LoggerConfigurator;
//# sourceMappingURL=LoggerConfigurators.d.ts.map

View File

@@ -0,0 +1,79 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { SeverityNumber } from '@opentelemetry/api-logs';
/**
* Default LoggerConfig used when no pattern matches
*
* @experimental This feature is in development as per the OpenTelemetry specification.
*/
const DEFAULT_LOGGER_CONFIG = {
disabled: false,
minimumSeverity: SeverityNumber.UNSPECIFIED,
traceBased: false,
};
/**
* Creates a LoggerConfigurator from an array of logger patterns.
* Patterns are evaluated in order, and the first matching pattern's config is used.
* Supports exact matching and simple wildcard patterns with '*'.
*
* The returned configurator computes a complete LoggerConfig by merging the matched
* pattern's config with default values for any unspecified properties.
*
* @param patterns - Array of logger patterns with their configurations
* @returns A LoggerConfigurator function that computes complete LoggerConfig
* @experimental This feature is in development as per the OpenTelemetry specification.
*
* @example
* ```typescript
* const configurator = createLoggerConfigurator([
* { pattern: 'debug-logger', config: { minimumSeverity: SeverityNumber.DEBUG } },
* { pattern: 'prod-*', config: { minimumSeverity: SeverityNumber.WARN } },
* { pattern: '*', config: { minimumSeverity: SeverityNumber.INFO } },
* ]);
* ```
*/
export function createLoggerConfigurator(patterns) {
return (loggerScope) => {
const loggerName = loggerScope.name;
// Find the first matching pattern
for (const { pattern, config } of patterns) {
if (matchesPattern(loggerName, pattern)) {
// Compute complete config by merging with defaults
return {
disabled: config.disabled ?? DEFAULT_LOGGER_CONFIG.disabled,
minimumSeverity: config.minimumSeverity ?? DEFAULT_LOGGER_CONFIG.minimumSeverity,
traceBased: config.traceBased ?? DEFAULT_LOGGER_CONFIG.traceBased,
};
}
}
// No pattern matched, return default config
return { ...DEFAULT_LOGGER_CONFIG };
};
}
/**
* Matches a logger name against a pattern.
* Supports simple wildcard matching with '*'.
*
* @param name - The logger name to match
* @param pattern - The pattern to match against (supports '*' wildcard)
* @returns true if the name matches the pattern
*/
function matchesPattern(name, pattern) {
// Exact match
if (pattern === name) {
return true;
}
// Wildcard pattern
if (pattern.includes('*')) {
const regexPattern = pattern
.split('*')
.map(part => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
.join('.*');
const regex = new RegExp(`^${regexPattern}$`);
return regex.test(name);
}
return false;
}
//# sourceMappingURL=LoggerConfigurators.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,34 @@
import type { BufferConfig } from '../types';
import type { SdkLogRecord } from './SdkLogRecord';
import type { LogRecordExporter } from './LogRecordExporter';
import type { LogRecordProcessor } from '../LogRecordProcessor';
export declare abstract class BatchLogRecordProcessorBase<T extends BufferConfig> implements LogRecordProcessor {
private readonly _maxExportBatchSize;
private readonly _maxQueueSize;
private readonly _scheduledDelayMillis;
private readonly _exportTimeoutMillis;
private readonly _exporter;
private _isExporting;
private _finishedLogRecords;
private _timer;
private _shutdownOnce;
constructor(exporter: LogRecordExporter, config?: T);
onEmit(logRecord: SdkLogRecord): void;
forceFlush(): Promise<void>;
shutdown(): Promise<void>;
private _shutdown;
/** Add a LogRecord in the buffer. */
private _addToBuffer;
/**
* Send all LogRecords to the exporter respecting the batch size limit
* This function is used only on forceFlush or shutdown,
* for all other cases _flush should be used
* */
private _flushAll;
private _flushOneBatch;
private _maybeStartTimer;
private _clearTimer;
private _export;
protected abstract onShutdown(): void;
}
//# sourceMappingURL=BatchLogRecordProcessorBase.d.ts.map

View File

@@ -0,0 +1,146 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { diag } from '@opentelemetry/api';
import { ExportResultCode, globalErrorHandler, BindOnceFuture, internal, callWithTimeout, } from '@opentelemetry/core';
export class BatchLogRecordProcessorBase {
_maxExportBatchSize;
_maxQueueSize;
_scheduledDelayMillis;
_exportTimeoutMillis;
_exporter;
_isExporting = false;
_finishedLogRecords = [];
_timer;
_shutdownOnce;
constructor(exporter, config) {
this._exporter = exporter;
this._maxExportBatchSize = config?.maxExportBatchSize ?? 512;
this._maxQueueSize = config?.maxQueueSize ?? 2048;
this._scheduledDelayMillis = config?.scheduledDelayMillis ?? 5000;
this._exportTimeoutMillis = config?.exportTimeoutMillis ?? 30000;
this._shutdownOnce = new BindOnceFuture(this._shutdown, this);
if (this._maxExportBatchSize > this._maxQueueSize) {
diag.warn('BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize');
this._maxExportBatchSize = this._maxQueueSize;
}
}
onEmit(logRecord) {
if (this._shutdownOnce.isCalled) {
return;
}
this._addToBuffer(logRecord);
}
forceFlush() {
if (this._shutdownOnce.isCalled) {
return this._shutdownOnce.promise;
}
return this._flushAll();
}
shutdown() {
return this._shutdownOnce.call();
}
async _shutdown() {
this.onShutdown();
await this._flushAll();
await this._exporter.shutdown();
}
/** Add a LogRecord in the buffer. */
_addToBuffer(logRecord) {
if (this._finishedLogRecords.length >= this._maxQueueSize) {
return;
}
this._finishedLogRecords.push(logRecord);
this._maybeStartTimer();
}
/**
* Send all LogRecords to the exporter respecting the batch size limit
* This function is used only on forceFlush or shutdown,
* for all other cases _flush should be used
* */
_flushAll() {
return new Promise((resolve, reject) => {
const promises = [];
const batchCount = Math.ceil(this._finishedLogRecords.length / this._maxExportBatchSize);
for (let i = 0; i < batchCount; i++) {
promises.push(this._flushOneBatch());
}
Promise.all(promises)
.then(() => {
resolve();
})
.catch(reject);
});
}
_flushOneBatch() {
this._clearTimer();
if (this._finishedLogRecords.length === 0) {
return Promise.resolve();
}
return callWithTimeout(this._export(this._finishedLogRecords.splice(0, this._maxExportBatchSize)), this._exportTimeoutMillis);
}
_maybeStartTimer() {
if (this._isExporting)
return;
const flush = () => {
this._isExporting = true;
this._flushOneBatch()
.then(() => {
this._isExporting = false;
if (this._finishedLogRecords.length > 0) {
this._clearTimer();
this._maybeStartTimer();
}
})
.catch(e => {
this._isExporting = false;
globalErrorHandler(e);
});
};
// we only wait if the queue doesn't have enough elements yet
if (this._finishedLogRecords.length >= this._maxExportBatchSize) {
return flush();
}
if (this._timer !== undefined)
return;
this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);
// depending on runtime, this may be a 'number' or NodeJS.Timeout
if (typeof this._timer !== 'number') {
this._timer.unref();
}
}
_clearTimer() {
if (this._timer !== undefined) {
clearTimeout(this._timer);
this._timer = undefined;
}
}
_export(logRecords) {
const doExport = () => internal
._export(this._exporter, logRecords)
.then((result) => {
if (result.code !== ExportResultCode.SUCCESS) {
globalErrorHandler(result.error ??
new Error(`BatchLogRecordProcessor: log record export failed (status ${result})`));
}
})
.catch(globalErrorHandler);
const pendingResources = [];
for (let i = 0; i < logRecords.length; i++) {
const resource = logRecords[i].resource;
if (resource.asyncAttributesPending &&
typeof resource.waitForAsyncAttributes === 'function') {
pendingResources.push(resource.waitForAsyncAttributes());
}
}
// Avoid scheduling a promise to make the behavior more predictable and easier to test
if (pendingResources.length === 0) {
return doExport();
}
else {
return Promise.all(pendingResources).then(doExport, globalErrorHandler);
}
}
}
//# sourceMappingURL=BatchLogRecordProcessorBase.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,33 @@
import type { ExportResult } from '@opentelemetry/core';
import type { ReadableLogRecord } from './ReadableLogRecord';
import type { LogRecordExporter } from './LogRecordExporter';
/**
* This is implementation of {@link LogRecordExporter} that prints LogRecords to the
* console. This class can be used for diagnostic purposes.
*
* NOTE: This {@link LogRecordExporter} is intended for diagnostics use only, output rendered to the console may change at any time.
*/
export declare class ConsoleLogRecordExporter implements LogRecordExporter {
/**
* Export logs.
* @param logs
* @param resultCallback
*/
export(logs: ReadableLogRecord[], resultCallback: (result: ExportResult) => void): void;
/**
* Shutdown the exporter.
*/
shutdown(): Promise<void>;
/**
* converts logRecord info into more readable format
* @param logRecord
*/
private _exportInfo;
/**
* Showing logs in console
* @param logRecords
* @param done
*/
private _sendLogRecords;
}
//# sourceMappingURL=ConsoleLogRecordExporter.d.ts.map

View File

@@ -0,0 +1,61 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { ExportResultCode, hrTimeToMicroseconds } from '@opentelemetry/core';
/**
* This is implementation of {@link LogRecordExporter} that prints LogRecords to the
* console. This class can be used for diagnostic purposes.
*
* NOTE: This {@link LogRecordExporter} is intended for diagnostics use only, output rendered to the console may change at any time.
*/
/* eslint-disable no-console */
export class ConsoleLogRecordExporter {
/**
* Export logs.
* @param logs
* @param resultCallback
*/
export(logs, resultCallback) {
this._sendLogRecords(logs, resultCallback);
}
/**
* Shutdown the exporter.
*/
shutdown() {
return Promise.resolve();
}
/**
* converts logRecord info into more readable format
* @param logRecord
*/
_exportInfo(logRecord) {
return {
resource: {
attributes: logRecord.resource.attributes,
},
instrumentationScope: logRecord.instrumentationScope,
timestamp: hrTimeToMicroseconds(logRecord.hrTime),
traceId: logRecord.spanContext?.traceId,
spanId: logRecord.spanContext?.spanId,
traceFlags: logRecord.spanContext?.traceFlags,
severityText: logRecord.severityText,
severityNumber: logRecord.severityNumber,
eventName: logRecord.eventName,
body: logRecord.body,
attributes: logRecord.attributes,
};
}
/**
* Showing logs in console
* @param logRecords
* @param done
*/
_sendLogRecords(logRecords, done) {
for (const logRecord of logRecords) {
console.dir(this._exportInfo(logRecord), { depth: 3 });
}
done?.({ code: ExportResultCode.SUCCESS });
}
}
//# sourceMappingURL=ConsoleLogRecordExporter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ConsoleLogRecordExporter.js","sourceRoot":"","sources":["../../../src/export/ConsoleLogRecordExporter.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAK7E;;;;;GAKG;AAEH,+BAA+B;AAC/B,MAAM,OAAO,wBAAwB;IACnC;;;;OAIG;IACI,MAAM,CACX,IAAyB,EACzB,cAA8C;QAE9C,IAAI,CAAC,eAAe,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;IAC7C,CAAC;IAED;;OAEG;IACI,QAAQ;QACb,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED;;;OAGG;IACK,WAAW,CAAC,SAA4B;QAC9C,OAAO;YACL,QAAQ,EAAE;gBACR,UAAU,EAAE,SAAS,CAAC,QAAQ,CAAC,UAAU;aAC1C;YACD,oBAAoB,EAAE,SAAS,CAAC,oBAAoB;YACpD,SAAS,EAAE,oBAAoB,CAAC,SAAS,CAAC,MAAM,CAAC;YACjD,OAAO,EAAE,SAAS,CAAC,WAAW,EAAE,OAAO;YACvC,MAAM,EAAE,SAAS,CAAC,WAAW,EAAE,MAAM;YACrC,UAAU,EAAE,SAAS,CAAC,WAAW,EAAE,UAAU;YAC7C,YAAY,EAAE,SAAS,CAAC,YAAY;YACpC,cAAc,EAAE,SAAS,CAAC,cAAc;YACxC,SAAS,EAAE,SAAS,CAAC,SAAS;YAC9B,IAAI,EAAE,SAAS,CAAC,IAAI;YACpB,UAAU,EAAE,SAAS,CAAC,UAAU;SACjC,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACK,eAAe,CACrB,UAA+B,EAC/B,IAAqC;QAErC,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE;YAClC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,SAAS,CAAC,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;SACxD;QACD,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC;IAC7C,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode, hrTimeToMicroseconds } from '@opentelemetry/core';\n\nimport type { ReadableLogRecord } from './ReadableLogRecord';\nimport type { LogRecordExporter } from './LogRecordExporter';\n\n/**\n * This is implementation of {@link LogRecordExporter} that prints LogRecords to the\n * console. This class can be used for diagnostic purposes.\n *\n * NOTE: This {@link LogRecordExporter} is intended for diagnostics use only, output rendered to the console may change at any time.\n */\n\n/* eslint-disable no-console */\nexport class ConsoleLogRecordExporter implements LogRecordExporter {\n /**\n * Export logs.\n * @param logs\n * @param resultCallback\n */\n public export(\n logs: ReadableLogRecord[],\n resultCallback: (result: ExportResult) => void\n ) {\n this._sendLogRecords(logs, resultCallback);\n }\n\n /**\n * Shutdown the exporter.\n */\n public shutdown(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * converts logRecord info into more readable format\n * @param logRecord\n */\n private _exportInfo(logRecord: ReadableLogRecord) {\n return {\n resource: {\n attributes: logRecord.resource.attributes,\n },\n instrumentationScope: logRecord.instrumentationScope,\n timestamp: hrTimeToMicroseconds(logRecord.hrTime),\n traceId: logRecord.spanContext?.traceId,\n spanId: logRecord.spanContext?.spanId,\n traceFlags: logRecord.spanContext?.traceFlags,\n severityText: logRecord.severityText,\n severityNumber: logRecord.severityNumber,\n eventName: logRecord.eventName,\n body: logRecord.body,\n attributes: logRecord.attributes,\n };\n }\n\n /**\n * Showing logs in console\n * @param logRecords\n * @param done\n */\n private _sendLogRecords(\n logRecords: ReadableLogRecord[],\n done?: (result: ExportResult) => void\n ): void {\n for (const logRecord of logRecords) {\n console.dir(this._exportInfo(logRecord), { depth: 3 });\n }\n done?.({ code: ExportResultCode.SUCCESS });\n }\n}\n"]}

View File

@@ -0,0 +1,21 @@
import type { ExportResult } from '@opentelemetry/core';
import type { ReadableLogRecord } from './ReadableLogRecord';
import type { LogRecordExporter } from './LogRecordExporter';
/**
* This class can be used for testing purposes. It stores the exported LogRecords
* in a list in memory that can be retrieved using the `getFinishedLogRecords()`
* method.
*/
export declare class InMemoryLogRecordExporter implements LogRecordExporter {
private _finishedLogRecords;
/**
* Indicates if the exporter has been "shutdown."
* When false, exported log records will not be stored in-memory.
*/
protected _stopped: boolean;
export(logs: ReadableLogRecord[], resultCallback: (result: ExportResult) => void): void;
shutdown(): Promise<void>;
getFinishedLogRecords(): ReadableLogRecord[];
reset(): void;
}
//# sourceMappingURL=InMemoryLogRecordExporter.d.ts.map

View File

@@ -0,0 +1,40 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { ExportResultCode } from '@opentelemetry/core';
/**
* This class can be used for testing purposes. It stores the exported LogRecords
* in a list in memory that can be retrieved using the `getFinishedLogRecords()`
* method.
*/
export class InMemoryLogRecordExporter {
_finishedLogRecords = [];
/**
* Indicates if the exporter has been "shutdown."
* When false, exported log records will not be stored in-memory.
*/
_stopped = false;
export(logs, resultCallback) {
if (this._stopped) {
return resultCallback({
code: ExportResultCode.FAILED,
error: new Error('Exporter has been stopped'),
});
}
this._finishedLogRecords.push(...logs);
resultCallback({ code: ExportResultCode.SUCCESS });
}
shutdown() {
this._stopped = true;
this.reset();
return Promise.resolve();
}
getFinishedLogRecords() {
return this._finishedLogRecords;
}
reset() {
this._finishedLogRecords = [];
}
}
//# sourceMappingURL=InMemoryLogRecordExporter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"InMemoryLogRecordExporter.js","sourceRoot":"","sources":["../../../src/export/InMemoryLogRecordExporter.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAKvD;;;;GAIG;AACH,MAAM,OAAO,yBAAyB;IAC5B,mBAAmB,GAAwB,EAAE,CAAC;IAEtD;;;OAGG;IACO,QAAQ,GAAG,KAAK,CAAC;IAEpB,MAAM,CACX,IAAyB,EACzB,cAA8C;QAE9C,IAAI,IAAI,CAAC,QAAQ,EAAE;YACjB,OAAO,cAAc,CAAC;gBACpB,IAAI,EAAE,gBAAgB,CAAC,MAAM;gBAC7B,KAAK,EAAE,IAAI,KAAK,CAAC,2BAA2B,CAAC;aAC9C,CAAC,CAAC;SACJ;QAED,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;QACvC,cAAc,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC;IACrD,CAAC;IAEM,QAAQ;QACb,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACrB,IAAI,CAAC,KAAK,EAAE,CAAC;QACb,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAEM,qBAAqB;QAC1B,OAAO,IAAI,CAAC,mBAAmB,CAAC;IAClC,CAAC;IAEM,KAAK;QACV,IAAI,CAAC,mBAAmB,GAAG,EAAE,CAAC;IAChC,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode } from '@opentelemetry/core';\n\nimport type { ReadableLogRecord } from './ReadableLogRecord';\nimport type { LogRecordExporter } from './LogRecordExporter';\n\n/**\n * This class can be used for testing purposes. It stores the exported LogRecords\n * in a list in memory that can be retrieved using the `getFinishedLogRecords()`\n * method.\n */\nexport class InMemoryLogRecordExporter implements LogRecordExporter {\n private _finishedLogRecords: ReadableLogRecord[] = [];\n\n /**\n * Indicates if the exporter has been \"shutdown.\"\n * When false, exported log records will not be stored in-memory.\n */\n protected _stopped = false;\n\n public export(\n logs: ReadableLogRecord[],\n resultCallback: (result: ExportResult) => void\n ) {\n if (this._stopped) {\n return resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Exporter has been stopped'),\n });\n }\n\n this._finishedLogRecords.push(...logs);\n resultCallback({ code: ExportResultCode.SUCCESS });\n }\n\n public shutdown(): Promise<void> {\n this._stopped = true;\n this.reset();\n return Promise.resolve();\n }\n\n public getFinishedLogRecords(): ReadableLogRecord[] {\n return this._finishedLogRecords;\n }\n\n public reset(): void {\n this._finishedLogRecords = [];\n }\n}\n"]}

View File

@@ -0,0 +1,12 @@
import type { ExportResult } from '@opentelemetry/core';
import type { ReadableLogRecord } from './ReadableLogRecord';
export interface LogRecordExporter {
/**
* Called to export {@link ReadableLogRecord}s.
* @param logs the list of sampled LogRecords to be exported.
*/
export(logs: ReadableLogRecord[], resultCallback: (result: ExportResult) => void): void;
/** Stops the exporter. */
shutdown(): Promise<void>;
}
//# sourceMappingURL=LogRecordExporter.d.ts.map

View File

@@ -0,0 +1,6 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=LogRecordExporter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"LogRecordExporter.js","sourceRoot":"","sources":["../../../src/export/LogRecordExporter.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ExportResult } from '@opentelemetry/core';\n\nimport type { ReadableLogRecord } from './ReadableLogRecord';\n\nexport interface LogRecordExporter {\n /**\n * Called to export {@link ReadableLogRecord}s.\n * @param logs the list of sampled LogRecords to be exported.\n */\n export(\n logs: ReadableLogRecord[],\n resultCallback: (result: ExportResult) => void\n ): void;\n\n /** Stops the exporter. */\n shutdown(): Promise<void>;\n}\n"]}

View File

@@ -0,0 +1,9 @@
import type { Context } from '@opentelemetry/api';
import type { LogRecordProcessor } from '../LogRecordProcessor';
import type { ReadableLogRecord } from './ReadableLogRecord';
export declare class NoopLogRecordProcessor implements LogRecordProcessor {
forceFlush(): Promise<void>;
onEmit(_logRecord: ReadableLogRecord, _context: Context): void;
shutdown(): Promise<void>;
}
//# sourceMappingURL=NoopLogRecordProcessor.d.ts.map

View File

@@ -0,0 +1,14 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export class NoopLogRecordProcessor {
forceFlush() {
return Promise.resolve();
}
onEmit(_logRecord, _context) { }
shutdown() {
return Promise.resolve();
}
}
//# sourceMappingURL=NoopLogRecordProcessor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"NoopLogRecordProcessor.js","sourceRoot":"","sources":["../../../src/export/NoopLogRecordProcessor.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAMH,MAAM,OAAO,sBAAsB;IACjC,UAAU;QACR,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED,MAAM,CAAC,UAA6B,EAAE,QAAiB,IAAS,CAAC;IAEjE,QAAQ;QACN,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport type { LogRecordProcessor } from '../LogRecordProcessor';\nimport type { ReadableLogRecord } from './ReadableLogRecord';\n\nexport class NoopLogRecordProcessor implements LogRecordProcessor {\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n onEmit(_logRecord: ReadableLogRecord, _context: Context): void {}\n\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n}\n"]}

View File

@@ -0,0 +1,18 @@
import type { Resource } from '@opentelemetry/resources';
import type { HrTime, SpanContext } from '@opentelemetry/api';
import type { InstrumentationScope } from '@opentelemetry/core';
import type { LogBody, LogAttributes, SeverityNumber } from '@opentelemetry/api-logs';
export interface ReadableLogRecord {
readonly hrTime: HrTime;
readonly hrTimeObserved: HrTime;
readonly spanContext?: SpanContext;
readonly severityText?: string;
readonly severityNumber?: SeverityNumber;
readonly body?: LogBody;
readonly eventName?: string;
readonly resource: Resource;
readonly instrumentationScope: InstrumentationScope;
readonly attributes: LogAttributes;
readonly droppedAttributesCount: number;
}
//# sourceMappingURL=ReadableLogRecord.d.ts.map

View File

@@ -0,0 +1,6 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=ReadableLogRecord.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ReadableLogRecord.js","sourceRoot":"","sources":["../../../src/export/ReadableLogRecord.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Resource } from '@opentelemetry/resources';\nimport type { HrTime, SpanContext } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type {\n LogBody,\n LogAttributes,\n SeverityNumber,\n} from '@opentelemetry/api-logs';\n\nexport interface ReadableLogRecord {\n readonly hrTime: HrTime;\n readonly hrTimeObserved: HrTime;\n readonly spanContext?: SpanContext;\n readonly severityText?: string;\n readonly severityNumber?: SeverityNumber;\n readonly body?: LogBody;\n readonly eventName?: string;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n readonly attributes: LogAttributes;\n readonly droppedAttributesCount: number;\n}\n"]}

View File

@@ -0,0 +1,64 @@
import type { HrTime, SpanContext } from '@opentelemetry/api';
import type { InstrumentationScope } from '@opentelemetry/core';
import type { AnyValue, LogBody, LogAttributes, SeverityNumber } from '@opentelemetry/api-logs';
import type { Resource } from '@opentelemetry/resources';
/**
* A recording of an event. Typically, the record includes a timestamp indicating when the
* event happened as well as other data that describes what happened, where it happened, etc.
*
* @remarks
* This interface is **not intended to be implemented by users**.
* To produce logs, use {@link Logger#emit}. To consume logs, implement {@link LogRecordProcessor#onEmit}.
* SdkLogRecord instances are created and managed by the SDK.
*/
export interface SdkLogRecord {
readonly hrTime: HrTime;
readonly hrTimeObserved: HrTime;
readonly spanContext?: SpanContext;
readonly resource: Resource;
readonly instrumentationScope: InstrumentationScope;
readonly attributes: LogAttributes;
severityText?: string;
severityNumber?: SeverityNumber;
body?: LogBody;
eventName?: string;
droppedAttributesCount: number;
/**
* Sets a single attribute on the log record.
* @param key The attribute key.
* @param value The attribute value.
* @returns The updated SdkLogRecord.
*/
setAttribute(key: string, value?: AnyValue): SdkLogRecord;
/**
* Sets multiple attributes on the log record.
* @param attributes The attributes to set.
* @returns The updated SdkLogRecord.
*/
setAttributes(attributes: LogAttributes): SdkLogRecord;
/**
* Sets the body of the log record.
* @param body The log body.
* @returns The updated SdkLogRecord.
*/
setBody(body: LogBody): SdkLogRecord;
/**
* Sets the event name for the log record.
* @param eventName The event name.
* @returns The updated SdkLogRecord.
*/
setEventName(eventName: string): SdkLogRecord;
/**
* Sets the severity number for the log record.
* @param severityNumber The severity number.
* @returns The updated SdkLogRecord.
*/
setSeverityNumber(severityNumber: SeverityNumber): SdkLogRecord;
/**
* Sets the severity text (log level) for the log record.
* @param severityText The severity text.
* @returns The updated SdkLogRecord.
*/
setSeverityText(severityText: string): SdkLogRecord;
}
//# sourceMappingURL=SdkLogRecord.d.ts.map

View File

@@ -0,0 +1,6 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=SdkLogRecord.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"SdkLogRecord.js","sourceRoot":"","sources":["../../../src/export/SdkLogRecord.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { HrTime, SpanContext } from '@opentelemetry/api';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type {\n AnyValue,\n LogBody,\n LogAttributes,\n SeverityNumber,\n} from '@opentelemetry/api-logs';\nimport type { Resource } from '@opentelemetry/resources';\n\n/**\n * A recording of an event. Typically, the record includes a timestamp indicating when the\n * event happened as well as other data that describes what happened, where it happened, etc.\n *\n * @remarks\n * This interface is **not intended to be implemented by users**.\n * To produce logs, use {@link Logger#emit}. To consume logs, implement {@link LogRecordProcessor#onEmit}.\n * SdkLogRecord instances are created and managed by the SDK.\n */\nexport interface SdkLogRecord {\n readonly hrTime: HrTime;\n readonly hrTimeObserved: HrTime;\n readonly spanContext?: SpanContext;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n readonly attributes: LogAttributes;\n severityText?: string;\n severityNumber?: SeverityNumber;\n body?: LogBody;\n eventName?: string;\n droppedAttributesCount: number;\n\n /**\n * Sets a single attribute on the log record.\n * @param key The attribute key.\n * @param value The attribute value.\n * @returns The updated SdkLogRecord.\n */\n setAttribute(key: string, value?: AnyValue): SdkLogRecord;\n\n /**\n * Sets multiple attributes on the log record.\n * @param attributes The attributes to set.\n * @returns The updated SdkLogRecord.\n */\n setAttributes(attributes: LogAttributes): SdkLogRecord;\n\n /**\n * Sets the body of the log record.\n * @param body The log body.\n * @returns The updated SdkLogRecord.\n */\n setBody(body: LogBody): SdkLogRecord;\n\n /**\n * Sets the event name for the log record.\n * @param eventName The event name.\n * @returns The updated SdkLogRecord.\n */\n setEventName(eventName: string): SdkLogRecord;\n\n /**\n * Sets the severity number for the log record.\n * @param severityNumber The severity number.\n * @returns The updated SdkLogRecord.\n */\n setSeverityNumber(severityNumber: SeverityNumber): SdkLogRecord;\n\n /**\n * Sets the severity text (log level) for the log record.\n * @param severityText The severity text.\n * @returns The updated SdkLogRecord.\n */\n setSeverityText(severityText: string): SdkLogRecord;\n}\n"]}

View File

@@ -0,0 +1,23 @@
import type { LogRecordExporter } from './LogRecordExporter';
import type { LogRecordProcessor } from '../LogRecordProcessor';
import type { SdkLogRecord } from './SdkLogRecord';
/**
* An implementation of the {@link LogRecordProcessor} interface that exports
* each {@link LogRecord} as it is emitted.
*
* NOTE: This {@link LogRecordProcessor} exports every {@link LogRecord}
* individually instead of batching them together, which can cause significant
* performance overhead with most exporters. For production use, please consider
* using the {@link BatchLogRecordProcessor} instead.
*/
export declare class SimpleLogRecordProcessor implements LogRecordProcessor {
private readonly _exporter;
private _shutdownOnce;
private _unresolvedExports;
constructor(exporter: LogRecordExporter);
onEmit(logRecord: SdkLogRecord): void;
forceFlush(): Promise<void>;
shutdown(): Promise<void>;
private _shutdown;
}
//# sourceMappingURL=SimpleLogRecordProcessor.d.ts.map

View File

@@ -0,0 +1,68 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { BindOnceFuture, ExportResultCode, globalErrorHandler, internal, } from '@opentelemetry/core';
/**
* An implementation of the {@link LogRecordProcessor} interface that exports
* each {@link LogRecord} as it is emitted.
*
* NOTE: This {@link LogRecordProcessor} exports every {@link LogRecord}
* individually instead of batching them together, which can cause significant
* performance overhead with most exporters. For production use, please consider
* using the {@link BatchLogRecordProcessor} instead.
*/
export class SimpleLogRecordProcessor {
_exporter;
_shutdownOnce;
_unresolvedExports;
constructor(exporter) {
this._exporter = exporter;
this._shutdownOnce = new BindOnceFuture(this._shutdown, this);
this._unresolvedExports = new Set();
}
onEmit(logRecord) {
if (this._shutdownOnce.isCalled) {
return;
}
const doExport = () => internal
._export(this._exporter, [logRecord])
.then((result) => {
if (result.code !== ExportResultCode.SUCCESS) {
globalErrorHandler(result.error ??
new Error(`SimpleLogRecordProcessor: log record export failed (status ${result})`));
}
})
.catch(globalErrorHandler);
// Avoid scheduling a promise to make the behavior more predictable and easier to test
if (logRecord.resource.asyncAttributesPending) {
const exportPromise = logRecord.resource
.waitForAsyncAttributes?.()
.then(() => {
// Using TS Non-null assertion operator because exportPromise could not be null in here
// if waitForAsyncAttributes is not present this code will never be reached
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this._unresolvedExports.delete(exportPromise);
return doExport();
}, globalErrorHandler);
// store the unresolved exports
if (exportPromise != null) {
this._unresolvedExports.add(exportPromise);
}
}
else {
void doExport();
}
}
async forceFlush() {
// await unresolved resources before resolving
await Promise.all(Array.from(this._unresolvedExports));
}
shutdown() {
return this._shutdownOnce.call();
}
_shutdown() {
return this._exporter.shutdown();
}
}
//# sourceMappingURL=SimpleLogRecordProcessor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"SimpleLogRecordProcessor.js","sourceRoot":"","sources":["../../../src/export/SimpleLogRecordProcessor.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,kBAAkB,EAClB,QAAQ,GACT,MAAM,qBAAqB,CAAC;AAK7B;;;;;;;;GAQG;AACH,MAAM,OAAO,wBAAwB;IAClB,SAAS,CAAoB;IACtC,aAAa,CAAuB;IACpC,kBAAkB,CAAqB;IAE/C,YAAY,QAA2B;QACrC,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC1B,IAAI,CAAC,aAAa,GAAG,IAAI,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;QAC9D,IAAI,CAAC,kBAAkB,GAAG,IAAI,GAAG,EAAiB,CAAC;IACrD,CAAC;IAEM,MAAM,CAAC,SAAuB;QACnC,IAAI,IAAI,CAAC,aAAa,CAAC,QAAQ,EAAE;YAC/B,OAAO;SACR;QAED,MAAM,QAAQ,GAAG,GAAG,EAAE,CACpB,QAAQ;aACL,OAAO,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC,SAAS,CAAC,CAAC;aACpC,IAAI,CAAC,CAAC,MAAoB,EAAE,EAAE;YAC7B,IAAI,MAAM,CAAC,IAAI,KAAK,gBAAgB,CAAC,OAAO,EAAE;gBAC5C,kBAAkB,CAChB,MAAM,CAAC,KAAK;oBACV,IAAI,KAAK,CACP,8DAA8D,MAAM,GAAG,CACxE,CACJ,CAAC;aACH;QACH,CAAC,CAAC;aACD,KAAK,CAAC,kBAAkB,CAAC,CAAC;QAE/B,sFAAsF;QACtF,IAAI,SAAS,CAAC,QAAQ,CAAC,sBAAsB,EAAE;YAC7C,MAAM,aAAa,GAAG,SAAS,CAAC,QAAQ;iBACrC,sBAAsB,EAAE,EAAE;iBAC1B,IAAI,CAAC,GAAG,EAAE;gBACT,uFAAuF;gBACvF,2EAA2E;gBAC3E,oEAAoE;gBACpE,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,aAAc,CAAC,CAAC;gBAC/C,OAAO,QAAQ,EAAE,CAAC;YACpB,CAAC,EAAE,kBAAkB,CAAC,CAAC;YAEzB,+BAA+B;YAC/B,IAAI,aAAa,IAAI,IAAI,EAAE;gBACzB,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;aAC5C;SACF;aAAM;YACL,KAAK,QAAQ,EAAE,CAAC;SACjB;IACH,CAAC;IAEM,KAAK,CAAC,UAAU;QACrB,8CAA8C;QAC9C,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,CAAC;IACzD,CAAC;IAEM,QAAQ;QACb,OAAO,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC;IACnC,CAAC;IAEO,SAAS;QACf,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;IACnC,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ExportResult } from '@opentelemetry/core';\nimport {\n BindOnceFuture,\n ExportResultCode,\n globalErrorHandler,\n internal,\n} from '@opentelemetry/core';\nimport type { LogRecordExporter } from './LogRecordExporter';\nimport type { LogRecordProcessor } from '../LogRecordProcessor';\nimport type { SdkLogRecord } from './SdkLogRecord';\n\n/**\n * An implementation of the {@link LogRecordProcessor} interface that exports\n * each {@link LogRecord} as it is emitted.\n *\n * NOTE: This {@link LogRecordProcessor} exports every {@link LogRecord}\n * individually instead of batching them together, which can cause significant\n * performance overhead with most exporters. For production use, please consider\n * using the {@link BatchLogRecordProcessor} instead.\n */\nexport class SimpleLogRecordProcessor implements LogRecordProcessor {\n private readonly _exporter: LogRecordExporter;\n private _shutdownOnce: BindOnceFuture<void>;\n private _unresolvedExports: Set<Promise<void>>;\n\n constructor(exporter: LogRecordExporter) {\n this._exporter = exporter;\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n this._unresolvedExports = new Set<Promise<void>>();\n }\n\n public onEmit(logRecord: SdkLogRecord): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n const doExport = () =>\n internal\n ._export(this._exporter, [logRecord])\n .then((result: ExportResult) => {\n if (result.code !== ExportResultCode.SUCCESS) {\n globalErrorHandler(\n result.error ??\n new Error(\n `SimpleLogRecordProcessor: log record export failed (status ${result})`\n )\n );\n }\n })\n .catch(globalErrorHandler);\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (logRecord.resource.asyncAttributesPending) {\n const exportPromise = logRecord.resource\n .waitForAsyncAttributes?.()\n .then(() => {\n // Using TS Non-null assertion operator because exportPromise could not be null in here\n // if waitForAsyncAttributes is not present this code will never be reached\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this._unresolvedExports.delete(exportPromise!);\n return doExport();\n }, globalErrorHandler);\n\n // store the unresolved exports\n if (exportPromise != null) {\n this._unresolvedExports.add(exportPromise);\n }\n } else {\n void doExport();\n }\n }\n\n public async forceFlush(): Promise<void> {\n // await unresolved resources before resolving\n await Promise.all(Array.from(this._unresolvedExports));\n }\n\n public shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown(): Promise<void> {\n return this._exporter.shutdown();\n }\n}\n"]}

View File

@@ -0,0 +1,12 @@
export type { LoggerProviderConfig, LoggerConfig, LoggerConfigurator, LogRecordLimits, BufferConfig, BatchLogRecordProcessorBrowserConfig, } from './types';
export { LoggerProvider } from './LoggerProvider';
export type { SdkLogRecord } from './export/SdkLogRecord';
export type { LogRecordProcessor } from './LogRecordProcessor';
export type { ReadableLogRecord } from './export/ReadableLogRecord';
export { ConsoleLogRecordExporter } from './export/ConsoleLogRecordExporter';
export type { LogRecordExporter } from './export/LogRecordExporter';
export { SimpleLogRecordProcessor } from './export/SimpleLogRecordProcessor';
export { InMemoryLogRecordExporter } from './export/InMemoryLogRecordExporter';
export { BatchLogRecordProcessor } from './platform';
export { createLoggerConfigurator, type LoggerPattern, } from './config/LoggerConfigurators';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,11 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export { LoggerProvider } from './LoggerProvider';
export { ConsoleLogRecordExporter } from './export/ConsoleLogRecordExporter';
export { SimpleLogRecordProcessor } from './export/SimpleLogRecordProcessor';
export { InMemoryLogRecordExporter } from './export/InMemoryLogRecordExporter';
export { BatchLogRecordProcessor } from './platform';
export { createLoggerConfigurator, } from './config/LoggerConfigurators';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAUH,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAIlD,OAAO,EAAE,wBAAwB,EAAE,MAAM,mCAAmC,CAAC;AAE7E,OAAO,EAAE,wBAAwB,EAAE,MAAM,mCAAmC,CAAC;AAC7E,OAAO,EAAE,yBAAyB,EAAE,MAAM,oCAAoC,CAAC;AAC/E,OAAO,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,EACL,wBAAwB,GAEzB,MAAM,8BAA8B,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport type {\n LoggerProviderConfig,\n LoggerConfig,\n LoggerConfigurator,\n LogRecordLimits,\n BufferConfig,\n BatchLogRecordProcessorBrowserConfig,\n} from './types';\nexport { LoggerProvider } from './LoggerProvider';\nexport type { SdkLogRecord } from './export/SdkLogRecord';\nexport type { LogRecordProcessor } from './LogRecordProcessor';\nexport type { ReadableLogRecord } from './export/ReadableLogRecord';\nexport { ConsoleLogRecordExporter } from './export/ConsoleLogRecordExporter';\nexport type { LogRecordExporter } from './export/LogRecordExporter';\nexport { SimpleLogRecordProcessor } from './export/SimpleLogRecordProcessor';\nexport { InMemoryLogRecordExporter } from './export/InMemoryLogRecordExporter';\nexport { BatchLogRecordProcessor } from './platform';\nexport {\n createLoggerConfigurator,\n type LoggerPattern,\n} from './config/LoggerConfigurators';\n"]}

View File

@@ -0,0 +1,30 @@
import type { Logger } from '@opentelemetry/api-logs';
import type { Resource } from '@opentelemetry/resources';
import type { InstrumentationScope } from '@opentelemetry/core';
import type { LogRecordProcessor } from '../LogRecordProcessor';
import type { LogRecordLimits, LoggerConfig, LoggerConfigurator } from '../types';
/**
* Default LoggerConfigurator that returns the default config for all loggers
*/
export declare const DEFAULT_LOGGER_CONFIGURATOR: LoggerConfigurator;
export declare class LoggerProviderSharedState {
readonly loggers: Map<string, Logger>;
activeProcessor: LogRecordProcessor;
readonly registeredLogRecordProcessors: LogRecordProcessor[];
readonly resource: Resource;
readonly forceFlushTimeoutMillis: number;
readonly logRecordLimits: Required<LogRecordLimits>;
readonly processors: LogRecordProcessor[];
private _loggerConfigurator;
private _loggerConfigs;
constructor(resource: Resource, forceFlushTimeoutMillis: number, logRecordLimits: Required<LogRecordLimits>, processors: LogRecordProcessor[], loggerConfigurator?: LoggerConfigurator);
/**
* Get the LoggerConfig for a given instrumentation scope.
* Uses the LoggerConfigurator function to compute the config on first access
* and caches the result.
*
* @experimental This feature is in development as per the OpenTelemetry specification.
*/
getLoggerConfig(instrumentationScope: InstrumentationScope): Required<LoggerConfig>;
}
//# sourceMappingURL=LoggerProviderSharedState.d.ts.map

View File

@@ -0,0 +1,67 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { SeverityNumber } from '@opentelemetry/api-logs';
import { NoopLogRecordProcessor } from '../export/NoopLogRecordProcessor';
import { MultiLogRecordProcessor } from '../MultiLogRecordProcessor';
import { getInstrumentationScopeKey } from './utils';
const DEFAULT_LOGGER_CONFIG = {
disabled: false,
minimumSeverity: SeverityNumber.UNSPECIFIED,
traceBased: false,
};
/**
* Default LoggerConfigurator that returns the default config for all loggers
*/
export const DEFAULT_LOGGER_CONFIGURATOR = () => ({
...DEFAULT_LOGGER_CONFIG,
});
export class LoggerProviderSharedState {
loggers = new Map();
activeProcessor;
registeredLogRecordProcessors = [];
resource;
forceFlushTimeoutMillis;
logRecordLimits;
processors;
_loggerConfigurator;
_loggerConfigs = new Map();
constructor(resource, forceFlushTimeoutMillis, logRecordLimits, processors, loggerConfigurator) {
this.resource = resource;
this.forceFlushTimeoutMillis = forceFlushTimeoutMillis;
this.logRecordLimits = logRecordLimits;
this.processors = processors;
if (processors.length > 0) {
this.registeredLogRecordProcessors = processors;
this.activeProcessor = new MultiLogRecordProcessor(this.registeredLogRecordProcessors, this.forceFlushTimeoutMillis);
}
else {
this.activeProcessor = new NoopLogRecordProcessor();
}
this._loggerConfigurator =
loggerConfigurator ?? DEFAULT_LOGGER_CONFIGURATOR;
}
/**
* Get the LoggerConfig for a given instrumentation scope.
* Uses the LoggerConfigurator function to compute the config on first access
* and caches the result.
*
* @experimental This feature is in development as per the OpenTelemetry specification.
*/
getLoggerConfig(instrumentationScope) {
const key = getInstrumentationScopeKey(instrumentationScope);
// Return cached config if available
let config = this._loggerConfigs.get(key);
if (config) {
return config;
}
// Compute config using the configurator
// The configurator always returns a complete config
config = this._loggerConfigurator(instrumentationScope);
// Cache the result
this._loggerConfigs.set(key, config);
return config;
}
}
//# sourceMappingURL=LoggerProviderSharedState.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"LoggerProviderSharedState.js","sourceRoot":"","sources":["../../../src/internal/LoggerProviderSharedState.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AASzD,OAAO,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAC;AAC1E,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,EAAE,0BAA0B,EAAE,MAAM,SAAS,CAAC;AAErD,MAAM,qBAAqB,GAA2B;IACpD,QAAQ,EAAE,KAAK;IACf,eAAe,EAAE,cAAc,CAAC,WAAW;IAC3C,UAAU,EAAE,KAAK;CAClB,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAuB,GAAG,EAAE,CAAC,CAAC;IACpE,GAAG,qBAAqB;CACzB,CAAC,CAAC;AAEH,MAAM,OAAO,yBAAyB;IAC3B,OAAO,GAAwB,IAAI,GAAG,EAAE,CAAC;IAClD,eAAe,CAAqB;IAC3B,6BAA6B,GAAyB,EAAE,CAAC;IACzD,QAAQ,CAAW;IACnB,uBAAuB,CAAS;IAChC,eAAe,CAA4B;IAC3C,UAAU,CAAuB;IAClC,mBAAmB,CAAqB;IACxC,cAAc,GAAwC,IAAI,GAAG,EAAE,CAAC;IAExE,YACE,QAAkB,EAClB,uBAA+B,EAC/B,eAA0C,EAC1C,UAAgC,EAChC,kBAAuC;QAEvC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,uBAAuB,GAAG,uBAAuB,CAAC;QACvD,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,EAAE;YACzB,IAAI,CAAC,6BAA6B,GAAG,UAAU,CAAC;YAChD,IAAI,CAAC,eAAe,GAAG,IAAI,uBAAuB,CAChD,IAAI,CAAC,6BAA6B,EAClC,IAAI,CAAC,uBAAuB,CAC7B,CAAC;SACH;aAAM;YACL,IAAI,CAAC,eAAe,GAAG,IAAI,sBAAsB,EAAE,CAAC;SACrD;QAED,IAAI,CAAC,mBAAmB;YACtB,kBAAkB,IAAI,2BAA2B,CAAC;IACtD,CAAC;IAED;;;;;;OAMG;IACH,eAAe,CACb,oBAA0C;QAE1C,MAAM,GAAG,GAAG,0BAA0B,CAAC,oBAAoB,CAAC,CAAC;QAE7D,oCAAoC;QACpC,IAAI,MAAM,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC1C,IAAI,MAAM,EAAE;YACV,OAAO,MAAM,CAAC;SACf;QAED,wCAAwC;QACxC,oDAAoD;QACpD,MAAM,GAAG,IAAI,CAAC,mBAAmB,CAAC,oBAAoB,CAAC,CAAC;QAExD,mBAAmB;QACnB,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QAErC,OAAO,MAAM,CAAC;IAChB,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Logger } from '@opentelemetry/api-logs';\nimport { SeverityNumber } from '@opentelemetry/api-logs';\nimport type { Resource } from '@opentelemetry/resources';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type { LogRecordProcessor } from '../LogRecordProcessor';\nimport type {\n LogRecordLimits,\n LoggerConfig,\n LoggerConfigurator,\n} from '../types';\nimport { NoopLogRecordProcessor } from '../export/NoopLogRecordProcessor';\nimport { MultiLogRecordProcessor } from '../MultiLogRecordProcessor';\nimport { getInstrumentationScopeKey } from './utils';\n\nconst DEFAULT_LOGGER_CONFIG: Required<LoggerConfig> = {\n disabled: false,\n minimumSeverity: SeverityNumber.UNSPECIFIED,\n traceBased: false,\n};\n\n/**\n * Default LoggerConfigurator that returns the default config for all loggers\n */\nexport const DEFAULT_LOGGER_CONFIGURATOR: LoggerConfigurator = () => ({\n ...DEFAULT_LOGGER_CONFIG,\n});\n\nexport class LoggerProviderSharedState {\n readonly loggers: Map<string, Logger> = new Map();\n activeProcessor: LogRecordProcessor;\n readonly registeredLogRecordProcessors: LogRecordProcessor[] = [];\n readonly resource: Resource;\n readonly forceFlushTimeoutMillis: number;\n readonly logRecordLimits: Required<LogRecordLimits>;\n readonly processors: LogRecordProcessor[];\n private _loggerConfigurator: LoggerConfigurator;\n private _loggerConfigs: Map<string, Required<LoggerConfig>> = new Map();\n\n constructor(\n resource: Resource,\n forceFlushTimeoutMillis: number,\n logRecordLimits: Required<LogRecordLimits>,\n processors: LogRecordProcessor[],\n loggerConfigurator?: LoggerConfigurator\n ) {\n this.resource = resource;\n this.forceFlushTimeoutMillis = forceFlushTimeoutMillis;\n this.logRecordLimits = logRecordLimits;\n this.processors = processors;\n if (processors.length > 0) {\n this.registeredLogRecordProcessors = processors;\n this.activeProcessor = new MultiLogRecordProcessor(\n this.registeredLogRecordProcessors,\n this.forceFlushTimeoutMillis\n );\n } else {\n this.activeProcessor = new NoopLogRecordProcessor();\n }\n\n this._loggerConfigurator =\n loggerConfigurator ?? DEFAULT_LOGGER_CONFIGURATOR;\n }\n\n /**\n * Get the LoggerConfig for a given instrumentation scope.\n * Uses the LoggerConfigurator function to compute the config on first access\n * and caches the result.\n *\n * @experimental This feature is in development as per the OpenTelemetry specification.\n */\n getLoggerConfig(\n instrumentationScope: InstrumentationScope\n ): Required<LoggerConfig> {\n const key = getInstrumentationScopeKey(instrumentationScope);\n\n // Return cached config if available\n let config = this._loggerConfigs.get(key);\n if (config) {\n return config;\n }\n\n // Compute config using the configurator\n // The configurator always returns a complete config\n config = this._loggerConfigurator(instrumentationScope);\n\n // Cache the result\n this._loggerConfigs.set(key, config);\n\n return config;\n }\n}\n"]}

View File

@@ -0,0 +1,8 @@
import type { InstrumentationScope } from '@opentelemetry/core';
/**
* Converting the instrumentation scope object to a unique identifier string.
* @param scope - The instrumentation scope to convert
* @returns A unique string identifier for the scope
*/
export declare function getInstrumentationScopeKey(scope: InstrumentationScope): string;
//# sourceMappingURL=utils.d.ts.map

View File

@@ -0,0 +1,13 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Converting the instrumentation scope object to a unique identifier string.
* @param scope - The instrumentation scope to convert
* @returns A unique string identifier for the scope
*/
export function getInstrumentationScopeKey(scope) {
return `${scope.name}@${scope.version || ''}:${scope.schemaUrl || ''}`;
}
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/internal/utils.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH;;;;GAIG;AACH,MAAM,UAAU,0BAA0B,CACxC,KAA2B;IAE3B,OAAO,GAAG,KAAK,CAAC,IAAI,IAAI,KAAK,CAAC,OAAO,IAAI,EAAE,IAAI,KAAK,CAAC,SAAS,IAAI,EAAE,EAAE,CAAC;AACzE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { InstrumentationScope } from '@opentelemetry/core';\n\n/**\n * Converting the instrumentation scope object to a unique identifier string.\n * @param scope - The instrumentation scope to convert\n * @returns A unique string identifier for the scope\n */\nexport function getInstrumentationScopeKey(\n scope: InstrumentationScope\n): string {\n return `${scope.name}@${scope.version || ''}:${scope.schemaUrl || ''}`;\n}\n"]}

View File

@@ -0,0 +1,11 @@
import type { LogRecordExporter } from './../../../export/LogRecordExporter';
import type { BatchLogRecordProcessorBrowserConfig } from '../../../types';
import { BatchLogRecordProcessorBase } from '../../../export/BatchLogRecordProcessorBase';
export declare class BatchLogRecordProcessor extends BatchLogRecordProcessorBase<BatchLogRecordProcessorBrowserConfig> {
private _visibilityChangeListener?;
private _pageHideListener?;
constructor(exporter: LogRecordExporter, config?: BatchLogRecordProcessorBrowserConfig);
protected onShutdown(): void;
private _onInit;
}
//# sourceMappingURL=BatchLogRecordProcessor.d.ts.map

View File

@@ -0,0 +1,42 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { BatchLogRecordProcessorBase } from '../../../export/BatchLogRecordProcessorBase';
export class BatchLogRecordProcessor extends BatchLogRecordProcessorBase {
_visibilityChangeListener;
_pageHideListener;
constructor(exporter, config) {
super(exporter, config);
this._onInit(config);
}
onShutdown() {
if (typeof document === 'undefined') {
return;
}
if (this._visibilityChangeListener) {
document.removeEventListener('visibilitychange', this._visibilityChangeListener);
}
if (this._pageHideListener) {
document.removeEventListener('pagehide', this._pageHideListener);
}
}
_onInit(config) {
if (config?.disableAutoFlushOnDocumentHide === true ||
typeof document === 'undefined') {
return;
}
this._visibilityChangeListener = () => {
if (document.visibilityState === 'hidden') {
void this.forceFlush();
}
};
this._pageHideListener = () => {
void this.forceFlush();
};
document.addEventListener('visibilitychange', this._visibilityChangeListener);
// use 'pagehide' event as a fallback for Safari; see https://bugs.webkit.org/show_bug.cgi?id=116769
document.addEventListener('pagehide', this._pageHideListener);
}
}
//# sourceMappingURL=BatchLogRecordProcessor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"BatchLogRecordProcessor.js","sourceRoot":"","sources":["../../../../../src/platform/browser/export/BatchLogRecordProcessor.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,EAAE,2BAA2B,EAAE,MAAM,6CAA6C,CAAC;AAE1F,MAAM,OAAO,uBAAwB,SAAQ,2BAAiE;IACpG,yBAAyB,CAAc;IACvC,iBAAiB,CAAc;IAEvC,YACE,QAA2B,EAC3B,MAA6C;QAE7C,KAAK,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;QACxB,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACvB,CAAC;IAES,UAAU;QAClB,IAAI,OAAO,QAAQ,KAAK,WAAW,EAAE;YACnC,OAAO;SACR;QACD,IAAI,IAAI,CAAC,yBAAyB,EAAE;YAClC,QAAQ,CAAC,mBAAmB,CAC1B,kBAAkB,EAClB,IAAI,CAAC,yBAAyB,CAC/B,CAAC;SACH;QACD,IAAI,IAAI,CAAC,iBAAiB,EAAE;YAC1B,QAAQ,CAAC,mBAAmB,CAAC,UAAU,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC;SAClE;IACH,CAAC;IAEO,OAAO,CAAC,MAA6C;QAC3D,IACE,MAAM,EAAE,8BAA8B,KAAK,IAAI;YAC/C,OAAO,QAAQ,KAAK,WAAW,EAC/B;YACA,OAAO;SACR;QACD,IAAI,CAAC,yBAAyB,GAAG,GAAG,EAAE;YACpC,IAAI,QAAQ,CAAC,eAAe,KAAK,QAAQ,EAAE;gBACzC,KAAK,IAAI,CAAC,UAAU,EAAE,CAAC;aACxB;QACH,CAAC,CAAC;QACF,IAAI,CAAC,iBAAiB,GAAG,GAAG,EAAE;YAC5B,KAAK,IAAI,CAAC,UAAU,EAAE,CAAC;QACzB,CAAC,CAAC;QACF,QAAQ,CAAC,gBAAgB,CACvB,kBAAkB,EAClB,IAAI,CAAC,yBAAyB,CAC/B,CAAC;QAEF,oGAAoG;QACpG,QAAQ,CAAC,gBAAgB,CAAC,UAAU,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC;IAChE,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { LogRecordExporter } from './../../../export/LogRecordExporter';\nimport type { BatchLogRecordProcessorBrowserConfig } from '../../../types';\nimport { BatchLogRecordProcessorBase } from '../../../export/BatchLogRecordProcessorBase';\n\nexport class BatchLogRecordProcessor extends BatchLogRecordProcessorBase<BatchLogRecordProcessorBrowserConfig> {\n private _visibilityChangeListener?: () => void;\n private _pageHideListener?: () => void;\n\n constructor(\n exporter: LogRecordExporter,\n config?: BatchLogRecordProcessorBrowserConfig\n ) {\n super(exporter, config);\n this._onInit(config);\n }\n\n protected onShutdown(): void {\n if (typeof document === 'undefined') {\n return;\n }\n if (this._visibilityChangeListener) {\n document.removeEventListener(\n 'visibilitychange',\n this._visibilityChangeListener\n );\n }\n if (this._pageHideListener) {\n document.removeEventListener('pagehide', this._pageHideListener);\n }\n }\n\n private _onInit(config?: BatchLogRecordProcessorBrowserConfig): void {\n if (\n config?.disableAutoFlushOnDocumentHide === true ||\n typeof document === 'undefined'\n ) {\n return;\n }\n this._visibilityChangeListener = () => {\n if (document.visibilityState === 'hidden') {\n void this.forceFlush();\n }\n };\n this._pageHideListener = () => {\n void this.forceFlush();\n };\n document.addEventListener(\n 'visibilitychange',\n this._visibilityChangeListener\n );\n\n // use 'pagehide' event as a fallback for Safari; see https://bugs.webkit.org/show_bug.cgi?id=116769\n document.addEventListener('pagehide', this._pageHideListener);\n }\n}\n"]}

View File

@@ -0,0 +1,2 @@
export { BatchLogRecordProcessor } from './export/BatchLogRecordProcessor';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,6 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export { BatchLogRecordProcessor } from './export/BatchLogRecordProcessor';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/browser/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,kCAAkC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BatchLogRecordProcessor } from './export/BatchLogRecordProcessor';\n"]}

View File

@@ -0,0 +1,2 @@
export { BatchLogRecordProcessor } from './node';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,6 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export { BatchLogRecordProcessor } from './node';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/platform/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,QAAQ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BatchLogRecordProcessor } from './node';\n"]}

View File

@@ -0,0 +1,6 @@
import type { BufferConfig } from '../../../types';
import { BatchLogRecordProcessorBase } from '../../../export/BatchLogRecordProcessorBase';
export declare class BatchLogRecordProcessor extends BatchLogRecordProcessorBase<BufferConfig> {
protected onShutdown(): void;
}
//# sourceMappingURL=BatchLogRecordProcessor.d.ts.map

View File

@@ -0,0 +1,9 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { BatchLogRecordProcessorBase } from '../../../export/BatchLogRecordProcessorBase';
export class BatchLogRecordProcessor extends BatchLogRecordProcessorBase {
onShutdown() { }
}
//# sourceMappingURL=BatchLogRecordProcessor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"BatchLogRecordProcessor.js","sourceRoot":"","sources":["../../../../../src/platform/node/export/BatchLogRecordProcessor.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,2BAA2B,EAAE,MAAM,6CAA6C,CAAC;AAE1F,MAAM,OAAO,uBAAwB,SAAQ,2BAAyC;IAC1E,UAAU,KAAU,CAAC;CAChC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { BufferConfig } from '../../../types';\nimport { BatchLogRecordProcessorBase } from '../../../export/BatchLogRecordProcessorBase';\n\nexport class BatchLogRecordProcessor extends BatchLogRecordProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n"]}

View File

@@ -0,0 +1,2 @@
export { BatchLogRecordProcessor } from './export/BatchLogRecordProcessor';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,6 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export { BatchLogRecordProcessor } from './export/BatchLogRecordProcessor';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/node/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,kCAAkC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport { BatchLogRecordProcessor } from './export/BatchLogRecordProcessor';\n"]}

View File

@@ -0,0 +1,97 @@
import type { Resource } from '@opentelemetry/resources';
import type { SeverityNumber } from '@opentelemetry/api-logs';
import type { InstrumentationScope } from '@opentelemetry/core';
import type { LogRecordProcessor } from './LogRecordProcessor';
/**
* A LoggerConfig defines various configurable aspects of a Logger's behavior.
*
* @experimental This feature is in development as per the OpenTelemetry specification.
*/
export interface LoggerConfig {
/**
* A boolean indication of whether the logger is enabled.
* If a Logger is disabled, it behaves equivalently to a No-op Logger.
* Defaults to false (loggers are enabled by default).
*
* @experimental This feature is in development as per the OpenTelemetry specification.
*/
disabled?: boolean;
/**
* A SeverityNumber indicating the minimum severity level for log records to be processed.
* If not explicitly set, defaults to 0 (UNSPECIFIED).
* Log records with a specified severity (i.e. not 0) that is less than this value will be dropped.
* Log records with unspecified severity (0) bypass this filter.
*
* @experimental This feature is in development as per the OpenTelemetry specification.
*/
minimumSeverity?: SeverityNumber;
/**
* A boolean indication of whether the logger should only process log records
* associated with sampled traces.
* If not explicitly set, defaults to false.
* If true, log records associated with unsampled traces will be dropped.
*
* @experimental This feature is in development as per the OpenTelemetry specification.
*/
traceBased?: boolean;
}
/**
* A LoggerConfigurator is a function which computes the LoggerConfig for a Logger.
* It is called when a Logger is first created, and for each outstanding Logger
* when a LoggerProvider's LoggerConfigurator is updated (if updating is supported).
*
* The function must return the complete LoggerConfig for the given logger scope.
* All config properties should have their values computed and set to appropriate defaults.
*
* @param loggerScope - The InstrumentationScope of the Logger
* @returns The computed LoggerConfig with all properties set
* @experimental This feature is in development as per the OpenTelemetry specification.
*/
export type LoggerConfigurator = (loggerScope: InstrumentationScope) => Required<LoggerConfig>;
export interface LoggerProviderConfig {
/** Resource associated with trace telemetry */
resource?: Resource;
/**
* How long the forceFlush can run before it is cancelled.
* The default value is 30000ms
*/
forceFlushTimeoutMillis?: number;
/** Log Record Limits*/
logRecordLimits?: LogRecordLimits;
/** Log Record Processors */
processors?: LogRecordProcessor[];
/**
* A function that computes the LoggerConfig for a given logger.
* This is called when a Logger is first created.
*
* @experimental This feature is in development as per the OpenTelemetry specification.
*/
loggerConfigurator?: LoggerConfigurator;
}
export interface LogRecordLimits {
/** attributeValueLengthLimit is maximum allowed attribute value size */
attributeValueLengthLimit?: number;
/** attributeCountLimit is number of attributes per LogRecord */
attributeCountLimit?: number;
}
/** Interface configuration for a buffer. */
export interface BufferConfig {
/** The maximum batch size of every export. It must be smaller or equal to
* maxQueueSize. The default value is 512. */
maxExportBatchSize?: number;
/** The delay interval in milliseconds between two consecutive exports.
* The default value is 5000ms. */
scheduledDelayMillis?: number;
/** How long the export can run before it is cancelled.
* The default value is 30000ms */
exportTimeoutMillis?: number;
/** The maximum queue size. After the size is reached log records are dropped.
* The default value is 2048. */
maxQueueSize?: number;
}
export interface BatchLogRecordProcessorBrowserConfig extends BufferConfig {
/** Disable flush when a user navigates to a new page, closes the tab or the browser, or,
* on mobile, switches to a different app. Auto flush is enabled by default. */
disableAutoFlushOnDocumentHide?: boolean;
}
//# sourceMappingURL=types.d.ts.map

View File

@@ -0,0 +1,6 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Resource } from '@opentelemetry/resources';\nimport type { SeverityNumber } from '@opentelemetry/api-logs';\nimport type { InstrumentationScope } from '@opentelemetry/core';\nimport type { LogRecordProcessor } from './LogRecordProcessor';\n\n/**\n * A LoggerConfig defines various configurable aspects of a Logger's behavior.\n *\n * @experimental This feature is in development as per the OpenTelemetry specification.\n */\nexport interface LoggerConfig {\n /**\n * A boolean indication of whether the logger is enabled.\n * If a Logger is disabled, it behaves equivalently to a No-op Logger.\n * Defaults to false (loggers are enabled by default).\n *\n * @experimental This feature is in development as per the OpenTelemetry specification.\n */\n disabled?: boolean;\n\n /**\n * A SeverityNumber indicating the minimum severity level for log records to be processed.\n * If not explicitly set, defaults to 0 (UNSPECIFIED).\n * Log records with a specified severity (i.e. not 0) that is less than this value will be dropped.\n * Log records with unspecified severity (0) bypass this filter.\n *\n * @experimental This feature is in development as per the OpenTelemetry specification.\n */\n minimumSeverity?: SeverityNumber;\n\n /**\n * A boolean indication of whether the logger should only process log records\n * associated with sampled traces.\n * If not explicitly set, defaults to false.\n * If true, log records associated with unsampled traces will be dropped.\n *\n * @experimental This feature is in development as per the OpenTelemetry specification.\n */\n traceBased?: boolean;\n}\n\n/**\n * A LoggerConfigurator is a function which computes the LoggerConfig for a Logger.\n * It is called when a Logger is first created, and for each outstanding Logger\n * when a LoggerProvider's LoggerConfigurator is updated (if updating is supported).\n *\n * The function must return the complete LoggerConfig for the given logger scope.\n * All config properties should have their values computed and set to appropriate defaults.\n *\n * @param loggerScope - The InstrumentationScope of the Logger\n * @returns The computed LoggerConfig with all properties set\n * @experimental This feature is in development as per the OpenTelemetry specification.\n */\nexport type LoggerConfigurator = (\n loggerScope: InstrumentationScope\n) => Required<LoggerConfig>;\n\nexport interface LoggerProviderConfig {\n /** Resource associated with trace telemetry */\n resource?: Resource;\n\n /**\n * How long the forceFlush can run before it is cancelled.\n * The default value is 30000ms\n */\n forceFlushTimeoutMillis?: number;\n\n /** Log Record Limits*/\n logRecordLimits?: LogRecordLimits;\n\n /** Log Record Processors */\n processors?: LogRecordProcessor[];\n\n /**\n * A function that computes the LoggerConfig for a given logger.\n * This is called when a Logger is first created.\n *\n * @experimental This feature is in development as per the OpenTelemetry specification.\n */\n loggerConfigurator?: LoggerConfigurator;\n}\n\nexport interface LogRecordLimits {\n /** attributeValueLengthLimit is maximum allowed attribute value size */\n attributeValueLengthLimit?: number;\n\n /** attributeCountLimit is number of attributes per LogRecord */\n attributeCountLimit?: number;\n}\n\n/** Interface configuration for a buffer. */\nexport interface BufferConfig {\n /** The maximum batch size of every export. It must be smaller or equal to\n * maxQueueSize. The default value is 512. */\n maxExportBatchSize?: number;\n\n /** The delay interval in milliseconds between two consecutive exports.\n * The default value is 5000ms. */\n scheduledDelayMillis?: number;\n\n /** How long the export can run before it is cancelled.\n * The default value is 30000ms */\n exportTimeoutMillis?: number;\n\n /** The maximum queue size. After the size is reached log records are dropped.\n * The default value is 2048. */\n maxQueueSize?: number;\n}\n\nexport interface BatchLogRecordProcessorBrowserConfig extends BufferConfig {\n /** Disable flush when a user navigates to a new page, closes the tab or the browser, or,\n * on mobile, switches to a different app. Auto flush is enabled by default. */\n disableAutoFlushOnDocumentHide?: boolean;\n}\n"]}

View File

@@ -0,0 +1,15 @@
import type { AnyValue } from '@opentelemetry/api-logs';
/**
* Validates if a value is a valid AnyValue for Log Attributes according to OpenTelemetry spec.
* Log Attributes support a superset of standard Attributes and must support:
* - Scalar values: string, boolean, signed 64 bit integer, or double precision floating point
* - Byte arrays (Uint8Array)
* - Arrays of any values (heterogeneous arrays allowed)
* - Maps from string to any value (nested objects)
* - Empty values (null/undefined)
*
* @param val - The value to validate
* @returns true if the value is a valid AnyValue, false otherwise
*/
export declare function isLogAttributeValue(val: unknown): val is AnyValue;
//# sourceMappingURL=validation.d.ts.map

View File

@@ -0,0 +1,58 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Validates if a value is a valid AnyValue for Log Attributes according to OpenTelemetry spec.
* Log Attributes support a superset of standard Attributes and must support:
* - Scalar values: string, boolean, signed 64 bit integer, or double precision floating point
* - Byte arrays (Uint8Array)
* - Arrays of any values (heterogeneous arrays allowed)
* - Maps from string to any value (nested objects)
* - Empty values (null/undefined)
*
* @param val - The value to validate
* @returns true if the value is a valid AnyValue, false otherwise
*/
export function isLogAttributeValue(val) {
return isLogAttributeValueInternal(val, new WeakSet());
}
function isLogAttributeValueInternal(val, visited) {
// null and undefined are explicitly allowed
if (val == null) {
return true;
}
// Scalar values
if (typeof val === 'string' ||
typeof val === 'number' ||
typeof val === 'boolean') {
return true;
}
// Byte arrays
if (val instanceof Uint8Array) {
return true;
}
// For objects and arrays, check for circular references
if (typeof val === 'object') {
if (visited.has(val)) {
// Circular reference detected - reject it
return false;
}
visited.add(val);
// Arrays (can contain any AnyValue, including heterogeneous)
if (Array.isArray(val)) {
return val.every(item => isLogAttributeValueInternal(item, visited));
}
// Only accept plain objects (not built-in objects like Date, RegExp, Error, etc.)
// Check if it's a plain object by verifying its constructor is Object or it has no constructor
const obj = val;
if (obj.constructor !== Object && obj.constructor !== undefined) {
return false;
}
// Objects/Maps (including empty objects)
// All object properties must be valid AnyValues
return Object.values(obj).every(item => isLogAttributeValueInternal(item, visited));
}
return false;
}
//# sourceMappingURL=validation.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"validation.js","sourceRoot":"","sources":["../../../src/utils/validation.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,mBAAmB,CAAC,GAAY;IAC9C,OAAO,2BAA2B,CAAC,GAAG,EAAE,IAAI,OAAO,EAAE,CAAC,CAAC;AACzD,CAAC;AAED,SAAS,2BAA2B,CAClC,GAAY,EACZ,OAAwB;IAExB,4CAA4C;IAC5C,IAAI,GAAG,IAAI,IAAI,EAAE;QACf,OAAO,IAAI,CAAC;KACb;IAED,gBAAgB;IAChB,IACE,OAAO,GAAG,KAAK,QAAQ;QACvB,OAAO,GAAG,KAAK,QAAQ;QACvB,OAAO,GAAG,KAAK,SAAS,EACxB;QACA,OAAO,IAAI,CAAC;KACb;IAED,cAAc;IACd,IAAI,GAAG,YAAY,UAAU,EAAE;QAC7B,OAAO,IAAI,CAAC;KACb;IAED,wDAAwD;IACxD,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;QAC3B,IAAI,OAAO,CAAC,GAAG,CAAC,GAAa,CAAC,EAAE;YAC9B,0CAA0C;YAC1C,OAAO,KAAK,CAAC;SACd;QACD,OAAO,CAAC,GAAG,CAAC,GAAa,CAAC,CAAC;QAE3B,6DAA6D;QAC7D,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;YACtB,OAAO,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,2BAA2B,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;SACtE;QAED,kFAAkF;QAClF,+FAA+F;QAC/F,MAAM,GAAG,GAAG,GAA8B,CAAC;QAC3C,IAAI,GAAG,CAAC,WAAW,KAAK,MAAM,IAAI,GAAG,CAAC,WAAW,KAAK,SAAS,EAAE;YAC/D,OAAO,KAAK,CAAC;SACd;QAED,yCAAyC;QACzC,gDAAgD;QAChD,OAAO,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CACrC,2BAA2B,CAAC,IAAI,EAAE,OAAO,CAAC,CAC3C,CAAC;KACH;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { AnyValue } from '@opentelemetry/api-logs';\n\n/**\n * Validates if a value is a valid AnyValue for Log Attributes according to OpenTelemetry spec.\n * Log Attributes support a superset of standard Attributes and must support:\n * - Scalar values: string, boolean, signed 64 bit integer, or double precision floating point\n * - Byte arrays (Uint8Array)\n * - Arrays of any values (heterogeneous arrays allowed)\n * - Maps from string to any value (nested objects)\n * - Empty values (null/undefined)\n *\n * @param val - The value to validate\n * @returns true if the value is a valid AnyValue, false otherwise\n */\nexport function isLogAttributeValue(val: unknown): val is AnyValue {\n return isLogAttributeValueInternal(val, new WeakSet());\n}\n\nfunction isLogAttributeValueInternal(\n val: unknown,\n visited: WeakSet<object>\n): val is AnyValue {\n // null and undefined are explicitly allowed\n if (val == null) {\n return true;\n }\n\n // Scalar values\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n return true;\n }\n\n // Byte arrays\n if (val instanceof Uint8Array) {\n return true;\n }\n\n // For objects and arrays, check for circular references\n if (typeof val === 'object') {\n if (visited.has(val as object)) {\n // Circular reference detected - reject it\n return false;\n }\n visited.add(val as object);\n\n // Arrays (can contain any AnyValue, including heterogeneous)\n if (Array.isArray(val)) {\n return val.every(item => isLogAttributeValueInternal(item, visited));\n }\n\n // Only accept plain objects (not built-in objects like Date, RegExp, Error, etc.)\n // Check if it's a plain object by verifying its constructor is Object or it has no constructor\n const obj = val as Record<string, unknown>;\n if (obj.constructor !== Object && obj.constructor !== undefined) {\n return false;\n }\n\n // Objects/Maps (including empty objects)\n // All object properties must be valid AnyValues\n return Object.values(obj).every(item =>\n isLogAttributeValueInternal(item, visited)\n );\n }\n\n return false;\n}\n"]}

View File

@@ -0,0 +1,2 @@
export declare const VERSION = "0.214.0";
//# sourceMappingURL=version.d.ts.map

View File

@@ -0,0 +1,7 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
// this is autogenerated file, see scripts/version-update.js
export const VERSION = '0.214.0';
//# sourceMappingURL=version.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,4DAA4D;AAC5D,MAAM,CAAC,MAAM,OAAO,GAAG,SAAS,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.214.0';\n"]}

View File

@@ -0,0 +1,49 @@
import type { AnyValue, LogAttributes, LogBody, LogRecord, SeverityNumber } from '@opentelemetry/api-logs';
import * as api from '@opentelemetry/api';
import type { InstrumentationScope } from '@opentelemetry/core';
import type { Resource } from '@opentelemetry/resources';
import type { ReadableLogRecord } from './export/ReadableLogRecord';
import type { LoggerProviderSharedState } from './internal/LoggerProviderSharedState';
export declare class LogRecordImpl implements ReadableLogRecord {
readonly hrTime: api.HrTime;
readonly hrTimeObserved: api.HrTime;
readonly spanContext?: api.SpanContext;
readonly resource: Resource;
readonly instrumentationScope: InstrumentationScope;
readonly attributes: LogAttributes;
private _severityText?;
private _severityNumber?;
private _body?;
private _eventName?;
private _attributesCount;
private _droppedAttributesCount;
private _isReadonly;
private readonly _logRecordLimits;
set severityText(severityText: string | undefined);
get severityText(): string | undefined;
set severityNumber(severityNumber: SeverityNumber | undefined);
get severityNumber(): SeverityNumber | undefined;
set body(body: LogBody | undefined);
get body(): LogBody | undefined;
get eventName(): string | undefined;
set eventName(eventName: string | undefined);
get droppedAttributesCount(): number;
constructor(_sharedState: LoggerProviderSharedState, instrumentationScope: InstrumentationScope, logRecord: LogRecord);
setAttribute(key: string, value?: AnyValue): this;
setAttributes(attributes: LogAttributes): this;
setBody(body: LogBody): this;
setEventName(eventName: string): this;
setSeverityNumber(severityNumber: SeverityNumber): this;
setSeverityText(severityText: string): this;
/**
* @internal
* A LogRecordProcessor may freely modify logRecord for the duration of the OnEmit call.
* If logRecord is needed after OnEmit returns (i.e. for asynchronous processing) only reads are permitted.
*/
_makeReadonly(): void;
private _truncateToSize;
private _setException;
private _truncateToLimitUtil;
private _isLogRecordReadonly;
}
//# sourceMappingURL=LogRecordImpl.d.ts.map

View File

@@ -0,0 +1,231 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import * as api from '@opentelemetry/api';
import { timeInputToHrTime } from '@opentelemetry/core';
import { ATTR_EXCEPTION_MESSAGE, ATTR_EXCEPTION_STACKTRACE, ATTR_EXCEPTION_TYPE, } from '@opentelemetry/semantic-conventions';
import { isLogAttributeValue } from './utils/validation';
export class LogRecordImpl {
hrTime;
hrTimeObserved;
spanContext;
resource;
instrumentationScope;
attributes = {};
_severityText;
_severityNumber;
_body;
_eventName;
_attributesCount = 0;
_droppedAttributesCount = 0;
_isReadonly = false;
_logRecordLimits;
set severityText(severityText) {
if (this._isLogRecordReadonly()) {
return;
}
this._severityText = severityText;
}
get severityText() {
return this._severityText;
}
set severityNumber(severityNumber) {
if (this._isLogRecordReadonly()) {
return;
}
this._severityNumber = severityNumber;
}
get severityNumber() {
return this._severityNumber;
}
set body(body) {
if (this._isLogRecordReadonly()) {
return;
}
this._body = body;
}
get body() {
return this._body;
}
get eventName() {
return this._eventName;
}
set eventName(eventName) {
if (this._isLogRecordReadonly()) {
return;
}
this._eventName = eventName;
}
get droppedAttributesCount() {
return this._droppedAttributesCount;
}
constructor(_sharedState, instrumentationScope, logRecord) {
const { timestamp, observedTimestamp, eventName, severityNumber, severityText, body, attributes = {}, exception, context, } = logRecord;
const now = Date.now();
this.hrTime = timeInputToHrTime(timestamp ?? now);
this.hrTimeObserved = timeInputToHrTime(observedTimestamp ?? now);
if (context) {
const spanContext = api.trace.getSpanContext(context);
if (spanContext && api.isSpanContextValid(spanContext)) {
this.spanContext = spanContext;
}
}
this.severityNumber = severityNumber;
this.severityText = severityText;
this.body = body;
this.resource = _sharedState.resource;
this.instrumentationScope = instrumentationScope;
this._logRecordLimits = _sharedState.logRecordLimits;
this._eventName = eventName;
this.setAttributes(attributes);
if (exception != null) {
this._setException(exception);
}
}
setAttribute(key, value) {
if (this._isLogRecordReadonly()) {
return this;
}
if (key.length === 0) {
api.diag.warn(`Invalid attribute key: ${key}`);
return this;
}
if (!isLogAttributeValue(value)) {
api.diag.warn(`Invalid attribute value set for key: ${key}`);
return this;
}
const isNewKey = !Object.prototype.hasOwnProperty.call(this.attributes, key);
if (isNewKey &&
this._attributesCount >= this._logRecordLimits.attributeCountLimit) {
this._droppedAttributesCount++;
// Only warn once per LogRecord to avoid log spam
if (this._droppedAttributesCount === 1) {
api.diag.warn('Dropping extra attributes.');
}
return this;
}
this.attributes[key] = this._truncateToSize(value);
if (isNewKey) {
this._attributesCount++;
}
return this;
}
setAttributes(attributes) {
for (const [k, v] of Object.entries(attributes)) {
this.setAttribute(k, v);
}
return this;
}
setBody(body) {
this.body = body;
return this;
}
setEventName(eventName) {
this.eventName = eventName;
return this;
}
setSeverityNumber(severityNumber) {
this.severityNumber = severityNumber;
return this;
}
setSeverityText(severityText) {
this.severityText = severityText;
return this;
}
/**
* @internal
* A LogRecordProcessor may freely modify logRecord for the duration of the OnEmit call.
* If logRecord is needed after OnEmit returns (i.e. for asynchronous processing) only reads are permitted.
*/
_makeReadonly() {
this._isReadonly = true;
}
_truncateToSize(value) {
const limit = this._logRecordLimits.attributeValueLengthLimit;
// Check limit
if (limit <= 0) {
// Negative values are invalid, so do not truncate
api.diag.warn(`Attribute value limit must be positive, got ${limit}`);
return value;
}
// null/undefined - no truncation needed
if (value == null) {
return value;
}
// String
if (typeof value === 'string') {
return this._truncateToLimitUtil(value, limit);
}
// Byte arrays - no truncation needed
if (value instanceof Uint8Array) {
return value;
}
// Arrays (can contain any AnyValue types)
if (Array.isArray(value)) {
return value.map(val => this._truncateToSize(val));
}
// Objects/Maps - recursively truncate nested values
if (typeof value === 'object') {
const truncatedObj = {};
for (const [k, v] of Object.entries(value)) {
truncatedObj[k] = this._truncateToSize(v);
}
return truncatedObj;
}
// Other types (number, boolean), no need to apply value length limit
return value;
}
_setException(exception) {
let hasMinimumAttributes = false;
if (typeof exception === 'string' || typeof exception === 'number') {
if (!Object.hasOwn(this.attributes, ATTR_EXCEPTION_MESSAGE)) {
this.setAttribute(ATTR_EXCEPTION_MESSAGE, String(exception));
}
hasMinimumAttributes = true;
}
else if (exception && typeof exception === 'object') {
const exceptionObj = exception;
if (exceptionObj.code) {
if (!Object.hasOwn(this.attributes, ATTR_EXCEPTION_TYPE)) {
this.setAttribute(ATTR_EXCEPTION_TYPE, exceptionObj.code.toString());
}
hasMinimumAttributes = true;
}
else if (exceptionObj.name) {
if (!Object.hasOwn(this.attributes, ATTR_EXCEPTION_TYPE)) {
this.setAttribute(ATTR_EXCEPTION_TYPE, exceptionObj.name);
}
hasMinimumAttributes = true;
}
if (exceptionObj.message) {
if (!Object.hasOwn(this.attributes, ATTR_EXCEPTION_MESSAGE)) {
this.setAttribute(ATTR_EXCEPTION_MESSAGE, exceptionObj.message);
}
hasMinimumAttributes = true;
}
if (exceptionObj.stack) {
if (!Object.hasOwn(this.attributes, ATTR_EXCEPTION_STACKTRACE)) {
this.setAttribute(ATTR_EXCEPTION_STACKTRACE, exceptionObj.stack);
}
hasMinimumAttributes = true;
}
}
if (!hasMinimumAttributes) {
api.diag.warn(`Failed to record an exception ${exception}`);
}
}
_truncateToLimitUtil(value, limit) {
if (value.length <= limit) {
return value;
}
return value.substring(0, limit);
}
_isLogRecordReadonly() {
if (this._isReadonly) {
api.diag.warn('Can not execute the operation on emitted log record');
}
return this._isReadonly;
}
}
//# sourceMappingURL=LogRecordImpl.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,20 @@
import type { Context } from '@opentelemetry/api';
import type { SdkLogRecord } from './export/SdkLogRecord';
export interface LogRecordProcessor {
/**
* Forces to export all finished log records
*/
forceFlush(): Promise<void>;
/**
* Called when a {@link LogRecord} is emit
* @param logRecord the ReadWriteLogRecord that just emitted.
* @param context the current Context, or an empty Context if the Logger was obtained with include_trace_context=false
*/
onEmit(logRecord: SdkLogRecord, context?: Context): void;
/**
* Shuts down the processor. Called when SDK is shut down. This is an
* opportunity for processor to do any cleanup required.
*/
shutdown(): Promise<void>;
}
//# sourceMappingURL=LogRecordProcessor.d.ts.map

View File

@@ -0,0 +1,6 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=LogRecordProcessor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"LogRecordProcessor.js","sourceRoot":"","sources":["../../src/LogRecordProcessor.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\n\nimport type { SdkLogRecord } from './export/SdkLogRecord';\n\nexport interface LogRecordProcessor {\n /**\n * Forces to export all finished log records\n */\n forceFlush(): Promise<void>;\n\n /**\n * Called when a {@link LogRecord} is emit\n * @param logRecord the ReadWriteLogRecord that just emitted.\n * @param context the current Context, or an empty Context if the Logger was obtained with include_trace_context=false\n */\n onEmit(logRecord: SdkLogRecord, context?: Context): void;\n\n /**\n * Shuts down the processor. Called when SDK is shut down. This is an\n * opportunity for processor to do any cleanup required.\n */\n shutdown(): Promise<void>;\n}\n"]}

View File

@@ -0,0 +1,11 @@
import type * as logsAPI from '@opentelemetry/api-logs';
import type { InstrumentationScope } from '@opentelemetry/core';
import type { LoggerProviderSharedState } from './internal/LoggerProviderSharedState';
export declare class Logger implements logsAPI.Logger {
readonly instrumentationScope: InstrumentationScope;
private _sharedState;
private readonly _loggerConfig;
constructor(instrumentationScope: InstrumentationScope, sharedState: LoggerProviderSharedState);
emit(logRecord: logsAPI.LogRecord): void;
}
//# sourceMappingURL=Logger.d.ts.map

View File

@@ -0,0 +1,69 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { SeverityNumber } from '@opentelemetry/api-logs';
import { context, trace, TraceFlags, isSpanContextValid, } from '@opentelemetry/api';
import { LogRecordImpl } from './LogRecordImpl';
export class Logger {
instrumentationScope;
_sharedState;
_loggerConfig;
constructor(instrumentationScope, sharedState) {
this.instrumentationScope = instrumentationScope;
this._sharedState = sharedState;
// Cache the logger configuration at construction time
// Since we don't support re-configuration, this avoids map lookups
// and string allocations on each emit() call
this._loggerConfig = this._sharedState.getLoggerConfig(this.instrumentationScope);
}
emit(logRecord) {
const loggerConfig = this._loggerConfig;
const currentContext = logRecord.context || context.active();
// Apply minimum severity filtering
const recordSeverity = logRecord.severityNumber ?? SeverityNumber.UNSPECIFIED;
// 1. Minimum severity: If the log record's SeverityNumber is specified
// (i.e. not 0) and is less than the configured minimum_severity,
// the log record MUST be dropped.
if (recordSeverity !== SeverityNumber.UNSPECIFIED &&
recordSeverity < loggerConfig.minimumSeverity) {
// Log record is dropped due to minimum severity filter
return;
}
// 2. Trace-based: If trace_based is true, and if the log record has a
// SpanId and the TraceFlags SAMPLED flag is unset, the log record MUST be dropped.
if (loggerConfig.traceBased) {
const spanContext = trace.getSpanContext(currentContext);
if (spanContext && isSpanContextValid(spanContext)) {
// Check if the trace is unsampled (SAMPLED flag is unset)
const isSampled = (spanContext.traceFlags & TraceFlags.SAMPLED) === TraceFlags.SAMPLED;
if (!isSampled) {
// Log record is dropped due to trace-based filter
return;
}
}
// If there's no valid span context, the log record is not associated with a trace
// and therefore bypasses trace-based filtering (as per spec)
}
/**
* If a Logger was obtained with include_trace_context=true,
* the LogRecords it emits MUST automatically include the Trace Context from the active Context,
* if Context has not been explicitly set.
*/
const logRecordInstance = new LogRecordImpl(this._sharedState, this.instrumentationScope, {
context: currentContext,
...logRecord,
});
/**
* the explicitly passed Context,
* the current Context, or an empty Context if the Logger was obtained with include_trace_context=false
*/
this._sharedState.activeProcessor.onEmit(logRecordInstance, currentContext);
/**
* A LogRecordProcessor may freely modify logRecord for the duration of the OnEmit call.
* If logRecord is needed after OnEmit returns (i.e. for asynchronous processing) only reads are permitted.
*/
logRecordInstance._makeReadonly();
}
}
//# sourceMappingURL=Logger.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,27 @@
import type * as logsAPI from '@opentelemetry/api-logs';
import type { LoggerProviderConfig } from './types';
export declare const DEFAULT_LOGGER_NAME = "unknown";
export declare class LoggerProvider implements logsAPI.LoggerProvider {
private _shutdownOnce;
private readonly _sharedState;
constructor(config?: LoggerProviderConfig);
/**
* Get a logger with the configuration of the LoggerProvider.
*/
getLogger(name: string, version?: string, options?: logsAPI.LoggerOptions): logsAPI.Logger;
/**
* Notifies all registered LogRecordProcessor to flush any buffered data.
*
* Returns a promise which is resolved when all flushes are complete.
*/
forceFlush(): Promise<void>;
/**
* Flush all buffered data and shut down the LoggerProvider and all registered
* LogRecordProcessor.
*
* Returns a promise which is resolved when all flushes are complete.
*/
shutdown(): Promise<void>;
private _shutdown;
}
//# sourceMappingURL=LoggerProvider.d.ts.map

View File

@@ -0,0 +1,78 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { diag } from '@opentelemetry/api';
import { NOOP_LOGGER } from '@opentelemetry/api-logs';
import { defaultResource } from '@opentelemetry/resources';
import { BindOnceFuture } from '@opentelemetry/core';
import { Logger } from './Logger';
import { DEFAULT_LOGGER_CONFIGURATOR, LoggerProviderSharedState, } from './internal/LoggerProviderSharedState';
export const DEFAULT_LOGGER_NAME = 'unknown';
export class LoggerProvider {
_shutdownOnce;
_sharedState;
constructor(config = {}) {
const mergedConfig = {
resource: config.resource ?? defaultResource(),
forceFlushTimeoutMillis: config.forceFlushTimeoutMillis ?? 30000,
logRecordLimits: {
attributeCountLimit: config.logRecordLimits?.attributeCountLimit ?? 128,
attributeValueLengthLimit: config.logRecordLimits?.attributeValueLengthLimit ?? Infinity,
},
loggerConfigurator: config.loggerConfigurator ?? DEFAULT_LOGGER_CONFIGURATOR,
processors: config.processors ?? [],
};
this._sharedState = new LoggerProviderSharedState(mergedConfig.resource, mergedConfig.forceFlushTimeoutMillis, mergedConfig.logRecordLimits, mergedConfig.processors, mergedConfig.loggerConfigurator);
this._shutdownOnce = new BindOnceFuture(this._shutdown, this);
}
/**
* Get a logger with the configuration of the LoggerProvider.
*/
getLogger(name, version, options) {
if (this._shutdownOnce.isCalled) {
diag.warn('A shutdown LoggerProvider cannot provide a Logger');
return NOOP_LOGGER;
}
if (!name) {
diag.warn('Logger requested without instrumentation scope name.');
}
const loggerName = name || DEFAULT_LOGGER_NAME;
const key = `${loggerName}@${version || ''}:${options?.schemaUrl || ''}`;
if (!this._sharedState.loggers.has(key)) {
this._sharedState.loggers.set(key, new Logger({ name: loggerName, version, schemaUrl: options?.schemaUrl }, this._sharedState));
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this._sharedState.loggers.get(key);
}
/**
* Notifies all registered LogRecordProcessor to flush any buffered data.
*
* Returns a promise which is resolved when all flushes are complete.
*/
forceFlush() {
// do not flush after shutdown
if (this._shutdownOnce.isCalled) {
diag.warn('invalid attempt to force flush after LoggerProvider shutdown');
return this._shutdownOnce.promise;
}
return this._sharedState.activeProcessor.forceFlush();
}
/**
* Flush all buffered data and shut down the LoggerProvider and all registered
* LogRecordProcessor.
*
* Returns a promise which is resolved when all flushes are complete.
*/
shutdown() {
if (this._shutdownOnce.isCalled) {
diag.warn('shutdown may only be called once per LoggerProvider');
return this._shutdownOnce.promise;
}
return this._shutdownOnce.call();
}
_shutdown() {
return this._sharedState.activeProcessor.shutdown();
}
}
//# sourceMappingURL=LoggerProvider.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,16 @@
import type { Context } from '@opentelemetry/api';
import type { LogRecordProcessor } from './LogRecordProcessor';
import type { SdkLogRecord } from './export/SdkLogRecord';
/**
* Implementation of the {@link LogRecordProcessor} that simply forwards all
* received events to a list of {@link LogRecordProcessor}s.
*/
export declare class MultiLogRecordProcessor implements LogRecordProcessor {
readonly processors: LogRecordProcessor[];
readonly forceFlushTimeoutMillis: number;
constructor(processors: LogRecordProcessor[], forceFlushTimeoutMillis: number);
forceFlush(): Promise<void>;
onEmit(logRecord: SdkLogRecord, context?: Context): void;
shutdown(): Promise<void>;
}
//# sourceMappingURL=MultiLogRecordProcessor.d.ts.map

View File

@@ -0,0 +1,28 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { callWithTimeout } from '@opentelemetry/core';
/**
* Implementation of the {@link LogRecordProcessor} that simply forwards all
* received events to a list of {@link LogRecordProcessor}s.
*/
export class MultiLogRecordProcessor {
processors;
forceFlushTimeoutMillis;
constructor(processors, forceFlushTimeoutMillis) {
this.processors = processors;
this.forceFlushTimeoutMillis = forceFlushTimeoutMillis;
}
async forceFlush() {
const timeout = this.forceFlushTimeoutMillis;
await Promise.all(this.processors.map(processor => callWithTimeout(processor.forceFlush(), timeout)));
}
onEmit(logRecord, context) {
this.processors.forEach(processors => processors.onEmit(logRecord, context));
}
async shutdown() {
await Promise.all(this.processors.map(processor => processor.shutdown()));
}
}
//# sourceMappingURL=MultiLogRecordProcessor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"MultiLogRecordProcessor.js","sourceRoot":"","sources":["../../src/MultiLogRecordProcessor.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAKtD;;;GAGG;AACH,MAAM,OAAO,uBAAuB;IAClB,UAAU,CAAuB;IACjC,uBAAuB,CAAS;IAChD,YACE,UAAgC,EAChC,uBAA+B;QAE/B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,uBAAuB,GAAG,uBAAuB,CAAC;IACzD,CAAC;IAEM,KAAK,CAAC,UAAU;QACrB,MAAM,OAAO,GAAG,IAAI,CAAC,uBAAuB,CAAC;QAC7C,MAAM,OAAO,CAAC,GAAG,CACf,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAC9B,eAAe,CAAC,SAAS,CAAC,UAAU,EAAE,EAAE,OAAO,CAAC,CACjD,CACF,CAAC;IACJ,CAAC;IAEM,MAAM,CAAC,SAAuB,EAAE,OAAiB;QACtD,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,CACnC,UAAU,CAAC,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,CACtC,CAAC;IACJ,CAAC;IAEM,KAAK,CAAC,QAAQ;QACnB,MAAM,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;IAC5E,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { callWithTimeout } from '@opentelemetry/core';\nimport type { Context } from '@opentelemetry/api';\nimport type { LogRecordProcessor } from './LogRecordProcessor';\nimport type { SdkLogRecord } from './export/SdkLogRecord';\n\n/**\n * Implementation of the {@link LogRecordProcessor} that simply forwards all\n * received events to a list of {@link LogRecordProcessor}s.\n */\nexport class MultiLogRecordProcessor implements LogRecordProcessor {\n public readonly processors: LogRecordProcessor[];\n public readonly forceFlushTimeoutMillis: number;\n constructor(\n processors: LogRecordProcessor[],\n forceFlushTimeoutMillis: number\n ) {\n this.processors = processors;\n this.forceFlushTimeoutMillis = forceFlushTimeoutMillis;\n }\n\n public async forceFlush(): Promise<void> {\n const timeout = this.forceFlushTimeoutMillis;\n await Promise.all(\n this.processors.map(processor =>\n callWithTimeout(processor.forceFlush(), timeout)\n )\n );\n }\n\n public onEmit(logRecord: SdkLogRecord, context?: Context): void {\n this.processors.forEach(processors =>\n processors.onEmit(logRecord, context)\n );\n }\n\n public async shutdown(): Promise<void> {\n await Promise.all(this.processors.map(processor => processor.shutdown()));\n }\n}\n"]}

View File

@@ -0,0 +1,45 @@
import type { LoggerConfig, LoggerConfigurator } from '../types';
/**
* Configuration for a specific logger pattern
*
* @experimental This feature is in development as per the OpenTelemetry specification.
*/
export interface LoggerPattern {
/**
* The logger name or pattern to match.
* Use '*' for wildcard matching.
*
* @experimental This feature is in development as per the OpenTelemetry specification.
*/
pattern: string;
/**
* The configuration to apply to matching loggers.
* Partial config is allowed; unspecified properties will use defaults.
*
* @experimental This feature is in development as per the OpenTelemetry specification.
*/
config: LoggerConfig;
}
/**
* Creates a LoggerConfigurator from an array of logger patterns.
* Patterns are evaluated in order, and the first matching pattern's config is used.
* Supports exact matching and simple wildcard patterns with '*'.
*
* The returned configurator computes a complete LoggerConfig by merging the matched
* pattern's config with default values for any unspecified properties.
*
* @param patterns - Array of logger patterns with their configurations
* @returns A LoggerConfigurator function that computes complete LoggerConfig
* @experimental This feature is in development as per the OpenTelemetry specification.
*
* @example
* ```typescript
* const configurator = createLoggerConfigurator([
* { pattern: 'debug-logger', config: { minimumSeverity: SeverityNumber.DEBUG } },
* { pattern: 'prod-*', config: { minimumSeverity: SeverityNumber.WARN } },
* { pattern: '*', config: { minimumSeverity: SeverityNumber.INFO } },
* ]);
* ```
*/
export declare function createLoggerConfigurator(patterns: LoggerPattern[]): LoggerConfigurator;
//# sourceMappingURL=LoggerConfigurators.d.ts.map

View File

@@ -0,0 +1,79 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { SeverityNumber } from '@opentelemetry/api-logs';
/**
* Default LoggerConfig used when no pattern matches
*
* @experimental This feature is in development as per the OpenTelemetry specification.
*/
const DEFAULT_LOGGER_CONFIG = {
disabled: false,
minimumSeverity: SeverityNumber.UNSPECIFIED,
traceBased: false,
};
/**
* Creates a LoggerConfigurator from an array of logger patterns.
* Patterns are evaluated in order, and the first matching pattern's config is used.
* Supports exact matching and simple wildcard patterns with '*'.
*
* The returned configurator computes a complete LoggerConfig by merging the matched
* pattern's config with default values for any unspecified properties.
*
* @param patterns - Array of logger patterns with their configurations
* @returns A LoggerConfigurator function that computes complete LoggerConfig
* @experimental This feature is in development as per the OpenTelemetry specification.
*
* @example
* ```typescript
* const configurator = createLoggerConfigurator([
* { pattern: 'debug-logger', config: { minimumSeverity: SeverityNumber.DEBUG } },
* { pattern: 'prod-*', config: { minimumSeverity: SeverityNumber.WARN } },
* { pattern: '*', config: { minimumSeverity: SeverityNumber.INFO } },
* ]);
* ```
*/
export function createLoggerConfigurator(patterns) {
return (loggerScope) => {
const loggerName = loggerScope.name;
// Find the first matching pattern
for (const { pattern, config } of patterns) {
if (matchesPattern(loggerName, pattern)) {
// Compute complete config by merging with defaults
return {
disabled: config.disabled ?? DEFAULT_LOGGER_CONFIG.disabled,
minimumSeverity: config.minimumSeverity ?? DEFAULT_LOGGER_CONFIG.minimumSeverity,
traceBased: config.traceBased ?? DEFAULT_LOGGER_CONFIG.traceBased,
};
}
}
// No pattern matched, return default config
return { ...DEFAULT_LOGGER_CONFIG };
};
}
/**
* Matches a logger name against a pattern.
* Supports simple wildcard matching with '*'.
*
* @param name - The logger name to match
* @param pattern - The pattern to match against (supports '*' wildcard)
* @returns true if the name matches the pattern
*/
function matchesPattern(name, pattern) {
// Exact match
if (pattern === name) {
return true;
}
// Wildcard pattern
if (pattern.includes('*')) {
const regexPattern = pattern
.split('*')
.map(part => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
.join('.*');
const regex = new RegExp(`^${regexPattern}$`);
return regex.test(name);
}
return false;
}
//# sourceMappingURL=LoggerConfigurators.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,34 @@
import type { BufferConfig } from '../types';
import type { SdkLogRecord } from './SdkLogRecord';
import type { LogRecordExporter } from './LogRecordExporter';
import type { LogRecordProcessor } from '../LogRecordProcessor';
export declare abstract class BatchLogRecordProcessorBase<T extends BufferConfig> implements LogRecordProcessor {
private readonly _maxExportBatchSize;
private readonly _maxQueueSize;
private readonly _scheduledDelayMillis;
private readonly _exportTimeoutMillis;
private readonly _exporter;
private _isExporting;
private _finishedLogRecords;
private _timer;
private _shutdownOnce;
constructor(exporter: LogRecordExporter, config?: T);
onEmit(logRecord: SdkLogRecord): void;
forceFlush(): Promise<void>;
shutdown(): Promise<void>;
private _shutdown;
/** Add a LogRecord in the buffer. */
private _addToBuffer;
/**
* Send all LogRecords to the exporter respecting the batch size limit
* This function is used only on forceFlush or shutdown,
* for all other cases _flush should be used
* */
private _flushAll;
private _flushOneBatch;
private _maybeStartTimer;
private _clearTimer;
private _export;
protected abstract onShutdown(): void;
}
//# sourceMappingURL=BatchLogRecordProcessorBase.d.ts.map

View File

@@ -0,0 +1,146 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { diag } from '@opentelemetry/api';
import { ExportResultCode, globalErrorHandler, BindOnceFuture, internal, callWithTimeout, } from '@opentelemetry/core';
export class BatchLogRecordProcessorBase {
_maxExportBatchSize;
_maxQueueSize;
_scheduledDelayMillis;
_exportTimeoutMillis;
_exporter;
_isExporting = false;
_finishedLogRecords = [];
_timer;
_shutdownOnce;
constructor(exporter, config) {
this._exporter = exporter;
this._maxExportBatchSize = config?.maxExportBatchSize ?? 512;
this._maxQueueSize = config?.maxQueueSize ?? 2048;
this._scheduledDelayMillis = config?.scheduledDelayMillis ?? 5000;
this._exportTimeoutMillis = config?.exportTimeoutMillis ?? 30000;
this._shutdownOnce = new BindOnceFuture(this._shutdown, this);
if (this._maxExportBatchSize > this._maxQueueSize) {
diag.warn('BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize');
this._maxExportBatchSize = this._maxQueueSize;
}
}
onEmit(logRecord) {
if (this._shutdownOnce.isCalled) {
return;
}
this._addToBuffer(logRecord);
}
forceFlush() {
if (this._shutdownOnce.isCalled) {
return this._shutdownOnce.promise;
}
return this._flushAll();
}
shutdown() {
return this._shutdownOnce.call();
}
async _shutdown() {
this.onShutdown();
await this._flushAll();
await this._exporter.shutdown();
}
/** Add a LogRecord in the buffer. */
_addToBuffer(logRecord) {
if (this._finishedLogRecords.length >= this._maxQueueSize) {
return;
}
this._finishedLogRecords.push(logRecord);
this._maybeStartTimer();
}
/**
* Send all LogRecords to the exporter respecting the batch size limit
* This function is used only on forceFlush or shutdown,
* for all other cases _flush should be used
* */
_flushAll() {
return new Promise((resolve, reject) => {
const promises = [];
const batchCount = Math.ceil(this._finishedLogRecords.length / this._maxExportBatchSize);
for (let i = 0; i < batchCount; i++) {
promises.push(this._flushOneBatch());
}
Promise.all(promises)
.then(() => {
resolve();
})
.catch(reject);
});
}
_flushOneBatch() {
this._clearTimer();
if (this._finishedLogRecords.length === 0) {
return Promise.resolve();
}
return callWithTimeout(this._export(this._finishedLogRecords.splice(0, this._maxExportBatchSize)), this._exportTimeoutMillis);
}
_maybeStartTimer() {
if (this._isExporting)
return;
const flush = () => {
this._isExporting = true;
this._flushOneBatch()
.then(() => {
this._isExporting = false;
if (this._finishedLogRecords.length > 0) {
this._clearTimer();
this._maybeStartTimer();
}
})
.catch(e => {
this._isExporting = false;
globalErrorHandler(e);
});
};
// we only wait if the queue doesn't have enough elements yet
if (this._finishedLogRecords.length >= this._maxExportBatchSize) {
return flush();
}
if (this._timer !== undefined)
return;
this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);
// depending on runtime, this may be a 'number' or NodeJS.Timeout
if (typeof this._timer !== 'number') {
this._timer.unref();
}
}
_clearTimer() {
if (this._timer !== undefined) {
clearTimeout(this._timer);
this._timer = undefined;
}
}
_export(logRecords) {
const doExport = () => internal
._export(this._exporter, logRecords)
.then((result) => {
if (result.code !== ExportResultCode.SUCCESS) {
globalErrorHandler(result.error ??
new Error(`BatchLogRecordProcessor: log record export failed (status ${result})`));
}
})
.catch(globalErrorHandler);
const pendingResources = [];
for (let i = 0; i < logRecords.length; i++) {
const resource = logRecords[i].resource;
if (resource.asyncAttributesPending &&
typeof resource.waitForAsyncAttributes === 'function') {
pendingResources.push(resource.waitForAsyncAttributes());
}
}
// Avoid scheduling a promise to make the behavior more predictable and easier to test
if (pendingResources.length === 0) {
return doExport();
}
else {
return Promise.all(pendingResources).then(doExport, globalErrorHandler);
}
}
}
//# sourceMappingURL=BatchLogRecordProcessorBase.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,33 @@
import type { ExportResult } from '@opentelemetry/core';
import type { ReadableLogRecord } from './ReadableLogRecord';
import type { LogRecordExporter } from './LogRecordExporter';
/**
* This is implementation of {@link LogRecordExporter} that prints LogRecords to the
* console. This class can be used for diagnostic purposes.
*
* NOTE: This {@link LogRecordExporter} is intended for diagnostics use only, output rendered to the console may change at any time.
*/
export declare class ConsoleLogRecordExporter implements LogRecordExporter {
/**
* Export logs.
* @param logs
* @param resultCallback
*/
export(logs: ReadableLogRecord[], resultCallback: (result: ExportResult) => void): void;
/**
* Shutdown the exporter.
*/
shutdown(): Promise<void>;
/**
* converts logRecord info into more readable format
* @param logRecord
*/
private _exportInfo;
/**
* Showing logs in console
* @param logRecords
* @param done
*/
private _sendLogRecords;
}
//# sourceMappingURL=ConsoleLogRecordExporter.d.ts.map

View File

@@ -0,0 +1,61 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { ExportResultCode, hrTimeToMicroseconds } from '@opentelemetry/core';
/**
* This is implementation of {@link LogRecordExporter} that prints LogRecords to the
* console. This class can be used for diagnostic purposes.
*
* NOTE: This {@link LogRecordExporter} is intended for diagnostics use only, output rendered to the console may change at any time.
*/
/* eslint-disable no-console */
export class ConsoleLogRecordExporter {
/**
* Export logs.
* @param logs
* @param resultCallback
*/
export(logs, resultCallback) {
this._sendLogRecords(logs, resultCallback);
}
/**
* Shutdown the exporter.
*/
shutdown() {
return Promise.resolve();
}
/**
* converts logRecord info into more readable format
* @param logRecord
*/
_exportInfo(logRecord) {
return {
resource: {
attributes: logRecord.resource.attributes,
},
instrumentationScope: logRecord.instrumentationScope,
timestamp: hrTimeToMicroseconds(logRecord.hrTime),
traceId: logRecord.spanContext?.traceId,
spanId: logRecord.spanContext?.spanId,
traceFlags: logRecord.spanContext?.traceFlags,
severityText: logRecord.severityText,
severityNumber: logRecord.severityNumber,
eventName: logRecord.eventName,
body: logRecord.body,
attributes: logRecord.attributes,
};
}
/**
* Showing logs in console
* @param logRecords
* @param done
*/
_sendLogRecords(logRecords, done) {
for (const logRecord of logRecords) {
console.dir(this._exportInfo(logRecord), { depth: 3 });
}
done?.({ code: ExportResultCode.SUCCESS });
}
}
//# sourceMappingURL=ConsoleLogRecordExporter.js.map

Some files were not shown because too many files have changed in this diff Show More