溫馨提示×

如何定制Ubuntu Node.js日志格式

小樊
40
2025-02-21 05:01:32
欄目: 編程語言

要定制 Ubuntu 上的 Node.js 應用程序的日志格式,您可以使用以下方法:

  1. 使用第三方日志庫:有許多第三方日志庫可以幫助您定制日志格式,例如 winstonbunyan。這些庫提供了豐富的配置選項,可以讓您自定義日志的輸出格式。

winston 為例,首先安裝它:

npm install winston

然后,在您的 Node.js 應用程序中設置自定義日志格式:

const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.printf(({ timestamp, level, message }) => {
      return `[${timestamp}] ${level.toUpperCase()}: ${message}`;
    })
  ),
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
    new winston.transports.File({ filename: 'logs/combined.log' }),
  ],
});

logger.info('Hello, world!');

在這個例子中,我們使用了 winston.format.combine 方法來組合多個格式化選項。winston.format.timestamp() 添加了時間戳,winston.format.printf() 定義了自定義的日志格式。

  1. 使用 Node.js 內置的 console 模塊:雖然 console 模塊的定制選項有限,但您仍然可以使用一些簡單的字符串操作來自定義日志輸出格式。

例如:

function log(message, level) {
  const timestamp = new Date().toISOString();
  console.log(`[${timestamp}] [${level.toUpperCase()}]: ${message}`);
}

log('Hello, world!', 'info');

這個簡單的 log 函數接受一個消息和一個日志級別,并使用自定義格式輸出日志。

注意:這些示例適用于任何基于 Node.js 的應用程序,不僅僅是 Ubuntu 系統上的應用程序。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女