Formatters API Reference

API reference for message formatting utilities in DoubleTie Logger.

Formatters API Reference

This reference documents the message formatting utilities in DoubleTie Logger.

registerFormatter(name, formatter)

Registers a custom formatter for log messages.

Signature:

function registerFormatter(name: string, formatter: Formatter): void;

Parameters:

ParameterTypeDescription
namestringName to identify the formatter
formatterFormatterThe formatter function

Example:

import { registerFormatter } from '@doubletie/logger';
 
// Register a simple JSON formatter
registerFormatter('json', (level, message, args, appName = 'app') => {
  return JSON.stringify({
    timestamp: new Date().toISOString(),
    level,
    app: appName,
    message,
    data: args.length > 0 ? args[0] : undefined
  });
});

getFormatter(name?)

Gets a formatter by name, falling back to default if not found.

Signature:

function getFormatter(name?: string): Formatter;

Parameters:

ParameterTypeDefaultDescription
namestring'default'The formatter name to retrieve

Returns: The formatter function

Example:

import { getFormatter } from '@doubletie/logger';
 
// Get the JSON formatter registered earlier
const jsonFormatter = getFormatter('json');
 
// Format a message using this formatter
const formattedMessage = jsonFormatter('error', 'Database error', [{ code: 500 }], 'api-service');

formatMessage(level, message, args?, formatterName?, appName?)

Formats a log message using the specified formatter.

Signature:

function formatMessage(
  level: LogLevel,
  message: string,
  args?: unknown[],
  formatterName?: string,
  appName?: string
): string;

Parameters:

ParameterTypeDefaultDescription
levelLogLevel-Log level
messagestring-Log message
argsunknown[][]Additional log arguments
formatterNamestring'default'Name of formatter to use
appNamestringundefinedApplication name

Returns: Formatted log message

Example:

import { formatMessage } from '@doubletie/logger';
 
// Format a message using the JSON formatter
const jsonLog = formatMessage(
  'error',
  'Database connection failed',
  [{ retries: 3 }],
  'json',  // Formatter name
  'db-service'  // App name
);
 
console.log(jsonLog);
// Output: {"timestamp":"2023-10-10T12:34:56.789Z","level":"error","app":"db-service","message":"Database connection failed","data":{"retries":3}}

Formatter Type

The type definition for formatter functions.

Signature:

type Formatter = (
  level: LogLevel,
  message: string,
  args: unknown[],
  appName?: string
) => string;

Parameters:

ParameterTypeDescription
levelLogLevelThe log level ('error', 'warn', 'info', 'success', 'debug')
messagestringThe message string being logged
argsunknown[]Array of additional arguments passed to the log method
appNamestringOptional application name for namespace separation

Returns: A formatted string

Built-in Formatters

DoubleTie Logger includes the following built-in formatters:

'default'

The default formatter that includes timestamps, colored log levels, and structured data formatting.

Features:

  • Color-coded log levels (in terminal environments)
  • ISO timestamp
  • Application name prefix (when provided)
  • Pretty-printed JSON for object arguments
  • Support for multiple arguments

Example Output:

2023-10-10T12:34:56.789Z [ERROR] [my-app] Database connection failed { "retries": 3 }

Creating Specialized Formatters

Here are examples of specialized formatters for different use cases:

Minimal Formatter

registerFormatter('minimal', (level, message) => {
  return `[${level.toUpperCase()}] ${message}`;
});

JSON Lines Formatter

registerFormatter('jsonl', (level, message, args, appName) => {
  return JSON.stringify({
    time: new Date().toISOString(),
    level,
    app: appName || 'app',
    msg: message,
    data: args.length > 0 ? args[0] : null
  });
});

CSV Formatter

registerFormatter('csv', (level, message, args, appName) => {
  const timestamp = new Date().toISOString();
  const escapedMessage = message.replace(/"/g, '""');
  const data = args.length > 0 ? JSON.stringify(args[0]).replace(/"/g, '""') : '';
  
  return `"${timestamp}","${level}","${appName || ''}","${escapedMessage}","${data}"`;
});

See Also

On this page

doubletie.com