ubuntu

如何配置Ubuntu下的Node.js日志

小樊
49
2025-04-07 01:07:11
栏目: 编程语言

在Ubuntu下配置Node.js应用程序的日志,可以使用多种方法。以下是一些常见的方法:

1. 使用内置的console.log

最简单的方法是使用Node.js内置的console.log进行日志记录。

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  console.log('Request received at', new Date());
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

2. 使用第三方日志库

使用第三方日志库可以提供更多的功能和灵活性。常用的日志库包括winstonmorgan

使用winston

winston是一个功能强大的日志库,支持多种传输方式(如文件、控制台、HTTP等)。

首先,安装winston

npm install winston

然后,在你的Node.js应用程序中配置winston

const express = require('express');
const winston = require('winston');
const app = express();
const port = 3000;

// 配置winston
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format: winston.format.simple()
  }));
}

app.get('/', (req, res) => {
  logger.info('Request received at', new Date());
  res.send('Hello World!');
});

app.listen(port, () => {
  logger.info(`Server running at http://localhost:${port}/`);
});

使用morgan

morgan是一个HTTP请求日志中间件,适用于Express应用程序。

首先,安装morgan

npm install morgan

然后,在你的Node.js应用程序中配置morgan

const express = require('express');
const morgan = require('morgan');
const app = express();
const port = 3000;

// 配置morgan
app.use(morgan('combined'));

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

3. 使用环境变量配置日志级别

你可以使用环境变量来配置日志级别,以便在不同环境下使用不同的日志级别。

const express = require('express');
const winston = require('winston');
const app = express();
const port = process.env.PORT || 3000;

// 配置winston
const logger = winston.createLogger({
  level: process.env.LOG_LEVEL || 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format: winston.format.simple()
  }));
}

app.get('/', (req, res) => {
  logger.info('Request received at', new Date());
  res.send('Hello World!');
});

app.listen(port, () => {
  logger.info(`Server running at http://localhost:${port}/`);
});

你可以通过设置环境变量来控制日志级别:

LOG_LEVEL=debug npm start

4. 使用pm2进行进程管理

pm2是一个进程管理器,可以方便地管理Node.js应用程序,并提供日志管理功能。

首先,安装pm2

npm install pm2 -g

然后,使用pm2启动你的Node.js应用程序:

pm2 start app.js --name my-app

pm2会自动管理日志文件,并提供日志查看和管理功能。

通过这些方法,你可以在Ubuntu下灵活地配置Node.js应用程序的日志。

0
看了该问题的人还看了