loglayer
Version:
A modern logging library with a fluent API for specifying log messages, metadata and errors
668 lines (656 loc) • 24.4 kB
text/typescript
import { LogLayerPlugin, PluginCallbackType, PluginBeforeDataOutParams, PluginShouldSendToLoggerParams, PluginBeforeMessageOutParams } from '@loglayer/plugin';
export { PluginBeforeDataOutFn, PluginBeforeMessageOutFn, PluginCallbackType, PluginOnContextCalledFn, PluginOnMetadataCalledFn, PluginShouldSendToLoggerFn } from '@loglayer/plugin';
import { ILogBuilder, MessageDataType, ILogLayer, IContextManager, ErrorOnlyOpts, LogLevelType, LogLayerTransport as LogLayerTransport$1, LogLevel } from '@loglayer/shared';
export { ErrorOnlyOpts, ILogBuilder, ILogLayer, LogLayerTransport, LogLevel, LogLevelType, PluginBeforeDataOutParams, PluginBeforeMessageOutParams, PluginShouldSendToLoggerParams } from '@loglayer/shared';
import { LogLayerTransport, LoggerlessTransport, LoggerlessTransportConfig, LogLayerTransportParams, BaseTransport, LogLayerTransportConfig } from '@loglayer/transport';
/**
* A class that contains methods to specify log metadata and an error and assembles
* it 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 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 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: LogLevelType;
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;
private logLevelEnabledStatus;
/**
* The configuration object used to initialize the logger.
* This is for internal use only and should not be modified directly.
*/
_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?: LogLevelType): void;
/**
* 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;
/**
* Enables a specific log level
*
* @see {@link https://loglayer.dev/logging-api/basic-logging.html#enabling-disabling-logging | Enabling/Disabling Logging Docs}
*/
enableIndividualLevel(logLevel: LogLevelType): ILogLayer;
/**
* Disables a specific log level
*
* @see {@link https://loglayer.dev/logging-api/basic-logging.html#enabling-disabling-logging | Enabling/Disabling Logging Docs}
*/
disableIndividualLevel(logLevel: LogLevelType): ILogLayer;
/**
* Sets the minimum log level to be used by the logger. Only messages with
* this level or higher severity will be logged.
*
* For example, if you setLevel(LogLevel.warn), this will:
* Enable:
* - warn
* - error
* - fatal
* Disable:
* - info
* - debug
* - trace
*
* @see {@link https://loglayer.dev/logging-api/basic-logging.html#enabling-disabling-logging | Enabling/Disabling Logging Docs}
*/
setLevel(logLevel: LogLevelType): ILogLayer;
/**
* Checks if a specific log level is enabled
*
* @see {@link https://loglayer.dev/logging-api/basic-logging.html#checking-if-a-log-level-is-enabled | Checking if a Log Level is Enabled Docs}
*/
isLevelEnabled(logLevel: LogLevelType): boolean;
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 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;
}
/**
* 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;
enableIndividualLevel(_logLevel: LogLevel): ILogLayer;
disableIndividualLevel(_logLevel: LogLevel): ILogLayer;
setLevel(_logLevel: LogLevel): ILogLayer;
isLevelEnabled(_logLevel: LogLevel): boolean;
/**
* Returns the mock log builder used for testing.
*/
getMockLogBuilder(): ILogBuilder;
/**
* Resets the mock log builder to a new instance of MockLogBuilder.
*/
resetMockLogBuilder(): void;
}
/**
* 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: LogLevelType;
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: LogLevelType;
data: any[];
};
/**
* Pops the last line that was logged. Returns null if no lines have been logged.
*/
popLine(): {
level: LogLevelType;
data: any[];
};
/**
* Clears all lines that have been logged.
*/
clearLines(): void;
}
/**
* Configuration options for the BlankTransport.
*/
interface BlankTransportConfig extends LoggerlessTransportConfig {
/**
* The function that will be called to handle log shipping.
* This is the only required parameter for creating a custom transport.
*/
shipToLogger: (params: LogLayerTransportParams) => any[];
}
/**
* A transport that allows users to quickly create custom transports by providing their own `shipToLogger` function.
*
* This is useful for creating simple custom transports without having to create a completely new transport class from scratch.
*
* @example
* ```typescript
* import { LogLayer, BlankTransport } from 'loglayer';
*
* const log = new LogLayer({
* transport: new BlankTransport({
* shipToLogger: ({ logLevel, messages, data, hasData }) => {
* // Your custom logging logic here
* console.log(`[${logLevel}]`, ...messages, data && hasData ? data : '');
* return messages;
* }
* })
* });
* ```
*/
declare class BlankTransport extends LoggerlessTransport {
private shipToLoggerFn;
constructor(config: BlankTransportConfig);
shipToLogger(params: LogLayerTransportParams): any[];
}
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 | "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;
/**
* If defined, populates the field with the ISO date.
* If dateFn is defined, will call dateFn to derive the date.
*/
dateField?: string;
/**
* If defined, populates the field with the log level.
* If levelFn is defined, will call levelFn to derive the level.
*/
levelField?: string;
/**
* If defined, a function that returns a string or number for the value to be used for the dateField.
*/
dateFn?: () => string | number;
/**
* If defined, a function that returns a string or number for a given log level.
* The input should be the logLevel.
*/
levelFn?: (logLevel: LogLevelType) => string | number;
}
/**
* Transport for use with a console logger.
*/
declare class ConsoleTransport extends BaseTransport<ConsoleType> {
private appendObjectData;
private logLevel;
private messageField?;
private dateField?;
private levelField?;
private dateFn?;
private levelFn?;
constructor(params: ConsoleTransportConfig);
shipToLogger({ logLevel, messages, data, hasData }: LogLayerTransportParams): any[];
}
/**
* Transport used for testing purposes.
*/
declare class TestTransport extends BaseTransport<TestLoggingLibrary> {
shipToLogger({ logLevel, messages, data, hasData }: LogLayerTransportParams): any[];
}
export { BlankTransport, ConsoleTransport, type ErrorSerializerType, LogLayer, type LogLayerConfig, MockLogBuilder, MockLogLayer, TestLoggingLibrary, TestTransport };