@grow-codes/grafana-loki 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +53 -0
- package/lib/index.cjs +229 -1
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts +117 -5
- package/lib/index.d.ts +117 -5
- package/lib/index.js +223 -2
- package/lib/index.js.map +1 -1
- package/lib/{query-CofVHbt1.d.cts → query-BYQW0k9P.d.cts} +2 -2
- package/lib/{query-CofVHbt1.d.ts → query-BYQW0k9P.d.ts} +2 -2
- package/package.json +2 -1
package/lib/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { L as LokiError, A as Attributes, a as LogRecord, b as AttrValue, c as LogClient, S as Severity, d as LogExporter, E as ExportOptions,
|
|
2
|
-
export {
|
|
1
|
+
import { L as LokiError, A as Attributes, a as LogRecord, b as AttrValue, c as LogClient, S as Severity, R as RedactionOptions, d as Logger, e as LogExporter, E as ExportOptions, f as ExportResult, B as BaseLogQueryClient, g as LogSearchOptions, h as LogSearchResult, T as TailOptions, i as TailHandle, H as HealthStatus, j as BatchingLogClientOptions, k as BatchingLogClient } from './query-BYQW0k9P.cjs';
|
|
2
|
+
export { l as AuthenticationError, m as BatchOptions, n as BatchProcessor, o as BatchStats, C as CancelledError, p as ConfigError, q as ConflictError, D as DEFAULT_BATCH_OPTIONS, r as DEFAULT_REDACT_KEYS, s as DropPolicy, t as DropReason, u as ErrorCode, v as ErrorDetails, w as LogInput, x as LogQueryClient, y as LogSink, z as LoggerOptions, N as NotFoundError, P as PermissionDeniedError, F as RateLimitError, G as RedactionProcessor, I as ResolvedBatchOptions, J as TimeoutError, U as UnavailableError, K as UnsupportedError, M as UnsupportedLogQueryClient, V as ValidationError, W as WaitForLogOptions, O as canonicalSeverity, Q as codeForStatus, X as errorForCode, Y as errorForStatus, Z as healthStatus, _ as isHealthyWord, $ as isLokiError, a0 as parseSeverity, a1 as pollTail, a2 as probeHealth, a3 as reasonForCode, a4 as resolveBatchOptions, a5 as severityText, a6 as waitForLog } from './query-BYQW0k9P.cjs';
|
|
3
3
|
import { Dispatcher } from 'undici';
|
|
4
4
|
import { Writable } from 'node:stream';
|
|
5
5
|
|
|
@@ -485,7 +485,7 @@ declare class HttpTransport {
|
|
|
485
485
|
declare function redactSecretsInText(text: string): string;
|
|
486
486
|
|
|
487
487
|
/** Package version (kept in sync by release-please). */
|
|
488
|
-
declare const SDK_VERSION = "0.
|
|
488
|
+
declare const SDK_VERSION = "0.2.0";
|
|
489
489
|
/** Catalog key of the service (`grafana-loki`). */
|
|
490
490
|
declare const PACKAGE_KEY = "grafana-loki";
|
|
491
491
|
/** Language tag used in the User-Agent. */
|
|
@@ -691,6 +691,118 @@ declare class WinstonTransport extends Writable {
|
|
|
691
691
|
close(): void;
|
|
692
692
|
}
|
|
693
693
|
|
|
694
|
+
/** Top-level stdout field: `"sdk"` = the SDK also exports the record (collector skips the line),
|
|
695
|
+
* `"sdk_failed"` = the SDK export failed or dropped it (collector ships the line). */
|
|
696
|
+
declare const LOG_SHIPPED_FIELD = "log_shipped";
|
|
697
|
+
/** What {@link connectLogClient} returns: the SDK transport and how to release it. */
|
|
698
|
+
interface LogConnection {
|
|
699
|
+
/** Batching log client of this package. */
|
|
700
|
+
logs: LogClient;
|
|
701
|
+
/** Flushes and closes the client (and the service client behind it). */
|
|
702
|
+
close(): Promise<void>;
|
|
703
|
+
}
|
|
704
|
+
/** Builds a {@link LogConnection} (service connector or a test seam); `undefined` = stdout only. */
|
|
705
|
+
type LogConnector = (options: {
|
|
706
|
+
resource: Attributes;
|
|
707
|
+
env: Readonly<Record<string, string | undefined>>;
|
|
708
|
+
/** Pass as `batch.onDrop`: records the SDK could not export are re-emitted on stdout. */
|
|
709
|
+
onDropped: (records: LogRecord[]) => void;
|
|
710
|
+
}) => LogConnection | undefined;
|
|
711
|
+
/** Options of {@link initLogging}. */
|
|
712
|
+
interface InitLoggingOptions {
|
|
713
|
+
/** `service.name` (default `GROW_SERVICE_NAME` > `OTEL_SERVICE_NAME` > `"unknown_service"`). */
|
|
714
|
+
service?: string;
|
|
715
|
+
/** Minimum level: trace|debug|info|warn|error|fatal (default `LOG_LEVEL` > `info`). */
|
|
716
|
+
level?: string;
|
|
717
|
+
/** Write JSON lines to stdout (default true). */
|
|
718
|
+
stdout?: boolean;
|
|
719
|
+
/** Ship through this package (default: `GROW_LOGGING_PROVIDER` equals the package key). */
|
|
720
|
+
ship?: boolean;
|
|
721
|
+
/** Extra redaction keys/patterns (default keys always apply). */
|
|
722
|
+
redaction?: RedactionOptions;
|
|
723
|
+
/** Environment (default `process.env`). */
|
|
724
|
+
env?: Readonly<Record<string, string | undefined>>;
|
|
725
|
+
/** Line writer (default `process.stdout`). Test seam. */
|
|
726
|
+
write?: (line: string) => void;
|
|
727
|
+
/** Connector override (tests, custom clients). Default: this package's `connectLogClient`. */
|
|
728
|
+
connect?: LogConnector;
|
|
729
|
+
}
|
|
730
|
+
/** Handle returned by {@link initLogging}. */
|
|
731
|
+
interface LoggingHandle {
|
|
732
|
+
/** The root logger (stdout JSON + SDK transport). */
|
|
733
|
+
logger: Logger;
|
|
734
|
+
/** The SDK log client when records are shipped, else `undefined`. */
|
|
735
|
+
logs: LogClient | undefined;
|
|
736
|
+
/** `true` when records are shipped through the SDK (stdout lines carry `log_shipped:"sdk"`). */
|
|
737
|
+
shipped: boolean;
|
|
738
|
+
/** `service.name` of every record. */
|
|
739
|
+
service: string;
|
|
740
|
+
/** Exports everything queued now (no-op without SDK transport). */
|
|
741
|
+
flush(timeoutMs?: number): Promise<void>;
|
|
742
|
+
/** Flushes and closes the SDK transport; idempotent. A new {@link initLogging} starts over. */
|
|
743
|
+
close(): Promise<void>;
|
|
744
|
+
/** Sends `message` (e.g. `foundation-canary-<token>`) through the SDK only and flushes. */
|
|
745
|
+
canary(message: string, attributes?: Attributes): Promise<boolean>;
|
|
746
|
+
/** A writable stream for `pino(…, stream)`: stdout copy + SDK transport. */
|
|
747
|
+
pinoStream(): Writable;
|
|
748
|
+
}
|
|
749
|
+
/** Runs `fn` with `requestId` attached to every record logged inside it. */
|
|
750
|
+
declare function withRequestId<T>(requestId: string, fn: () => T): T;
|
|
751
|
+
/** The request id of the current request ({@link withRequestId} / `requestLogger()`). */
|
|
752
|
+
declare function currentRequestId(): string | undefined;
|
|
753
|
+
/** The handle of the last {@link initLogging} call, if any. */
|
|
754
|
+
declare function getLogging(): LoggingHandle | undefined;
|
|
755
|
+
/**
|
|
756
|
+
* Converts one record into the stdout JSON line (flat, collector friendly). `marker` is written
|
|
757
|
+
* as the top-level {@link LOG_SHIPPED_FIELD} (`"sdk"`, `"sdk_failed"`); `undefined` omits it.
|
|
758
|
+
*/
|
|
759
|
+
declare function stdoutLine(record: LogRecord, marker?: string): string;
|
|
760
|
+
/**
|
|
761
|
+
* Initialises logging once per process: JSON lines on stdout (always, unless `stdout: false`) and,
|
|
762
|
+
* when `GROW_LOGGING_PROVIDER` names this package, the SDK transport built by `connectLogClient`
|
|
763
|
+
* from the package's own `GROW_<KEY>_*` variables (stdout lines are then marked
|
|
764
|
+
* `log_shipped:"sdk"`). Never throws for an unreachable logging service. Call it after
|
|
765
|
+
* `loadConfig()` of the secrets package.
|
|
766
|
+
*
|
|
767
|
+
* ```ts
|
|
768
|
+
* const { logger, flush } = initLogging({ service: "orders" });
|
|
769
|
+
* logger.info("started", { port: 3000 });
|
|
770
|
+
* ```
|
|
771
|
+
*/
|
|
772
|
+
declare function initLogging(opts?: InitLoggingOptions): LoggingHandle;
|
|
773
|
+
|
|
774
|
+
/** Minimal request shape (Node `IncomingMessage`, Express, Nest on Express). */
|
|
775
|
+
interface RequestLike {
|
|
776
|
+
method?: string;
|
|
777
|
+
url?: string;
|
|
778
|
+
originalUrl?: string;
|
|
779
|
+
headers: Record<string, string | string[] | undefined>;
|
|
780
|
+
}
|
|
781
|
+
/** Minimal response shape (Node `ServerResponse`). */
|
|
782
|
+
interface ResponseLike {
|
|
783
|
+
statusCode: number;
|
|
784
|
+
setHeader(name: string, value: string): unknown;
|
|
785
|
+
once(event: "finish" | "close", listener: () => void): unknown;
|
|
786
|
+
}
|
|
787
|
+
/** Options of {@link requestLogger}. */
|
|
788
|
+
interface RequestLoggerOptions {
|
|
789
|
+
/** Logger to use (default: the `initLogging()` logger). */
|
|
790
|
+
logger?: Logger;
|
|
791
|
+
/** Header that carries the request id (default `x-request-id`). */
|
|
792
|
+
header?: string;
|
|
793
|
+
/** Paths that are not logged (default `/health/live`, `/health/ready`). Prefix match. */
|
|
794
|
+
skip?: readonly string[];
|
|
795
|
+
}
|
|
796
|
+
/** Connect/Express style middleware. */
|
|
797
|
+
type RequestMiddleware = (req: RequestLike, res: ResponseLike, next: (err?: unknown) => void) => void;
|
|
798
|
+
/**
|
|
799
|
+
* Request middleware for Express, NestJS (`app.use(requestLogger())`) and plain Node `http`:
|
|
800
|
+
* reuses or creates the request id (`x-request-id`, echoed on the response), attaches it to every
|
|
801
|
+
* record logged while the request runs, and logs one `request completed` record with method,
|
|
802
|
+
* path, status and duration.
|
|
803
|
+
*/
|
|
804
|
+
declare function requestLogger(opts?: RequestLoggerOptions): RequestMiddleware;
|
|
805
|
+
|
|
694
806
|
/** Label names allowed by Loki (Prometheus rules). */
|
|
695
807
|
declare const LABEL_NAME_PATTERN: RegExp;
|
|
696
808
|
/**
|
|
@@ -1344,5 +1456,5 @@ declare function snappyCompress(data: Uint8Array): Uint8Array;
|
|
|
1344
1456
|
*/
|
|
1345
1457
|
declare function decodeRpcStatusMessage(bytes: Uint8Array): string | undefined;
|
|
1346
1458
|
|
|
1347
|
-
export { ALL_STREAMS_SELECTOR, AttrValue, Attributes, BaseLogQueryClient, BatchingLogClient, BatchingLogClientOptions, CardinalityGuard, DEFAULT_ALLOWED_LABELS, DEFAULT_REQUEST_ID_HEADERS, DEFAULT_TIMEOUTS, ENCODING_FLAGS_HEADER, EnvReader, ExportOptions, ExportResult, HealthStatus, HttpTransport, LABEL_NAME_PATTERN, LANGUAGE, LogClient, LogExporter, LogQL, LogRecord, LogSearchOptions, LogSearchResult, LokiClient, LokiConfig, LokiError, LokiLogExporter, LokiLogQueryClient, LokiOtlpExporter, MAX_QUERY_LIMIT, MAX_TENANT_ID_LENGTH, MAX_VENDOR_TEXT, MIN_SECRET_LENGTH, OTLP_SCOPE_NAME, PACKAGE_KEY, REDACTED, RESERVED_METADATA_KEYS, RetryPolicy, SDK_KIT_VERSION, SDK_VERSION, SENSITIVE_FIELD_PARTS, Secret, Severity, TENANT_HEADER, TailHandle, TailOptions, VENDOR_ENV, WinstonTransport, attrToString, createDispatcher, createPinoTransport, dateToNanos, decodeBuildInfo, decodeCursor, decodeEntry, decodeIndexStats, decodeQueryResult, decodeRpcStatusMessage, decodeSeries, decodeStreams, decodeStringList, decodeTailFrame, definedOnly, describeCommonConfig, encodeCursor, encodePushRequest, entryToLogRecord, formatLabelSet, isIdempotentMethod, isRetryableStatus, isSensitiveField, isSensitiveHeader, isValidLabelName, logRecordByteSize, logRecordFromJson, logRecordToJson, mergeOptions, mergeStreams, msToDuration, nanosToDate, normalizeLabelName, optionalNanos, parseBool, parseDuration, parseInteger, parseLogRecord, parseRetryAfter, pinoLevelToSeverity, pinoLineToRecord, pollUntil, quoteLogQL, readCommonEnv, recordsToOtlpJson, recordsToStreams, redactError, redactFields, redactHeaders, redactSecretsInText, redactText, redactUrl, resolveCommonConfig, safeCall, safeLogger, secondsToDate, secretValues, serializeLogRecord, silentLogger, sleep, snappyCompress, stringMap, tenantIdProblem, throwIfAborted, toAttrValue, toAttributes, toNanos, toOtlpValue, toSearchLogQL, validateCommonConfig, validateLabelName, validateLabels, winstonLevelToSeverity };
|
|
1348
|
-
export type { CallOptions, CardinalityGuardOptions, ClientInternals, ClientLogger, CommonConfig, CommonConfigOptions, CommonVendorEnv, Direction, EnvHit, EnvMap, ErrorClassifier, ErrorInfo, ErrorResponse, HeadersInput, Hooks, IndexOptions, KnownSecret, LabelsOptions, LiveTailOptions, LogFields, LogRecordJson, LokiBuildInfo, LokiClientShared, LokiConfigOptions, LokiDroppedEntry, LokiEntry, LokiEntryResult, LokiIndexStats, LokiLogClientOptions, LokiLogExporterOptions, LokiMatrixSeries, LokiPusher, LokiQueryResult, LokiQuerySource, LokiResultType, LokiSample, LokiStream, LokiStreamResult, LokiTail, LokiTailFrame, LokiTime, LokiVectorSample, MatchOperator, MergedEntry, NumericOperator, OtlpAnyValue, OtlpKeyValue, OtlpPushOptions, PinoTransportOptions, PollOptions, PushFormat, PushOptions, QueryOptions, QueryRangeOptions, QueryValue, RequestInfo, RequestOptions, ResponseInfo, ResponseType, RetryPolicyOptions, SeriesOptions, TailCallbacks, TimeRangeOptions, TlsOptions, TransportOptions, TransportResponse, VolumeOptions, VolumeRangeOptions, WinstonInfo, WinstonTransportOptions };
|
|
1459
|
+
export { ALL_STREAMS_SELECTOR, AttrValue, Attributes, BaseLogQueryClient, BatchingLogClient, BatchingLogClientOptions, CardinalityGuard, DEFAULT_ALLOWED_LABELS, DEFAULT_REQUEST_ID_HEADERS, DEFAULT_TIMEOUTS, ENCODING_FLAGS_HEADER, EnvReader, ExportOptions, ExportResult, HealthStatus, HttpTransport, LABEL_NAME_PATTERN, LANGUAGE, LOG_SHIPPED_FIELD, LogClient, LogExporter, LogQL, LogRecord, LogSearchOptions, LogSearchResult, Logger, LokiClient, LokiConfig, LokiError, LokiLogExporter, LokiLogQueryClient, LokiOtlpExporter, MAX_QUERY_LIMIT, MAX_TENANT_ID_LENGTH, MAX_VENDOR_TEXT, MIN_SECRET_LENGTH, OTLP_SCOPE_NAME, PACKAGE_KEY, REDACTED, RESERVED_METADATA_KEYS, RedactionOptions, RetryPolicy, SDK_KIT_VERSION, SDK_VERSION, SENSITIVE_FIELD_PARTS, Secret, Severity, TENANT_HEADER, TailHandle, TailOptions, VENDOR_ENV, WinstonTransport, attrToString, createDispatcher, createPinoTransport, currentRequestId, dateToNanos, decodeBuildInfo, decodeCursor, decodeEntry, decodeIndexStats, decodeQueryResult, decodeRpcStatusMessage, decodeSeries, decodeStreams, decodeStringList, decodeTailFrame, definedOnly, describeCommonConfig, encodeCursor, encodePushRequest, entryToLogRecord, formatLabelSet, getLogging, initLogging, isIdempotentMethod, isRetryableStatus, isSensitiveField, isSensitiveHeader, isValidLabelName, logRecordByteSize, logRecordFromJson, logRecordToJson, mergeOptions, mergeStreams, msToDuration, nanosToDate, normalizeLabelName, optionalNanos, parseBool, parseDuration, parseInteger, parseLogRecord, parseRetryAfter, pinoLevelToSeverity, pinoLineToRecord, pollUntil, quoteLogQL, readCommonEnv, recordsToOtlpJson, recordsToStreams, redactError, redactFields, redactHeaders, redactSecretsInText, redactText, redactUrl, requestLogger, resolveCommonConfig, safeCall, safeLogger, secondsToDate, secretValues, serializeLogRecord, silentLogger, sleep, snappyCompress, stdoutLine, stringMap, tenantIdProblem, throwIfAborted, toAttrValue, toAttributes, toNanos, toOtlpValue, toSearchLogQL, validateCommonConfig, validateLabelName, validateLabels, winstonLevelToSeverity, withRequestId };
|
|
1460
|
+
export type { CallOptions, CardinalityGuardOptions, ClientInternals, ClientLogger, CommonConfig, CommonConfigOptions, CommonVendorEnv, Direction, EnvHit, EnvMap, ErrorClassifier, ErrorInfo, ErrorResponse, HeadersInput, Hooks, IndexOptions, InitLoggingOptions, KnownSecret, LabelsOptions, LiveTailOptions, LogConnection, LogConnector, LogFields, LogRecordJson, LoggingHandle, LokiBuildInfo, LokiClientShared, LokiConfigOptions, LokiDroppedEntry, LokiEntry, LokiEntryResult, LokiIndexStats, LokiLogClientOptions, LokiLogExporterOptions, LokiMatrixSeries, LokiPusher, LokiQueryResult, LokiQuerySource, LokiResultType, LokiSample, LokiStream, LokiStreamResult, LokiTail, LokiTailFrame, LokiTime, LokiVectorSample, MatchOperator, MergedEntry, NumericOperator, OtlpAnyValue, OtlpKeyValue, OtlpPushOptions, PinoTransportOptions, PollOptions, PushFormat, PushOptions, QueryOptions, QueryRangeOptions, QueryValue, RequestInfo, RequestLike, RequestLoggerOptions, RequestMiddleware, RequestOptions, ResponseInfo, ResponseLike, ResponseType, RetryPolicyOptions, SeriesOptions, TailCallbacks, TimeRangeOptions, TlsOptions, TransportOptions, TransportResponse, VolumeOptions, VolumeRangeOptions, WinstonInfo, WinstonTransportOptions };
|
package/lib/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { L as LokiError, A as Attributes, a as LogRecord, b as AttrValue, c as LogClient, S as Severity, d as LogExporter, E as ExportOptions,
|
|
2
|
-
export {
|
|
1
|
+
import { L as LokiError, A as Attributes, a as LogRecord, b as AttrValue, c as LogClient, S as Severity, R as RedactionOptions, d as Logger, e as LogExporter, E as ExportOptions, f as ExportResult, B as BaseLogQueryClient, g as LogSearchOptions, h as LogSearchResult, T as TailOptions, i as TailHandle, H as HealthStatus, j as BatchingLogClientOptions, k as BatchingLogClient } from './query-BYQW0k9P.js';
|
|
2
|
+
export { l as AuthenticationError, m as BatchOptions, n as BatchProcessor, o as BatchStats, C as CancelledError, p as ConfigError, q as ConflictError, D as DEFAULT_BATCH_OPTIONS, r as DEFAULT_REDACT_KEYS, s as DropPolicy, t as DropReason, u as ErrorCode, v as ErrorDetails, w as LogInput, x as LogQueryClient, y as LogSink, z as LoggerOptions, N as NotFoundError, P as PermissionDeniedError, F as RateLimitError, G as RedactionProcessor, I as ResolvedBatchOptions, J as TimeoutError, U as UnavailableError, K as UnsupportedError, M as UnsupportedLogQueryClient, V as ValidationError, W as WaitForLogOptions, O as canonicalSeverity, Q as codeForStatus, X as errorForCode, Y as errorForStatus, Z as healthStatus, _ as isHealthyWord, $ as isLokiError, a0 as parseSeverity, a1 as pollTail, a2 as probeHealth, a3 as reasonForCode, a4 as resolveBatchOptions, a5 as severityText, a6 as waitForLog } from './query-BYQW0k9P.js';
|
|
3
3
|
import { Dispatcher } from 'undici';
|
|
4
4
|
import { Writable } from 'node:stream';
|
|
5
5
|
|
|
@@ -485,7 +485,7 @@ declare class HttpTransport {
|
|
|
485
485
|
declare function redactSecretsInText(text: string): string;
|
|
486
486
|
|
|
487
487
|
/** Package version (kept in sync by release-please). */
|
|
488
|
-
declare const SDK_VERSION = "0.
|
|
488
|
+
declare const SDK_VERSION = "0.2.0";
|
|
489
489
|
/** Catalog key of the service (`grafana-loki`). */
|
|
490
490
|
declare const PACKAGE_KEY = "grafana-loki";
|
|
491
491
|
/** Language tag used in the User-Agent. */
|
|
@@ -691,6 +691,118 @@ declare class WinstonTransport extends Writable {
|
|
|
691
691
|
close(): void;
|
|
692
692
|
}
|
|
693
693
|
|
|
694
|
+
/** Top-level stdout field: `"sdk"` = the SDK also exports the record (collector skips the line),
|
|
695
|
+
* `"sdk_failed"` = the SDK export failed or dropped it (collector ships the line). */
|
|
696
|
+
declare const LOG_SHIPPED_FIELD = "log_shipped";
|
|
697
|
+
/** What {@link connectLogClient} returns: the SDK transport and how to release it. */
|
|
698
|
+
interface LogConnection {
|
|
699
|
+
/** Batching log client of this package. */
|
|
700
|
+
logs: LogClient;
|
|
701
|
+
/** Flushes and closes the client (and the service client behind it). */
|
|
702
|
+
close(): Promise<void>;
|
|
703
|
+
}
|
|
704
|
+
/** Builds a {@link LogConnection} (service connector or a test seam); `undefined` = stdout only. */
|
|
705
|
+
type LogConnector = (options: {
|
|
706
|
+
resource: Attributes;
|
|
707
|
+
env: Readonly<Record<string, string | undefined>>;
|
|
708
|
+
/** Pass as `batch.onDrop`: records the SDK could not export are re-emitted on stdout. */
|
|
709
|
+
onDropped: (records: LogRecord[]) => void;
|
|
710
|
+
}) => LogConnection | undefined;
|
|
711
|
+
/** Options of {@link initLogging}. */
|
|
712
|
+
interface InitLoggingOptions {
|
|
713
|
+
/** `service.name` (default `GROW_SERVICE_NAME` > `OTEL_SERVICE_NAME` > `"unknown_service"`). */
|
|
714
|
+
service?: string;
|
|
715
|
+
/** Minimum level: trace|debug|info|warn|error|fatal (default `LOG_LEVEL` > `info`). */
|
|
716
|
+
level?: string;
|
|
717
|
+
/** Write JSON lines to stdout (default true). */
|
|
718
|
+
stdout?: boolean;
|
|
719
|
+
/** Ship through this package (default: `GROW_LOGGING_PROVIDER` equals the package key). */
|
|
720
|
+
ship?: boolean;
|
|
721
|
+
/** Extra redaction keys/patterns (default keys always apply). */
|
|
722
|
+
redaction?: RedactionOptions;
|
|
723
|
+
/** Environment (default `process.env`). */
|
|
724
|
+
env?: Readonly<Record<string, string | undefined>>;
|
|
725
|
+
/** Line writer (default `process.stdout`). Test seam. */
|
|
726
|
+
write?: (line: string) => void;
|
|
727
|
+
/** Connector override (tests, custom clients). Default: this package's `connectLogClient`. */
|
|
728
|
+
connect?: LogConnector;
|
|
729
|
+
}
|
|
730
|
+
/** Handle returned by {@link initLogging}. */
|
|
731
|
+
interface LoggingHandle {
|
|
732
|
+
/** The root logger (stdout JSON + SDK transport). */
|
|
733
|
+
logger: Logger;
|
|
734
|
+
/** The SDK log client when records are shipped, else `undefined`. */
|
|
735
|
+
logs: LogClient | undefined;
|
|
736
|
+
/** `true` when records are shipped through the SDK (stdout lines carry `log_shipped:"sdk"`). */
|
|
737
|
+
shipped: boolean;
|
|
738
|
+
/** `service.name` of every record. */
|
|
739
|
+
service: string;
|
|
740
|
+
/** Exports everything queued now (no-op without SDK transport). */
|
|
741
|
+
flush(timeoutMs?: number): Promise<void>;
|
|
742
|
+
/** Flushes and closes the SDK transport; idempotent. A new {@link initLogging} starts over. */
|
|
743
|
+
close(): Promise<void>;
|
|
744
|
+
/** Sends `message` (e.g. `foundation-canary-<token>`) through the SDK only and flushes. */
|
|
745
|
+
canary(message: string, attributes?: Attributes): Promise<boolean>;
|
|
746
|
+
/** A writable stream for `pino(…, stream)`: stdout copy + SDK transport. */
|
|
747
|
+
pinoStream(): Writable;
|
|
748
|
+
}
|
|
749
|
+
/** Runs `fn` with `requestId` attached to every record logged inside it. */
|
|
750
|
+
declare function withRequestId<T>(requestId: string, fn: () => T): T;
|
|
751
|
+
/** The request id of the current request ({@link withRequestId} / `requestLogger()`). */
|
|
752
|
+
declare function currentRequestId(): string | undefined;
|
|
753
|
+
/** The handle of the last {@link initLogging} call, if any. */
|
|
754
|
+
declare function getLogging(): LoggingHandle | undefined;
|
|
755
|
+
/**
|
|
756
|
+
* Converts one record into the stdout JSON line (flat, collector friendly). `marker` is written
|
|
757
|
+
* as the top-level {@link LOG_SHIPPED_FIELD} (`"sdk"`, `"sdk_failed"`); `undefined` omits it.
|
|
758
|
+
*/
|
|
759
|
+
declare function stdoutLine(record: LogRecord, marker?: string): string;
|
|
760
|
+
/**
|
|
761
|
+
* Initialises logging once per process: JSON lines on stdout (always, unless `stdout: false`) and,
|
|
762
|
+
* when `GROW_LOGGING_PROVIDER` names this package, the SDK transport built by `connectLogClient`
|
|
763
|
+
* from the package's own `GROW_<KEY>_*` variables (stdout lines are then marked
|
|
764
|
+
* `log_shipped:"sdk"`). Never throws for an unreachable logging service. Call it after
|
|
765
|
+
* `loadConfig()` of the secrets package.
|
|
766
|
+
*
|
|
767
|
+
* ```ts
|
|
768
|
+
* const { logger, flush } = initLogging({ service: "orders" });
|
|
769
|
+
* logger.info("started", { port: 3000 });
|
|
770
|
+
* ```
|
|
771
|
+
*/
|
|
772
|
+
declare function initLogging(opts?: InitLoggingOptions): LoggingHandle;
|
|
773
|
+
|
|
774
|
+
/** Minimal request shape (Node `IncomingMessage`, Express, Nest on Express). */
|
|
775
|
+
interface RequestLike {
|
|
776
|
+
method?: string;
|
|
777
|
+
url?: string;
|
|
778
|
+
originalUrl?: string;
|
|
779
|
+
headers: Record<string, string | string[] | undefined>;
|
|
780
|
+
}
|
|
781
|
+
/** Minimal response shape (Node `ServerResponse`). */
|
|
782
|
+
interface ResponseLike {
|
|
783
|
+
statusCode: number;
|
|
784
|
+
setHeader(name: string, value: string): unknown;
|
|
785
|
+
once(event: "finish" | "close", listener: () => void): unknown;
|
|
786
|
+
}
|
|
787
|
+
/** Options of {@link requestLogger}. */
|
|
788
|
+
interface RequestLoggerOptions {
|
|
789
|
+
/** Logger to use (default: the `initLogging()` logger). */
|
|
790
|
+
logger?: Logger;
|
|
791
|
+
/** Header that carries the request id (default `x-request-id`). */
|
|
792
|
+
header?: string;
|
|
793
|
+
/** Paths that are not logged (default `/health/live`, `/health/ready`). Prefix match. */
|
|
794
|
+
skip?: readonly string[];
|
|
795
|
+
}
|
|
796
|
+
/** Connect/Express style middleware. */
|
|
797
|
+
type RequestMiddleware = (req: RequestLike, res: ResponseLike, next: (err?: unknown) => void) => void;
|
|
798
|
+
/**
|
|
799
|
+
* Request middleware for Express, NestJS (`app.use(requestLogger())`) and plain Node `http`:
|
|
800
|
+
* reuses or creates the request id (`x-request-id`, echoed on the response), attaches it to every
|
|
801
|
+
* record logged while the request runs, and logs one `request completed` record with method,
|
|
802
|
+
* path, status and duration.
|
|
803
|
+
*/
|
|
804
|
+
declare function requestLogger(opts?: RequestLoggerOptions): RequestMiddleware;
|
|
805
|
+
|
|
694
806
|
/** Label names allowed by Loki (Prometheus rules). */
|
|
695
807
|
declare const LABEL_NAME_PATTERN: RegExp;
|
|
696
808
|
/**
|
|
@@ -1344,5 +1456,5 @@ declare function snappyCompress(data: Uint8Array): Uint8Array;
|
|
|
1344
1456
|
*/
|
|
1345
1457
|
declare function decodeRpcStatusMessage(bytes: Uint8Array): string | undefined;
|
|
1346
1458
|
|
|
1347
|
-
export { ALL_STREAMS_SELECTOR, AttrValue, Attributes, BaseLogQueryClient, BatchingLogClient, BatchingLogClientOptions, CardinalityGuard, DEFAULT_ALLOWED_LABELS, DEFAULT_REQUEST_ID_HEADERS, DEFAULT_TIMEOUTS, ENCODING_FLAGS_HEADER, EnvReader, ExportOptions, ExportResult, HealthStatus, HttpTransport, LABEL_NAME_PATTERN, LANGUAGE, LogClient, LogExporter, LogQL, LogRecord, LogSearchOptions, LogSearchResult, LokiClient, LokiConfig, LokiError, LokiLogExporter, LokiLogQueryClient, LokiOtlpExporter, MAX_QUERY_LIMIT, MAX_TENANT_ID_LENGTH, MAX_VENDOR_TEXT, MIN_SECRET_LENGTH, OTLP_SCOPE_NAME, PACKAGE_KEY, REDACTED, RESERVED_METADATA_KEYS, RetryPolicy, SDK_KIT_VERSION, SDK_VERSION, SENSITIVE_FIELD_PARTS, Secret, Severity, TENANT_HEADER, TailHandle, TailOptions, VENDOR_ENV, WinstonTransport, attrToString, createDispatcher, createPinoTransport, dateToNanos, decodeBuildInfo, decodeCursor, decodeEntry, decodeIndexStats, decodeQueryResult, decodeRpcStatusMessage, decodeSeries, decodeStreams, decodeStringList, decodeTailFrame, definedOnly, describeCommonConfig, encodeCursor, encodePushRequest, entryToLogRecord, formatLabelSet, isIdempotentMethod, isRetryableStatus, isSensitiveField, isSensitiveHeader, isValidLabelName, logRecordByteSize, logRecordFromJson, logRecordToJson, mergeOptions, mergeStreams, msToDuration, nanosToDate, normalizeLabelName, optionalNanos, parseBool, parseDuration, parseInteger, parseLogRecord, parseRetryAfter, pinoLevelToSeverity, pinoLineToRecord, pollUntil, quoteLogQL, readCommonEnv, recordsToOtlpJson, recordsToStreams, redactError, redactFields, redactHeaders, redactSecretsInText, redactText, redactUrl, resolveCommonConfig, safeCall, safeLogger, secondsToDate, secretValues, serializeLogRecord, silentLogger, sleep, snappyCompress, stringMap, tenantIdProblem, throwIfAborted, toAttrValue, toAttributes, toNanos, toOtlpValue, toSearchLogQL, validateCommonConfig, validateLabelName, validateLabels, winstonLevelToSeverity };
|
|
1348
|
-
export type { CallOptions, CardinalityGuardOptions, ClientInternals, ClientLogger, CommonConfig, CommonConfigOptions, CommonVendorEnv, Direction, EnvHit, EnvMap, ErrorClassifier, ErrorInfo, ErrorResponse, HeadersInput, Hooks, IndexOptions, KnownSecret, LabelsOptions, LiveTailOptions, LogFields, LogRecordJson, LokiBuildInfo, LokiClientShared, LokiConfigOptions, LokiDroppedEntry, LokiEntry, LokiEntryResult, LokiIndexStats, LokiLogClientOptions, LokiLogExporterOptions, LokiMatrixSeries, LokiPusher, LokiQueryResult, LokiQuerySource, LokiResultType, LokiSample, LokiStream, LokiStreamResult, LokiTail, LokiTailFrame, LokiTime, LokiVectorSample, MatchOperator, MergedEntry, NumericOperator, OtlpAnyValue, OtlpKeyValue, OtlpPushOptions, PinoTransportOptions, PollOptions, PushFormat, PushOptions, QueryOptions, QueryRangeOptions, QueryValue, RequestInfo, RequestOptions, ResponseInfo, ResponseType, RetryPolicyOptions, SeriesOptions, TailCallbacks, TimeRangeOptions, TlsOptions, TransportOptions, TransportResponse, VolumeOptions, VolumeRangeOptions, WinstonInfo, WinstonTransportOptions };
|
|
1459
|
+
export { ALL_STREAMS_SELECTOR, AttrValue, Attributes, BaseLogQueryClient, BatchingLogClient, BatchingLogClientOptions, CardinalityGuard, DEFAULT_ALLOWED_LABELS, DEFAULT_REQUEST_ID_HEADERS, DEFAULT_TIMEOUTS, ENCODING_FLAGS_HEADER, EnvReader, ExportOptions, ExportResult, HealthStatus, HttpTransport, LABEL_NAME_PATTERN, LANGUAGE, LOG_SHIPPED_FIELD, LogClient, LogExporter, LogQL, LogRecord, LogSearchOptions, LogSearchResult, Logger, LokiClient, LokiConfig, LokiError, LokiLogExporter, LokiLogQueryClient, LokiOtlpExporter, MAX_QUERY_LIMIT, MAX_TENANT_ID_LENGTH, MAX_VENDOR_TEXT, MIN_SECRET_LENGTH, OTLP_SCOPE_NAME, PACKAGE_KEY, REDACTED, RESERVED_METADATA_KEYS, RedactionOptions, RetryPolicy, SDK_KIT_VERSION, SDK_VERSION, SENSITIVE_FIELD_PARTS, Secret, Severity, TENANT_HEADER, TailHandle, TailOptions, VENDOR_ENV, WinstonTransport, attrToString, createDispatcher, createPinoTransport, currentRequestId, dateToNanos, decodeBuildInfo, decodeCursor, decodeEntry, decodeIndexStats, decodeQueryResult, decodeRpcStatusMessage, decodeSeries, decodeStreams, decodeStringList, decodeTailFrame, definedOnly, describeCommonConfig, encodeCursor, encodePushRequest, entryToLogRecord, formatLabelSet, getLogging, initLogging, isIdempotentMethod, isRetryableStatus, isSensitiveField, isSensitiveHeader, isValidLabelName, logRecordByteSize, logRecordFromJson, logRecordToJson, mergeOptions, mergeStreams, msToDuration, nanosToDate, normalizeLabelName, optionalNanos, parseBool, parseDuration, parseInteger, parseLogRecord, parseRetryAfter, pinoLevelToSeverity, pinoLineToRecord, pollUntil, quoteLogQL, readCommonEnv, recordsToOtlpJson, recordsToStreams, redactError, redactFields, redactHeaders, redactSecretsInText, redactText, redactUrl, requestLogger, resolveCommonConfig, safeCall, safeLogger, secondsToDate, secretValues, serializeLogRecord, silentLogger, sleep, snappyCompress, stdoutLine, stringMap, tenantIdProblem, throwIfAborted, toAttrValue, toAttributes, toNanos, toOtlpValue, toSearchLogQL, validateCommonConfig, validateLabelName, validateLabels, winstonLevelToSeverity, withRequestId };
|
|
1460
|
+
export type { CallOptions, CardinalityGuardOptions, ClientInternals, ClientLogger, CommonConfig, CommonConfigOptions, CommonVendorEnv, Direction, EnvHit, EnvMap, ErrorClassifier, ErrorInfo, ErrorResponse, HeadersInput, Hooks, IndexOptions, InitLoggingOptions, KnownSecret, LabelsOptions, LiveTailOptions, LogConnection, LogConnector, LogFields, LogRecordJson, LoggingHandle, LokiBuildInfo, LokiClientShared, LokiConfigOptions, LokiDroppedEntry, LokiEntry, LokiEntryResult, LokiIndexStats, LokiLogClientOptions, LokiLogExporterOptions, LokiMatrixSeries, LokiPusher, LokiQueryResult, LokiQuerySource, LokiResultType, LokiSample, LokiStream, LokiStreamResult, LokiTail, LokiTailFrame, LokiTime, LokiVectorSample, MatchOperator, MergedEntry, NumericOperator, OtlpAnyValue, OtlpKeyValue, OtlpPushOptions, PinoTransportOptions, PollOptions, PushFormat, PushOptions, QueryOptions, QueryRangeOptions, QueryValue, RequestInfo, RequestLike, RequestLoggerOptions, RequestMiddleware, RequestOptions, ResponseInfo, ResponseLike, ResponseType, RetryPolicyOptions, SeriesOptions, TailCallbacks, TimeRangeOptions, TlsOptions, TransportOptions, TransportResponse, VolumeOptions, VolumeRangeOptions, WinstonInfo, WinstonTransportOptions };
|
package/lib/index.js
CHANGED
|
@@ -5,6 +5,8 @@ import { ProxyAgent, Agent, fetch } from 'undici';
|
|
|
5
5
|
import { gzipSync } from 'zlib';
|
|
6
6
|
import { trace, context, isSpanContextValid } from '@opentelemetry/api';
|
|
7
7
|
import { Writable } from 'stream';
|
|
8
|
+
import { AsyncLocalStorage } from 'async_hooks';
|
|
9
|
+
import { randomUUID } from 'crypto';
|
|
8
10
|
import { compress } from 'snappyjs';
|
|
9
11
|
import WebSocket from 'ws';
|
|
10
12
|
|
|
@@ -603,7 +605,7 @@ function secretValues(...values) {
|
|
|
603
605
|
}
|
|
604
606
|
|
|
605
607
|
// src/core/version.ts
|
|
606
|
-
var SDK_VERSION = "0.
|
|
608
|
+
var SDK_VERSION = "0.2.0";
|
|
607
609
|
var PACKAGE_KEY = "grafana-loki";
|
|
608
610
|
var LANGUAGE = "typescript";
|
|
609
611
|
var SDK_KIT_VERSION = "0.3.0";
|
|
@@ -2037,6 +2039,225 @@ var WinstonTransport = class extends Writable {
|
|
|
2037
2039
|
}
|
|
2038
2040
|
};
|
|
2039
2041
|
|
|
2042
|
+
// src/logging-connect.ts
|
|
2043
|
+
var connectLogClient = ({
|
|
2044
|
+
resource,
|
|
2045
|
+
onDropped
|
|
2046
|
+
}) => {
|
|
2047
|
+
const client = LokiClient.fromEnv();
|
|
2048
|
+
const factory = client.logClient;
|
|
2049
|
+
if (typeof factory !== "function") {
|
|
2050
|
+
void client.close();
|
|
2051
|
+
return void 0;
|
|
2052
|
+
}
|
|
2053
|
+
const logs = factory.call(client, { resource, batch: { onDrop: onDropped } });
|
|
2054
|
+
return {
|
|
2055
|
+
logs,
|
|
2056
|
+
close: async () => {
|
|
2057
|
+
await logs.close();
|
|
2058
|
+
await client.close();
|
|
2059
|
+
}
|
|
2060
|
+
};
|
|
2061
|
+
};
|
|
2062
|
+
|
|
2063
|
+
// src/logging/init.ts
|
|
2064
|
+
var LOG_SHIPPED_FIELD = "log_shipped";
|
|
2065
|
+
var requestContext = new AsyncLocalStorage();
|
|
2066
|
+
var GLOBAL_KEY = /* @__PURE__ */ Symbol.for(`grow-codes.${PACKAGE_KEY}.logging`);
|
|
2067
|
+
function withRequestId(requestId, fn) {
|
|
2068
|
+
return requestContext.run({ requestId }, fn);
|
|
2069
|
+
}
|
|
2070
|
+
function currentRequestId() {
|
|
2071
|
+
return requestContext.getStore()?.requestId;
|
|
2072
|
+
}
|
|
2073
|
+
function getLogging() {
|
|
2074
|
+
return globalThis[GLOBAL_KEY];
|
|
2075
|
+
}
|
|
2076
|
+
function first(env, ...names) {
|
|
2077
|
+
for (const name of names) {
|
|
2078
|
+
const value = env[name]?.trim();
|
|
2079
|
+
if (value !== void 0 && value !== "") return value;
|
|
2080
|
+
}
|
|
2081
|
+
return void 0;
|
|
2082
|
+
}
|
|
2083
|
+
function stdoutLine(record, marker) {
|
|
2084
|
+
const line = {
|
|
2085
|
+
time: record.timestamp.toISOString(),
|
|
2086
|
+
level: severityText(record.severity).toLowerCase(),
|
|
2087
|
+
msg: record.body
|
|
2088
|
+
};
|
|
2089
|
+
const resource = record.resource;
|
|
2090
|
+
if (resource["service.name"] !== void 0) line["service"] = resource["service.name"];
|
|
2091
|
+
if (resource["deployment.environment"] !== void 0)
|
|
2092
|
+
line["environment"] = resource["deployment.environment"];
|
|
2093
|
+
if (record.traceId !== void 0) line["trace_id"] = record.traceId;
|
|
2094
|
+
if (record.spanId !== void 0) line["span_id"] = record.spanId;
|
|
2095
|
+
for (const [key, value] of Object.entries(record.attributes)) if (!(key in line)) line[key] = value;
|
|
2096
|
+
if (marker !== void 0) line[LOG_SHIPPED_FIELD] = marker;
|
|
2097
|
+
return JSON.stringify(line);
|
|
2098
|
+
}
|
|
2099
|
+
function initLogging(opts = {}) {
|
|
2100
|
+
const existing = getLogging();
|
|
2101
|
+
if (existing !== void 0) return existing;
|
|
2102
|
+
const env = opts.env ?? process.env;
|
|
2103
|
+
const service = opts.service ?? first(env, "GROW_SERVICE_NAME", "OTEL_SERVICE_NAME") ?? "unknown_service";
|
|
2104
|
+
const environment = first(env, "GROW_ENVIRONMENT", "DEPLOYMENT_ENVIRONMENT");
|
|
2105
|
+
const resource = { "service.name": service };
|
|
2106
|
+
if (environment !== void 0) resource["deployment.environment"] = environment;
|
|
2107
|
+
const levelText = opts.level ?? first(env, "LOG_LEVEL", "GROW_LOG_LEVEL") ?? "info";
|
|
2108
|
+
const minSeverity = parseSeverity(levelText) ?? 9 /* Info */;
|
|
2109
|
+
const write = opts.write ?? ((line) => void process.stdout.write(`${line}
|
|
2110
|
+
`));
|
|
2111
|
+
const redaction = new RedactionProcessor(opts.redaction ?? {});
|
|
2112
|
+
const ship = opts.ship ?? first(env, "GROW_LOGGING_PROVIDER") === PACKAGE_KEY;
|
|
2113
|
+
let connection;
|
|
2114
|
+
if (ship) {
|
|
2115
|
+
try {
|
|
2116
|
+
const onDropped = (records) => {
|
|
2117
|
+
for (const record of records) {
|
|
2118
|
+
try {
|
|
2119
|
+
write(stdoutLine(record, "sdk_failed"));
|
|
2120
|
+
} catch {
|
|
2121
|
+
}
|
|
2122
|
+
}
|
|
2123
|
+
};
|
|
2124
|
+
connection = (opts.connect ?? connectLogClient)({ resource, env, onDropped });
|
|
2125
|
+
} catch (err) {
|
|
2126
|
+
write(
|
|
2127
|
+
stdoutLine(
|
|
2128
|
+
{
|
|
2129
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
2130
|
+
severity: 13 /* Warn */,
|
|
2131
|
+
body: `logging: ${PACKAGE_KEY} transport not available, stdout only (${err.name})`,
|
|
2132
|
+
attributes: {},
|
|
2133
|
+
resource
|
|
2134
|
+
}
|
|
2135
|
+
)
|
|
2136
|
+
);
|
|
2137
|
+
}
|
|
2138
|
+
}
|
|
2139
|
+
const logs = connection?.logs;
|
|
2140
|
+
const shipped = logs !== void 0;
|
|
2141
|
+
const toStdout = opts.stdout ?? true;
|
|
2142
|
+
const sink = {
|
|
2143
|
+
send(input) {
|
|
2144
|
+
const requestId = currentRequestId();
|
|
2145
|
+
const attributes = toAttributes({
|
|
2146
|
+
...requestId === void 0 ? {} : { request_id: requestId },
|
|
2147
|
+
...input.attributes
|
|
2148
|
+
});
|
|
2149
|
+
const severity = input.severity ?? 9 /* Info */;
|
|
2150
|
+
const record = {
|
|
2151
|
+
timestamp: input.timestamp ?? /* @__PURE__ */ new Date(),
|
|
2152
|
+
severity,
|
|
2153
|
+
severityText: severityText(severity),
|
|
2154
|
+
body: input.message,
|
|
2155
|
+
attributes,
|
|
2156
|
+
resource
|
|
2157
|
+
};
|
|
2158
|
+
if (input.traceId !== void 0) record.traceId = input.traceId;
|
|
2159
|
+
if (input.spanId !== void 0) record.spanId = input.spanId;
|
|
2160
|
+
if (input.traceFlags !== void 0) record.traceFlags = input.traceFlags;
|
|
2161
|
+
if (toStdout) {
|
|
2162
|
+
try {
|
|
2163
|
+
write(stdoutLine(redaction.process(record), shipped ? "sdk" : void 0));
|
|
2164
|
+
} catch {
|
|
2165
|
+
}
|
|
2166
|
+
}
|
|
2167
|
+
logs?.send(record);
|
|
2168
|
+
}
|
|
2169
|
+
};
|
|
2170
|
+
let closing;
|
|
2171
|
+
const handle = {
|
|
2172
|
+
logger: new Logger(sink, { minSeverity }),
|
|
2173
|
+
logs,
|
|
2174
|
+
shipped,
|
|
2175
|
+
service,
|
|
2176
|
+
flush: (timeoutMs) => logs === void 0 ? Promise.resolve() : logs.flush(timeoutMs),
|
|
2177
|
+
close: () => {
|
|
2178
|
+
closing ??= (async () => {
|
|
2179
|
+
if (globalThis[GLOBAL_KEY] === handle) globalThis[GLOBAL_KEY] = void 0;
|
|
2180
|
+
await connection?.close();
|
|
2181
|
+
})();
|
|
2182
|
+
return closing;
|
|
2183
|
+
},
|
|
2184
|
+
canary: async (message, attributes = {}) => {
|
|
2185
|
+
if (logs === void 0) return false;
|
|
2186
|
+
logs.send({ message, severity: 9 /* Info */, attributes: { "foundation.canary": true, ...attributes } });
|
|
2187
|
+
await logs.flush(5e3).catch(() => void 0);
|
|
2188
|
+
return true;
|
|
2189
|
+
},
|
|
2190
|
+
pinoStream: () => pinoTee(write, logs, shipped, toStdout)
|
|
2191
|
+
};
|
|
2192
|
+
globalThis[GLOBAL_KEY] = handle;
|
|
2193
|
+
return handle;
|
|
2194
|
+
}
|
|
2195
|
+
function pinoTee(write, logs, shipped, toStdout) {
|
|
2196
|
+
const transport = logs === void 0 ? void 0 : createPinoTransport(logs, { flushOnEnd: false });
|
|
2197
|
+
return new Writable({
|
|
2198
|
+
write(chunk, _encoding, callback) {
|
|
2199
|
+
const text = chunk.toString();
|
|
2200
|
+
if (toStdout) {
|
|
2201
|
+
for (const raw of text.split("\n")) {
|
|
2202
|
+
if (raw.trim() === "") continue;
|
|
2203
|
+
let out = raw;
|
|
2204
|
+
if (shipped) {
|
|
2205
|
+
try {
|
|
2206
|
+
out = JSON.stringify({ ...JSON.parse(raw), [LOG_SHIPPED_FIELD]: "sdk" });
|
|
2207
|
+
} catch {
|
|
2208
|
+
}
|
|
2209
|
+
}
|
|
2210
|
+
write(out);
|
|
2211
|
+
}
|
|
2212
|
+
}
|
|
2213
|
+
if (transport === void 0) callback();
|
|
2214
|
+
else transport.write(chunk, callback);
|
|
2215
|
+
},
|
|
2216
|
+
final(callback) {
|
|
2217
|
+
if (transport === void 0) callback();
|
|
2218
|
+
else transport.end(callback);
|
|
2219
|
+
}
|
|
2220
|
+
});
|
|
2221
|
+
}
|
|
2222
|
+
function headerValue(value) {
|
|
2223
|
+
const v = Array.isArray(value) ? value[0] : value;
|
|
2224
|
+
return v === void 0 || v.trim() === "" ? void 0 : v.trim().slice(0, 128);
|
|
2225
|
+
}
|
|
2226
|
+
function requestLogger(opts = {}) {
|
|
2227
|
+
const header = (opts.header ?? "x-request-id").toLowerCase();
|
|
2228
|
+
const skip = opts.skip ?? ["/health/live", "/health/ready"];
|
|
2229
|
+
return (req, res, next) => {
|
|
2230
|
+
const requestId = headerValue(req.headers[header]) ?? randomUUID();
|
|
2231
|
+
res.setHeader(header, requestId);
|
|
2232
|
+
const path = (req.originalUrl ?? req.url ?? "/").split("?")[0] ?? "/";
|
|
2233
|
+
const start = performance.now();
|
|
2234
|
+
if (!skip.some((p) => path.startsWith(p))) {
|
|
2235
|
+
let done = false;
|
|
2236
|
+
const finish = () => {
|
|
2237
|
+
if (done) return;
|
|
2238
|
+
done = true;
|
|
2239
|
+
const logger = opts.logger ?? getLogging()?.logger;
|
|
2240
|
+
const status = res.statusCode;
|
|
2241
|
+
const attributes = {
|
|
2242
|
+
request_id: requestId,
|
|
2243
|
+
"http.method": req.method ?? "GET",
|
|
2244
|
+
"http.route": path,
|
|
2245
|
+
"http.status_code": status,
|
|
2246
|
+
duration_ms: Math.round((performance.now() - start) * 100) / 100
|
|
2247
|
+
};
|
|
2248
|
+
if (status >= 500) logger?.error("request completed", attributes);
|
|
2249
|
+
else if (status >= 400) logger?.warn("request completed", attributes);
|
|
2250
|
+
else logger?.info("request completed", attributes);
|
|
2251
|
+
};
|
|
2252
|
+
res.once("finish", finish);
|
|
2253
|
+
res.once("close", finish);
|
|
2254
|
+
}
|
|
2255
|
+
withRequestId(requestId, () => {
|
|
2256
|
+
next();
|
|
2257
|
+
});
|
|
2258
|
+
};
|
|
2259
|
+
}
|
|
2260
|
+
|
|
2040
2261
|
// src/time.ts
|
|
2041
2262
|
var NS_PER_MS = 1000000n;
|
|
2042
2263
|
var DIGITS = /^\d+$/;
|
|
@@ -3637,6 +3858,6 @@ var LokiClient = class _LokiClient {
|
|
|
3637
3858
|
}
|
|
3638
3859
|
};
|
|
3639
3860
|
|
|
3640
|
-
export { ALL_STREAMS_SELECTOR, BatchProcessor, BatchingLogClient, CardinalityGuard, DEFAULT_ALLOWED_LABELS, DEFAULT_BATCH_OPTIONS, DEFAULT_REDACT_KEYS, DEFAULT_REQUEST_ID_HEADERS, DEFAULT_TIMEOUTS, ENCODING_FLAGS_HEADER, EnvReader, HttpTransport, LABEL_NAME_PATTERN, LANGUAGE, LogQL, Logger, LokiClient, LokiConfig, LokiLogExporter, LokiLogQueryClient, LokiOtlpExporter, MAX_QUERY_LIMIT, MAX_TENANT_ID_LENGTH, MAX_VENDOR_TEXT, MIN_SECRET_LENGTH, OTLP_SCOPE_NAME, PACKAGE_KEY, REDACTED, RESERVED_METADATA_KEYS, RedactionProcessor, RetryPolicy, SDK_KIT_VERSION, SDK_VERSION, SENSITIVE_FIELD_PARTS, Secret, TENANT_HEADER, VENDOR_ENV, WinstonTransport, attrToString, createDispatcher, createPinoTransport, dateToNanos, decodeBuildInfo, decodeCursor, decodeEntry, decodeIndexStats, decodeQueryResult, decodeRpcStatusMessage, decodeSeries, decodeStreams, decodeStringList, decodeTailFrame, definedOnly, describeCommonConfig, encodeCursor, encodePushRequest, entryToLogRecord, formatLabelSet, healthStatus, isHealthyWord, isIdempotentMethod, isRetryableStatus, isSensitiveField, isSensitiveHeader, isValidLabelName, mergeOptions, mergeStreams, msToDuration, nanosToDate, normalizeLabelName, optionalNanos, parseBool, parseDuration, parseInteger, parseRetryAfter, pinoLevelToSeverity, pinoLineToRecord, probeHealth, quoteLogQL, readCommonEnv, recordsToOtlpJson, recordsToStreams, redactError, redactFields, redactHeaders, redactSecretsInText, redactText, redactUrl, resolveBatchOptions, resolveCommonConfig, safeCall, safeLogger, secondsToDate, secretValues, silentLogger, snappyCompress, stringMap, tenantIdProblem, toNanos, toOtlpValue, toSearchLogQL, validateCommonConfig, validateLabelName, validateLabels, winstonLevelToSeverity };
|
|
3861
|
+
export { ALL_STREAMS_SELECTOR, BatchProcessor, BatchingLogClient, CardinalityGuard, DEFAULT_ALLOWED_LABELS, DEFAULT_BATCH_OPTIONS, DEFAULT_REDACT_KEYS, DEFAULT_REQUEST_ID_HEADERS, DEFAULT_TIMEOUTS, ENCODING_FLAGS_HEADER, EnvReader, HttpTransport, LABEL_NAME_PATTERN, LANGUAGE, LOG_SHIPPED_FIELD, LogQL, Logger, LokiClient, LokiConfig, LokiLogExporter, LokiLogQueryClient, LokiOtlpExporter, MAX_QUERY_LIMIT, MAX_TENANT_ID_LENGTH, MAX_VENDOR_TEXT, MIN_SECRET_LENGTH, OTLP_SCOPE_NAME, PACKAGE_KEY, REDACTED, RESERVED_METADATA_KEYS, RedactionProcessor, RetryPolicy, SDK_KIT_VERSION, SDK_VERSION, SENSITIVE_FIELD_PARTS, Secret, TENANT_HEADER, VENDOR_ENV, WinstonTransport, attrToString, createDispatcher, createPinoTransport, currentRequestId, dateToNanos, decodeBuildInfo, decodeCursor, decodeEntry, decodeIndexStats, decodeQueryResult, decodeRpcStatusMessage, decodeSeries, decodeStreams, decodeStringList, decodeTailFrame, definedOnly, describeCommonConfig, encodeCursor, encodePushRequest, entryToLogRecord, formatLabelSet, getLogging, healthStatus, initLogging, isHealthyWord, isIdempotentMethod, isRetryableStatus, isSensitiveField, isSensitiveHeader, isValidLabelName, mergeOptions, mergeStreams, msToDuration, nanosToDate, normalizeLabelName, optionalNanos, parseBool, parseDuration, parseInteger, parseRetryAfter, pinoLevelToSeverity, pinoLineToRecord, probeHealth, quoteLogQL, readCommonEnv, recordsToOtlpJson, recordsToStreams, redactError, redactFields, redactHeaders, redactSecretsInText, redactText, redactUrl, requestLogger, resolveBatchOptions, resolveCommonConfig, safeCall, safeLogger, secondsToDate, secretValues, silentLogger, snappyCompress, stdoutLine, stringMap, tenantIdProblem, toNanos, toOtlpValue, toSearchLogQL, validateCommonConfig, validateLabelName, validateLabels, winstonLevelToSeverity, withRequestId };
|
|
3641
3862
|
//# sourceMappingURL=index.js.map
|
|
3642
3863
|
//# sourceMappingURL=index.js.map
|