前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >日志库 winston 的学习笔记 - 创建一个使用 winston 的 Node.js 应用

日志库 winston 的学习笔记 - 创建一个使用 winston 的 Node.js 应用

作者头像
Jerry Wang
发布2021-12-14 13:28:42
1.2K0
发布2021-12-14 13:28:42
举报

winston 被设计为一个简单且通用的日志库,支持多种传输。 传输本质上是日志的存储设备。 每个 winston 记录器都可以在不同级别配置多个存储渠道。例如,人们可能希望将错误日志存储在持久的远程位置(如数据库),但所有调试日志都输出到控制台或本地文件。

使用 winston 的推荐方法是创建您自己的记录器。 最简单的方法是使用 winston.createLogger:

代码语言:javascript
复制
const winston = require('winston');
 
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  defaultMeta: { service: 'user-service' },
  transports: [
    //
    // - Write all logs with level `error` and below to `error.log`
    // - Write all logs with level `info` and below to `combined.log`
    //
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' }),
  ],
});
 
//
// If we're not in production then log to the `console` with the format:
// `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
//
if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format: winston.format.simple(),
  }));
}

winston 的日志等级

代码语言:javascript
复制
const levels = { 
  error: 0,
  warn: 1,
  info: 2,
  http: 3,
  verbose: 4,
  debug: 5,
  silly: 6
};

如何创建 logger

代码语言:javascript
复制
const logger = winston.createLogger({
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

即使 logger 实例创建之后,也能容易地删除或者增添新的 transport:

代码语言:javascript
复制
const files = new winston.transports.File({ filename: 'combined.log' });
const console = new winston.transports.Console();
 
logger
  .clear()          // Remove all transports
  .add(console)     // Add console transport
  .add(files)       // Add file transport
  .remove(console); // Remove console transport

也能使用 logger 的 configure 方法,重新配置新的 transport:

代码语言:javascript
复制
const logger = winston.createLogger({
  level: 'info',
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});
 
//
// Replaces the previous transports with those in the
// new configuration wholesale.
//
const DailyRotateFile = require('winston-daily-rotate-file');
logger.configure({
  level: 'verbose',
  transports: [
    new DailyRotateFile(opts)
  ]
});

在 winston 中,Logger 和 Transport 实例都被视为接受 info 对象的 objectMode 流。

提供给给定格式的 info 参数表示单个日志消息。 对象本身是可变的。 每个信息必须至少具有 level 和 message 属性:

代码语言:javascript
复制
const info = {
  level: 'info',                 // Level of the logging message  
  message: 'Hey! Log something?' // Descriptive message being logged.
};

除了级别和消息之外的属性被视为“元属性”:

代码语言:javascript
复制
const { level, message, ...meta } = info;

我们来动手写一个实际的例子。

主程序:

代码语言:javascript
复制
// @ts-nocheck
var express = require('express');
var app = express();
var DEFAULTPORT = 3003;
var port = process.env.PORT || DEFAULTPORT;
var winstonTest = require("./winstonTest");

app.get('/', function(_req, res){
   res.send("Hello world");
   winstonTest.logMessage('234');
});

app.listen(port, function(){
     console.log("App listens on port: " + port);
});

winstonTest 的实现:

代码语言:javascript
复制
const winston = require('winston');
 
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  defaultMeta: { service: 'user-service' },
  transports: [
    //
    // - Write all logs with level `error` and below to `error.log`
    // - Write all logs with level `info` and below to `combined.log`
    //
    new winston.transports.File({ filename: 'data/error.log', level: 'error' }),
    new winston.transports.File({ filename: 'data/combined.log' }),
  ]
});

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

console.log('Logger initialized successfully!');

function log(content){
    logger.info('hello', { message: content });
}

module.exports = {
    logMessage: log
};

浏览器里输入如下 url: http://localhost:3003/ 在 combined.log 里生成了如下 log 文件:

这就是 winston 最基本的使用方法。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-10-21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • winston 的日志等级
  • 如何创建 logger
相关产品与服务
日志服务
日志服务(Cloud Log Service,CLS)是腾讯云提供的一站式日志服务平台,提供了从日志采集、日志存储到日志检索,图表分析、监控告警、日志投递等多项服务,协助用户通过日志来解决业务运维、服务监控、日志审计等场景问题。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档