UNPKG

loglayer

Version:

A modern logging library with a fluent API for specifying log messages, metadata and errors

565 lines (554 loc) 20.4 kB
import { ILogBuilder, MessageDataType, ILogLayer, IContextManager, ErrorOnlyOpts, LogLevel, LogLayerTransport as LogLayerTransport$1 } from '@loglayer/shared'; export { ErrorOnlyOpts, ILogBuilder, ILogLayer, LogLayerTransport, LogLevel } from '@loglayer/shared'; import { LogLayerPlugin, PluginCallbackType, PluginBeforeDataOutParams, PluginShouldSendToLoggerParams, PluginBeforeMessageOutParams } from '@loglayer/plugin'; export * from '@loglayer/plugin'; import { LogLayerTransport, BaseTransport, LogLayerTransportConfig, LogLevel as LogLevel$1, LogLayerTransportParams } from '@loglayer/transport'; /** * A class that contains methods to specify log metadata and an error and assembles * it together to form a data object that can be passed into the transport. */ declare class LogBuilder implements ILogBuilder { private err; private metadata; private structuredLogger; private hasMetadata; private pluginManager; constructor(structuredLogger: LogLayer); /** * Specifies metadata to include with the log message * * @see {@link https://loglayer.dev/logging-api/metadata.html | Metadata Docs} */ withMetadata(metadata?: Record<string, any>): this; /** * Specifies an Error to include with the log message * * @see {@link https://loglayer.dev/logging-api/error-handling.html | Error Handling Docs} */ withError(error: any): this; /** * Sends a log message to the logging library under an info log level. */ info(...messages: MessageDataType[]): void; /** * Sends a log message to the logging library under the warn log level */ warn(...messages: MessageDataType[]): void; /** * Sends a log message to the logging library under the error log level */ error(...messages: MessageDataType[]): void; /** * Sends a log message to the logging library under the debug log level * * The logging library may or may not support multiple message parameters and only * the first parameter would be used. */ debug(...messages: MessageDataType[]): void; /** * Sends a log message to the logging library under the trace log level * * The logging library may or may not support multiple message parameters and only * the first parameter would be used. */ trace(...messages: MessageDataType[]): void; /** * Sends a log message to the logging library under the fatal log level * * The logging library may or may not support multiple message parameters and only * the first parameter would be used. */ fatal(...messages: MessageDataType[]): void; /** * All logging inputs are dropped and stops sending logs to the logging library. */ disableLogging(): this; /** * Enable sending logs to the logging library. */ enableLogging(): this; private formatLog; } /** * A class that manages plugins and runs their callbacks. * Used by LogLayer to run plugins at various stages of the logging process. */ declare class PluginManager { private idToPlugin; private onBeforeDataOut; private shouldSendToLogger; private onMetadataCalled; private onBeforeMessageOut; private onContextCalled; constructor(plugins: Array<LogLayerPlugin>); private mapPlugins; private indexPlugins; hasPlugins(callbackType: PluginCallbackType): boolean; countPlugins(callbackType?: PluginCallbackType): number; addPlugins(plugins: Array<LogLayerPlugin>): void; enablePlugin(id: string): void; disablePlugin(id: string): void; removePlugin(id: string): void; /** * Runs plugins that defines onBeforeDataOut. */ runOnBeforeDataOut(params: PluginBeforeDataOutParams, loglayer: ILogLayer): Record<string, any> | undefined; /** * Runs plugins that define shouldSendToLogger. Any plugin that returns false will prevent the message from being sent to the transport. */ runShouldSendToLogger(params: PluginShouldSendToLoggerParams, loglayer: ILogLayer): boolean; /** * Runs plugins that define onMetadataCalled. */ runOnMetadataCalled(metadata: Record<string, any>, loglayer: ILogLayer): Record<string, any> | null; runOnBeforeMessageOut(params: PluginBeforeMessageOutParams, loglayer: ILogLayer): MessageDataType[]; /** * Runs plugins that define onContextCalled. */ runOnContextCalled(context: Record<string, any>, loglayer: ILogLayer): Record<string, any> | null; } type ErrorSerializerType = (err: any) => Record<string, any> | string; /** * Configuration options for LogLayer * @see {@link https://loglayer.dev/configuration.html | LogLayer Configuration Docs} */ interface LogLayerConfig { /** * The prefix to prepend to all log messages */ prefix?: string; /** * Set to false to drop all log input and stop sending to the logging * library. * * Can be re-enabled with `enableLogging()`. * * Default is `true`. */ enabled?: boolean; /** * If set to true, will also output messages via console logging before * sending to the logging library. * * Useful for troubleshooting a logging library / transports * to ensure logs are still being created when the underlying * does not print anything. */ consoleDebug?: boolean; /** * The transport(s) that implements a logging library to send logs to. * Can be a single transport or an array of transports. */ transport: LogLayerTransport | Array<LogLayerTransport>; /** * Plugins to use. */ plugins?: Array<LogLayerPlugin>; /** * A function that takes in an incoming Error type and transforms it into an object. * Used in the event that the logging library does not natively support serialization of errors. */ errorSerializer?: ErrorSerializerType; /** * Logging libraries may require a specific field name for errors so it knows * how to parse them. * * Default is 'err'. */ errorFieldName?: string; /** * If true, always copy error.message if available as a log message along * with providing the error data to the logging library. * * Can be overridden individually by setting `copyMsg: false` in the `onlyError()` * call. * * Default is false. */ copyMsgOnOnlyError?: boolean; /** * If set to true, the error will be included as part of metadata instead of * of the root of the log data. * * metadataFieldName must be set to true for this to work. * * Default is false. */ errorFieldInMetadata?: boolean; /** * If specified, will set the context object to a specific field * instead of flattening the data alongside the error and message. * * Default is context data will be flattened. */ contextFieldName?: string; /** * If specified, will set the metadata object to a specific field * instead of flattening the data alongside the error and message. * * Default is metadata will be flattened. */ metadataFieldName?: string; /** * If set to true, will not include context data in the log message. */ muteContext?: boolean; /** * If set to true, will not include metadata data in the log message. */ muteMetadata?: boolean; } interface FormatLogParams { logLevel: LogLevel; params?: any[]; metadata?: Record<string, any> | null; err?: any; } /** * Wraps around a logging framework to provide convenience methods that allow * developers to programmatically specify their errors and metadata along with * a message in a consistent fashion. */ declare class LogLayer implements ILogLayer { private pluginManager; private idToTransport; private hasMultipleTransports; private singleTransport; private contextManager; _config: LogLayerConfig; constructor(config: LogLayerConfig); /** * Sets the context manager to use for managing context data. */ withContextManager(contextManager: IContextManager): LogLayer; /** * Returns the context manager instance being used. */ getContextManager<M extends IContextManager = IContextManager>(): M; private _initializeTransports; /** * Calls child() and sets the prefix to be included with every log message. * * @see {@link https://loglayer.dev/logging-api/basic-logging.html#message-prefixing | Message Prefixing Docs} */ withPrefix(prefix: string): LogLayer; /** * Appends context data which will be included with * every log entry. * * Passing in an empty value / object will *not* clear the context. * * To clear the context, use {@link https://loglayer.dev/logging-api/context.html#clearing-context | clearContext()}. * * @see {@link https://loglayer.dev/logging-api/context.html | Context Docs} */ withContext(context?: Record<string, any>): LogLayer; /** * Clears the context data. */ clearContext(): this; getContext(): Record<string, any>; /** * Add additional plugins. * * @see {@link https://loglayer.dev/plugins/ | Plugins Docs} */ addPlugins(plugins: Array<LogLayerPlugin>): void; /** * Enables a plugin by id. * * @see {@link https://loglayer.dev/plugins/ | Plugins Docs} */ enablePlugin(id: string): void; /** * Disables a plugin by id. * * @see {@link https://loglayer.dev/plugins/ | Plugins Docs} */ disablePlugin(id: string): void; /** * Removes a plugin by id. * * @see {@link https://loglayer.dev/plugins/ | Plugins Docs} */ removePlugin(id: string): void; /** * Specifies metadata to include with the log message * * @see {@link https://loglayer.dev/logging-api/metadata.html | Metadata Docs} */ withMetadata(metadata?: Record<string, any>): LogBuilder; /** * Specifies an Error to include with the log message * * @see {@link https://loglayer.dev/logging-api/error-handling.html | Error Handling Docs} */ withError(error: any): LogBuilder; /** * Creates a new instance of LogLayer but with the initialization * configuration and context copied over. * * @see {@link https://loglayer.dev/logging-api/child-loggers.html | Child Logging Docs} */ child(): LogLayer; /** * Replaces all existing transports with new ones. * * When used with child loggers, it only affects the current logger instance * and does not modify the parent's transports. * * @see {@link https://loglayer.dev/logging-api/transport-management.html | Transport Management Docs} */ withFreshTransports(transports: LogLayerTransport | Array<LogLayerTransport>): LogLayer; /** * Replaces all existing plugins with new ones. * * When used with child loggers, it only affects the current logger instance * and does not modify the parent's plugins. * * @see {@link https://loglayer.dev/plugins/ | Plugins Docs} */ withFreshPlugins(plugins: Array<LogLayerPlugin>): LogLayer; protected withPluginManager(pluginManager: PluginManager): this; /** * Logs only the error object without a log message * * @see {@link https://loglayer.dev/logging-api/error-handling.html | Error Handling Docs} */ errorOnly(error: any, opts?: ErrorOnlyOpts): void; /** * Logs only metadata without a log message * * @see {@link https://loglayer.dev/logging-api/metadata.html | Metadata Docs} */ metadataOnly(metadata?: Record<string, any>, logLevel?: LogLevel): this; /** * Sends a log message to the logging library under an info log level. * * The logging library may or may not support multiple message parameters and only * the first parameter would be used. * * @see {@link https://loglayer.dev/logging-api/basic-logging.html | Basic Logging Docs} */ info(...messages: MessageDataType[]): void; /** * Sends a log message to the logging library under the warn log level * * @see {@link https://loglayer.dev/logging-api/basic-logging.html | Basic Logging Docs} */ warn(...messages: MessageDataType[]): void; /** * Sends a log message to the logging library under the error log level * * @see {@link https://loglayer.dev/logging-api/basic-logging.html | Basic Logging Docs} */ error(...messages: MessageDataType[]): void; /** * Sends a log message to the logging library under the debug log level * * @see {@link https://loglayer.dev/logging-api/basic-logging.html | Basic Logging Docs} */ debug(...messages: MessageDataType[]): void; /** * Sends a log message to the logging library under the trace log level * * @see {@link https://loglayer.dev/logging-api/basic-logging.html | Basic Logging Docs} */ trace(...messages: MessageDataType[]): void; /** * Sends a log message to the logging library under the fatal log level * * @see {@link https://loglayer.dev/logging-api/basic-logging.html | Basic Logging Docs} */ fatal(...messages: MessageDataType[]): void; /** * All logging inputs are dropped and stops sending logs to the logging library. * * @see {@link https://loglayer.dev/logging-api/basic-logging.html#enabling-disabling-logging | Enabling/Disabling Logging Docs} */ disableLogging(): this; /** * Enable sending logs to the logging library. * * @see {@link https://loglayer.dev/logging-api/basic-logging.html#enabling-disabling-logging | Enabling/Disabling Logging Docs} */ enableLogging(): this; /** * Disables inclusion of context data in the print * * @see {@link https://loglayer.dev/logging-api/context.html#managing-context | Managing Context Docs} */ muteContext(): ILogLayer; /** * Enables inclusion of context data in the print * * @see {@link https://loglayer.dev/logging-api/context.html#managing-context | Managing Context Docs} */ unMuteContext(): ILogLayer; /** * Disables inclusion of metadata in the print * * @see {@link https://loglayer.dev/logging-api/metadata.html#controlling-metadata-output | Controlling Metadata Output Docs} */ muteMetadata(): ILogLayer; /** * Enables inclusion of metadata in the print * * @see {@link https://loglayer.dev/logging-api/metadata.html#controlling-metadata-output | Controlling Metadata Output Docs} */ unMuteMetadata(): ILogLayer; private formatContext; private formatMetadata; /** * Returns a logger instance for a specific transport * * @see {@link https://loglayer.dev/logging-api/transport-management.html | Transport Management Docs} */ getLoggerInstance<Logger>(id: string): Logger | undefined; _formatMessage(messages?: MessageDataType[]): void; _formatLog({ logLevel, params, metadata, err }: FormatLogParams): void; } /** * A mock implementation of the ILogLayer interface that does nothing. * Useful for writing unit tests. */ declare class MockLogLayer implements ILogLayer { private mockLogBuilder; info(...messages: MessageDataType[]): void; warn(...messages: MessageDataType[]): void; error(...messages: MessageDataType[]): void; debug(...messages: MessageDataType[]): void; trace(...messages: MessageDataType[]): void; fatal(...messages: MessageDataType[]): void; getLoggerInstance<T extends LogLayerTransport$1>(id: string): any; errorOnly(error: any, opts?: ErrorOnlyOpts): void; metadataOnly(metadata?: Record<string, any>, logLevel?: LogLevel): void; addPlugins(plugins: Array<LogLayerPlugin>): void; removePlugin(id: string): void; enablePlugin(id: string): void; disablePlugin(id: string): void; withPrefix(prefix: string): ILogLayer; withContext(context?: Record<string, any>): ILogLayer; withError(error: any): ILogBuilder; withMetadata(metadata?: Record<string, any>): ILogBuilder; getContext(): Record<string, any>; clearContext(): ILogLayer; enableLogging(): this; disableLogging(): this; child(): this; muteContext(): this; unMuteContext(): this; muteMetadata(): this; unMuteMetadata(): this; withFreshTransports(transports: LogLayerTransport$1 | Array<LogLayerTransport$1>): this; withFreshPlugins(plugins: Array<LogLayerPlugin>): this; withContextManager(contextManager: any): this; getContextManager(): any; /** * Sets the mock log builder to use for testing. */ setMockLogBuilder(mockLogBuilder: ILogBuilder): void; /** * Returns the mock log builder used for testing. */ getMockLogBuilder(): ILogBuilder; /** * Resets the mock log builder to a new instance of MockLogBuilder. */ resetMockLogBuilder(): void; } /** * A mock implementation of the ILogBuilder interface that does nothing. * Useful for writing unit tests. */ declare class MockLogBuilder implements ILogBuilder { debug(...messages: MessageDataType[]): void; error(...messages: MessageDataType[]): void; info(...messages: MessageDataType[]): void; trace(...messages: MessageDataType[]): void; warn(...messages: MessageDataType[]): void; fatal(...messages: MessageDataType[]): void; enableLogging(): this; disableLogging(): this; withMetadata(metadata?: Record<string, any>): ILogBuilder; withError(error: any): ILogBuilder; } type ConsoleType = typeof console; /** * Configuration options for the ConsoleTransport. */ interface ConsoleTransportConfig extends LogLayerTransportConfig<ConsoleType> { /** * If true, object data will be appended as the last parameter. * If false, object data will be prepended as the first parameter (default). * Has no effect if messageField is defined. */ appendObjectData?: boolean; /** * Minimum log level to process. Defaults to "trace". */ level?: LogLevel$1 | "trace" | "debug" | "info" | "warn" | "error" | "fatal"; /** * If defined, * - will place the message into the specified field in the log object. * - Multi-parameter messages will be joined with a space. Use the sprintf plugin to format messages. * - Only the log object will be logged to the console when this is defined. */ messageField?: string; } /** * Transport for use with a console logger. */ declare class ConsoleTransport extends BaseTransport<ConsoleType> { private appendObjectData; private logLevel; private messageField?; constructor(params: ConsoleTransportConfig); shipToLogger({ logLevel, messages, data, hasData }: LogLayerTransportParams): any[]; } /** * A test logging library that can be used to test LogLayer plugins and transports. * It is meant to be used with the TestTransport. */ declare class TestLoggingLibrary { /** * An array of log lines that have been logged. */ lines: Array<{ level: LogLevel; data: any[]; }>; constructor(); info(...params: any[]): void; warn(...params: any[]): void; error(...params: any[]): void; debug(...params: any[]): void; trace(...params: any[]): void; fatal(...params: any[]): void; private addLine; /** * Get the last line that was logged. Returns null if no lines have been logged. */ getLastLine(): { level: LogLevel; data: any[]; }; /** * Pops the last line that was logged. Returns null if no lines have been logged. */ popLine(): { level: LogLevel; data: any[]; }; /** * Clears all lines that have been logged. */ clearLines(): void; } /** * Transport used for testing purposes. */ declare class TestTransport extends BaseTransport<TestLoggingLibrary> { shipToLogger({ logLevel, messages, data, hasData }: LogLayerTransportParams): any[]; } export { ConsoleTransport, type ErrorSerializerType, LogLayer, type LogLayerConfig, MockLogBuilder, MockLogLayer, TestLoggingLibrary, TestTransport };