All files / logger/src file-transport.ts

100% Statements 8/8
80% Branches 4/5
100% Functions 4/4
100% Lines 8/8

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                                              6x 6x 6x 6x       6x 6x 5x 1x      
import { appendFile, mkdir } from 'node:fs/promises';
import { dirname } from 'node:path';
 
import { formatTagPrefix } from './tags.ts';
import type { Transport } from './types.ts';
 
type FileTransportOptions = {
  filePath: string;
  tags?: boolean;
};
 
/**
 * Creates a file transport that appends timestamped log lines to a file.
 * Parent directories are created automatically.
 *
 * This transport requires Node.js (`node:fs/promises`).
 *
 * @param options - Options for the file transport.
 * @param options.filePath - Absolute path to the log file.
 * @param options.tags - Whether to include tags in the output (default: `true`).
 * @returns A transport function that appends to the file.
 */
export function makeFileTransport(options: FileTransportOptions): Transport {
  const { filePath, tags = true } = options;
  return (entry) => {
    const tagPrefix = formatTagPrefix(tags, entry);
    const parts = [
      ...(entry.message ? [entry.message] : []),
      ...(entry.data ?? []),
    ];
    const line = `${new Date().toISOString()} [${entry.level}] ${tagPrefix}${parts.join(' ')}\n`;
    mkdir(dirname(filePath), { recursive: true })
      .then(async () => appendFile(filePath, line))
      .catch(() => undefined);
  };
}