winstonでログ出力

winston を使ったスタックトレースの出しかた。

logger.ts

import { createLogger, format, transports } from 'winston';

const { combine, timestamp, errors, printf, cli, metadata } = format;


const myFormat = printf(({ level, message, metadata }) => {
  if (metadata && metadata.stack) {
    return `${metadata.timestamp} ${level}: ${metadata.stack}`;
  } else {
    return `${metadata.timestamp} ${level}: ${message}`;
  }
});

export const logger = createLogger({
  format: combine(
    errors({ stack: true }),
    timestamp(),
    cli(),
    metadata(),
    myFormat,
  ),
  transports: [new transports.Console()],
});

logger.test.ts

import {logger} from '../../src/logger.js'
import { test } from 'vitest'


test("winstonの通常ログ", () => {
  logger.info("これはINFOです。");
});


test("winstonの例外時にスタックトレースを表示する", () => {
  try {
    throw new RangeError("これは範囲エラーです.");
  }catch(err) {
    logger.error(err);
  }
});

テスト出力

 RUN  v2.1.0 /home/hoge/projects/hello_typescript

stdout | __tests__/unit/logger.test.ts > winstonの通常ログ
2024-11-04T10:58:55.786Z info:     これはINFOです。

stdout | __tests__/unit/logger.test.ts > winstonの例外時にスタックトレースを表示する
2024-11-04T10:58:55.789Z error: RangeError: これは範囲エラーです.
    at /home/hoge/projects/hello_typescript/__tests__/unit/logger.test.ts:12:11
    at file:///home/hoge/projects/hello_typescript/node_modules/@vitest/runner/dist/index.js:146:14
    at file:///home/hoge/projects/hello_typescript/node_modules/@vitest/runner/dist/index.js:529:11
    at runWithTimeout (file:///home/hoge/projects/hello_typescript/node_modules/@vitest/runner/dist/index.js:61:7)
    at runTest (file:///home/hoge/projects/hello_typescript/node_modules/@vitest/runner/dist/index.js:982:17)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at runSuite (file:///home/hoge/projects/hello_typescript/node_modules/@vitest/runner/dist/index.js:1131:15)
    at runFiles (file:///home/hoge/projects/hello_typescript/node_modules/@vitest/runner/dist/index.js:1188:5)
    at startTests (file:///home/hoge/projects/hello_typescript/node_modules/@vitest/runner/dist/index.js:1197:3)
    at file:///home/hoge/projects/hello_typescript/node_modules/vitest/dist/chunks/runBaseTests.9YDrdSI4.js:130:11

 ✓ __tests__/unit/logger.test.ts (2)
 ✓ __tests__/unit/main.test.ts (3)
 ✓ build/__tests__/unit/main.test.js (2)

 Test Files  3 passed (3)
      Tests  7 passed (7)
   Start at  19:58:55
   Duration  209ms (transform 52ms, setup 0ms, collect 95ms, tests 12ms, environment 0ms, prepare 141ms)