Extensible TypeScript Logger for Node.js and Browser with customizable log levels, pretty or JSON output formatting, and universal compatibility.
—
Comprehensive configuration system for customizing logger behavior, output formatting, styling, masking, and operational settings.
Main configuration interface for logger initialization with all available options.
/**
* Logger configuration parameters
* @template LogObj - Type for log object structure
*/
interface ISettingsParam<LogObj> {
/** Output format: "json" for structured output, "pretty" for human-readable, "hidden" to suppress output */
type?: "json" | "pretty" | "hidden";
/** Logger name for identification and hierarchy */
name?: string;
/** Parent logger names for nested logger hierarchies */
parentNames?: string[];
/** Minimum log level to output (0=silly, 1=trace, 2=debug, 3=info, 4=warn, 5=error, 6=fatal) */
minLevel?: number;
/** Parent logger names for nested logger hierarchies */
parentNames?: string[];
/** Property name for arguments array in JSON output */
argumentsArrayName?: string;
/** Hide file position information in production environments */
hideLogPositionForProduction?: boolean;
/** Template string for pretty log format with placeholders */
prettyLogTemplate?: string;
/** Template string for error formatting */
prettyErrorTemplate?: string;
/** Template string for error stack trace formatting */
prettyErrorStackTemplate?: string;
/** Separator for parent logger names in error output */
prettyErrorParentNamesSeparator?: string;
/** Delimiter for logger names in error output */
prettyErrorLoggerNameDelimiter?: string;
/** Apply ANSI color styling to pretty logs */
stylePrettyLogs?: boolean;
/** Timezone for timestamp formatting */
prettyLogTimeZone?: "UTC" | "local";
/** ANSI styling configuration for different log components */
prettyLogStyles?: IPrettyLogStyles;
/** Options for object inspection and formatting */
prettyInspectOptions?: InspectOptions;
/** Property name to store metadata in log objects */
metaProperty?: string;
/** Replacement text for masked sensitive values */
maskPlaceholder?: string;
/** Array of object keys whose values should be masked */
maskValuesOfKeys?: string[];
/** Whether key masking should be case-insensitive */
maskValuesOfKeysCaseInsensitive?: boolean;
/** Regular expressions for masking values in logs */
maskValuesRegEx?: RegExp[];
/** Prefix arguments added to every log message */
prefix?: unknown[];
/** Array of attached transport functions */
attachedTransports?: ((transportLogger: LogObj & ILogObjMeta) => void)[];
/** Override default internal functions */
overwrite?: ConfigurationOverrides<LogObj>;
}Usage Examples:
import { Logger } from "tslog";
// Basic configuration
const logger = new Logger({
name: "MyApp",
type: "pretty",
minLevel: 2,
});
// Production configuration
const prodLogger = new Logger({
name: "ProductionApp",
type: "json",
hideLogPositionForProduction: true,
prettyLogTimeZone: "UTC",
maskValuesOfKeys: ["password", "token", "secret"],
maskPlaceholder: "[REDACTED]",
});
// Development configuration with styling
const devLogger = new Logger({
name: "DevApp",
type: "pretty",
stylePrettyLogs: true,
prettyLogStyles: {
logLevelName: {
ERROR: ["bold", "red"],
WARN: ["bold", "yellow"],
INFO: ["bold", "blue"],
},
},
});ANSI styling options for different components of pretty-formatted log output.
interface IPrettyLogStyles {
/** Year component styling */
yyyy?: TStyle;
/** Month component styling */
mm?: TStyle;
/** Day component styling */
dd?: TStyle;
/** Hour component styling */
hh?: TStyle;
/** Minute component styling */
MM?: TStyle;
/** Second component styling */
ss?: TStyle;
/** Millisecond component styling */
ms?: TStyle;
/** Full ISO date string styling */
dateIsoStr?: TStyle;
/** Log level name styling */
logLevelName?: TStyle;
/** File name styling */
fileName?: TStyle;
/** File name with line number styling */
fileNameWithLine?: TStyle;
/** File path styling */
filePath?: TStyle;
/** File line number styling */
fileLine?: TStyle;
/** File path with line number styling */
filePathWithLine?: TStyle;
/** Logger name styling */
name?: TStyle;
/** Logger name with prefix delimiter styling */
nameWithDelimiterPrefix?: TStyle;
/** Logger name with suffix delimiter styling */
nameWithDelimiterSuffix?: TStyle;
/** Error name styling */
errorName?: TStyle;
/** Error message styling */
errorMessage?: TStyle;
}
type TStyle =
| null
| string
| string[]
| {
[value: string]: null | string | string[];
};Usage Examples:
import { Logger } from "tslog";
// Custom styling configuration
const styledLogger = new Logger({
name: "StyledApp",
type: "pretty",
stylePrettyLogs: true,
prettyLogStyles: {
// Style log levels differently
logLevelName: {
ERROR: ["bold", "red", "bgWhite"],
WARN: ["bold", "yellow"],
INFO: ["bold", "blue"],
DEBUG: ["dim", "green"],
},
// Style timestamps
dateIsoStr: ["dim", "white"],
// Style file paths
filePathWithLine: ["underline", "cyan"],
// Style logger names
name: ["bold", "magenta"],
},
});
// Available style options: colors, background colors, and modifiers
const detailedStyles = {
logLevelName: {
// Colors: black, red, green, yellow, blue, magenta, cyan, white
// Bright colors: blackBright, redBright, greenBright, etc.
ERROR: ["bold", "redBright"],
// Background colors: bgBlack, bgRed, bgGreen, etc.
// Bright backgrounds: bgBlackBright, bgRedBright, etc.
WARN: ["bold", "black", "bgYellow"],
// Modifiers: bold, dim, italic, underline, strikethrough, inverse
DEBUG: ["dim", "italic", "green"],
},
};Customizable templates for log output formatting with placeholder replacement.
/**
* Default pretty log template with available placeholders:
* {{yyyy}}, {{mm}}, {{dd}}, {{hh}}, {{MM}}, {{ss}}, {{ms}}
* {{dateIsoStr}}, {{logLevelName}}, {{fileName}}, {{filePath}}
* {{fileLine}}, {{filePathWithLine}}, {{name}}, {{nameWithDelimiterPrefix}}
*/
prettyLogTemplate: string; // Default: "{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}\t{{logLevelName}}\t{{filePathWithLine}}{{nameWithDelimiterPrefix}}\t"
/**
* Template for error formatting
*/
prettyErrorTemplate: string; // Default: "\n{{errorName}} {{errorMessage}}\nerror stack:\n{{errorStack}}"
/**
* Template for error stack trace entries
*/
prettyErrorStackTemplate: string; // Default: " • {{fileName}}\t{{method}}\n\t{{filePathWithLine}}"Usage Examples:
import { Logger } from "tslog";
// Custom template configuration
const customLogger = new Logger({
name: "CustomFormat",
type: "pretty",
prettyLogTemplate: "[{{dateIsoStr}}] {{logLevelName}} ({{name}}): ",
prettyErrorTemplate: "ERROR: {{errorName}} - {{errorMessage}}\nStack:\n{{errorStack}}",
prettyErrorStackTemplate: " at {{method}} ({{filePathWithLine}})",
});
// Minimal template
const minimalLogger = new Logger({
type: "pretty",
prettyLogTemplate: "{{logLevelName}}: ",
});Security features for hiding sensitive information in log output.
/**
* Masking configuration options
*/
interface MaskingConfig {
/** Replacement text for masked values */
maskPlaceholder?: string; // Default: "[***]"
/** Object keys whose values should be masked */
maskValuesOfKeys?: string[]; // Default: ["password"]
/** Case-insensitive key matching */
maskValuesOfKeysCaseInsensitive?: boolean; // Default: false
/** Regular expressions for value masking */
maskValuesRegEx?: RegExp[];
}Usage Examples:
import { Logger } from "tslog";
// Security-focused logger
const secureLogger = new Logger({
name: "SecureApp",
maskPlaceholder: "[REDACTED]",
maskValuesOfKeys: [
"password", "token", "secret", "key", "auth",
"authorization", "credential", "apiKey"
],
maskValuesOfKeysCaseInsensitive: true,
maskValuesRegEx: [
/\b[\w\.-]+@[\w\.-]+\.\w+\b/g, // Email addresses
/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g, // Credit card numbers
],
});
// Example of masking in action
secureLogger.info("User login", {
username: "john_doe",
password: "secret123", // Will be masked
email: "john@example.com", // Will be masked by regex
});Advanced configuration for overriding internal logger functions.
interface ConfigurationOverrides<LogObj> {
/** Override placeholder replacement function */
addPlaceholders?: (logObjMeta: IMeta, placeholderValues: Record<string, string | number>) => void;
/** Override value masking function */
mask?: (args: unknown[]) => unknown[];
/** Override log object creation function */
toLogObj?: (args: unknown[], clonesLogObj?: LogObj) => LogObj;
/** Override metadata addition function */
addMeta?: (logObj: LogObj, logLevelId: number, logLevelName: string) => LogObj & ILogObjMeta;
/** Override metadata formatting function */
formatMeta?: (meta?: IMeta) => string;
/** Override log object formatting function */
formatLogObj?: (maskedArgs: unknown[], settings: ISettings<LogObj>) => { args: unknown[]; errors: string[] };
/** Override formatted output transport function */
transportFormatted?: (logMetaMarkup: string, logArgs: unknown[], logErrors: string[], settings: ISettings<LogObj>) => void;
/** Override JSON output transport function */
transportJSON?: (json: unknown) => void;
}/**
* Resolved settings interface with all defaults applied
* @template LogObj - Type for log object structure
*/
interface ISettings<LogObj> extends ISettingsParam<LogObj> {
type: "json" | "pretty" | "hidden";
minLevel: number;
hideLogPositionForProduction: boolean;
prettyLogTemplate: string;
prettyErrorTemplate: string;
prettyErrorStackTemplate: string;
prettyErrorParentNamesSeparator: string;
prettyErrorLoggerNameDelimiter: string;
stylePrettyLogs: boolean;
prettyLogTimeZone: "UTC" | "local";
prettyLogStyles: IPrettyLogStyles;
prettyInspectOptions: InspectOptions;
metaProperty: string;
maskPlaceholder: string;
maskValuesOfKeys: string[];
maskValuesOfKeysCaseInsensitive: boolean;
prefix: unknown[];
attachedTransports: ((transportLogger: LogObj & ILogObjMeta) => void)[];
}/**
* Options for object inspection and formatting
* Based on Node.js util.inspect options
*/
interface InspectOptions {
/** Enable colors in output */
colors?: boolean;
/** Compact object formatting */
compact?: boolean;
/** Maximum depth for object inspection */
depth?: number;
/** Maximum array length to display */
maxArrayLength?: number;
/** Maximum string length to display */
maxStringLength?: number;
/** Show hidden properties */
showHidden?: boolean;
/** Show proxy details */
showProxy?: boolean;
}Install with Tessl CLI
npx tessl i tessl/npm-tslog