All files / src/logger log-entry.ts

100% Statements 7/7
100% Branches 3/3
100% Functions 1/1
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60                                                                                                        1x 1708x 1708x 1129x 1129x 1708x 1708x  
import type { Writable } from 'type-fest';
 
import type { LogLevel } from './definition.ts';
 
/**
 * Represents a structured log entry with timestamp and metadata.
 *
 * This type is used internally by formatters and sinks that need to work with structured log data. The timestamp is
 * stored as milliseconds since epoch.
 */
export type LogEntry = {
  /**
   * The severity level of the log entry.
   */
  readonly level: LogLevel;
 
  /**
   * Timestamp when the entry was created (milliseconds since epoch).
   */
  readonly timestamp: number;
 
  /**
   * The formatted message content.
   */
  readonly message: string;
 
  /**
   * Additional arguments provided with the log entry.
   */
  readonly args?: readonly unknown[];
};
 
/**
 * Creates a LogEntry object with the current timestamp.
 *
 * This utility function is used by formatters that need to work with structured log data including timestamps. The
 * timestamp is automatically set to the current time.
 *
 * @example
 *
 * ```ts
 * import { asLogEntry } from 'emitnlog/logger';
 *
 * const entry = asLogEntry('info', 'Operation completed', [{ duration: 150 }]);
 * console.log(entry.timestamp); // Current timestamp in milliseconds
 * ```
 *
 * @param level The log level
 * @param message The log message
 * @param args Additional arguments
 * @returns A LogEntry object with current timestamp
 */
export const asLogEntry = (level: LogLevel, message: string, args?: readonly unknown[]): LogEntry => {
  const entry: Writable<LogEntry> = { level, timestamp: Date.now(), message };
  if (args?.length) {
    entry.args = args;
  }
  return entry;
};