@google-cloud/pino-logging-gcp-config
Version:
Module to create a basic Pino LoggerConfig to support Google Cloud structured logging
168 lines (167 loc) • 6.21 kB
TypeScript
/**
* Copyright 2024 Google LLC
*
* 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.
*/
/**
* @fileoverview Create a default LoggerConfig for pino structured logging.
*
* @see https://cloud.google.com/logging/docs/structured-logging
*/
import * as pino from 'pino';
import { ServiceContext } from '@google-cloud/logging';
import * as gax from 'google-gax';
/**
* Parameters for configuring GCP logging for Pino, allows specifying
* serviceContext for Error Reporting.
*/
export interface GCPLoggingPinoOptions {
/**
* Optional details of service to be logged, and used in Cloud Error
* Reporting.
*
* If specified, the {@link ServiceContext.service} name must be given.
*
* If not specified, a service name will be auto-detected from the
* environment.
*
* @see https://cloud.google.com/error-reporting/docs/formatting-error-messages
*
*/
serviceContext?: ServiceContext;
/**
* Optional Google Cloud project ID to be used for composing the
* 'logging.googleapis.com/trace' field.
*
* If not specified, the project ID will be auto-detected from the
* environment.
*/
traceGoogleCloudProjectId?: string;
/**
* Optional GoogleAuth - used to override defaults when detecting
* ServiceContext and project ID from the environment.
*/
auth?: gax.GoogleAuth;
/**
* Optional pino destination stream to be used for any
* diagnostic messages.
*/
pinoDestinationStream?: pino.DestinationStream;
/**
* Prevent the diagnostic log message from being emitted.
*/
inihibitDiagnosticMessage?: boolean;
}
/**
* Encapsulates configuration and methods for formatting pino logs for Google
* Cloud Logging.
*/
declare class GcpLoggingPino {
serviceContext: ServiceContext | null;
traceGoogleCloudProjectId: string | null;
pendingInit: Promise<void> | null;
pinoLoggerOptions: pino.LoggerOptions;
constructor(options?: GCPLoggingPinoOptions, pinoLoggerOptionsMixin?: pino.LoggerOptions);
/**
* Resolves and initializes the configuration options for the logger.
*
* This function sets up the `serviceContext` and `traceGoogleCloudProjectId`
* properties for the logger. It uses the provided options or attempts to
* auto-detect values from the environment if they are not specified.
*
* @param options Configuration options for GCP logging.
* @return an array of promises for async init actions.
*/
initializeOptions(options?: GCPLoggingPinoOptions): Promise<void>[];
/**
* Outputs a single log line once per process containing the diagnostic info
* for this logger.
*
* Note that it is not possible for this package to perform API level logging
* with a line of the form cloud-solutions/pino-logging-gcp-config-v1.0.0
*/
outputDiagnosticEntry(pinoDestinationStream?: pino.DestinationStream): void;
/**
* Creates a JSON fragment string containing the timestamp in GCP logging
* format.
*
* @example ', "timestamp": { "seconds": 123456789, "nanos": 123000000 }'
*
* Creating a string with seconds/nanos is ~10x faster than formatting the
* timestamp as an ISO string.
*
* @see https://cloud.google.com/logging/docs/agent/logging/configuration#timestamp-processing
*
* As Javascript Date uses millisecond precision, in
* {@link formatLogObject} the logger adds a monotonically increasing insertId
* into the log object to preserve log order inside GCP logging.
*
* @see https://github.com/googleapis/nodejs-logging/blob/main/src/entry.ts#L189
*/
static getGcpLoggingTimestamp(): string;
/**
* Converts pino log level to Google severity level.
*
* @see pino.LoggerOptions.formatters.level
*/
static pinoLevelToGcpSeverity(pinoSeverityLabel: string, pinoSeverityLevel: number): Record<string, unknown>;
/**
* Reformats log entry record for GCP.
*
* * Adds OpenTelemetry properties with correct key.
* * Adds stack_trace if an Error is given in the err property.
* * Adds serviceContext
* * Adds sequential insertId to preserve logging order.
*/
formatLogObject(input: Record<string, unknown>): Record<string, unknown>;
/**
* Creates a pino.LoggerOptions configured for GCP structured logging.
*/
buidPinoLoggerOptions(pinoOptionsMixin?: pino.LoggerOptions): pino.LoggerOptions;
}
/**
* Creates a {@link pino.LoggerOptions} object which configures pino to output
* JSON records compatible with
* {@link https://cloud.google.com/logging/docs/structured-logging|Google Cloud structured Logging}.
*
* @param pinoLoggerOptionsMixin Additional Pino Logger settings that will be added to
* the returned value.
*
* @throws {Error} If `serviceContext.service` is provided but is not a valid
* string or is empty.
*
* @example
* const logger = pino.pino(
* createGcpLoggingPinoConfig(
* {
* serviceContext: {
* service: 'my-service',
* version: '1.2.3',
* },
* },
* {
* // Set Pino log level to 'debug'.
* level: 'debug',
* }
* )
* );
*
* logger.info('hello world');
* logger.error(err, 'failure: ' + err);
*/
export declare function createGcpLoggingPinoConfig(options?: GCPLoggingPinoOptions, pinoLoggerOptionsMixin?: pino.LoggerOptions): pino.LoggerOptions;
export declare const TEST_ONLY: {
PINO_TO_GCP_LOG_LEVELS: Record<pino.Level, string>;
GcpLoggingPino: typeof GcpLoggingPino;
};
export {};