Winston Logger 可以用在前端做日志记录吗?

Can Winston Logger be used on the front-end for logging?

我正在使用

创建完整的均值堆栈应用程序

NodeJs , Angular 6 , ExpressJs and MongoDB

我已经设法创建了一个服务器并且它运行良好,而不是在我的应用程序中记录错误时使用 console.log 我决定使用 Winston Logger 这是我现在拥有的

Server side

var appRoot = require('app-root-path');
var winston = require('winston');

// define the custom settings for each transport (file, console)
var options = {
    file: {
        level: 'info',
        filename: `${appRoot}/logs/app.log`,
        handleExceptions: true,
        json: true,
        maxsize: 5242880, // 5MB
        maxFiles: 5,
        colorize: false,
    },
    console: {
        level: 'debug',
        handleExceptions: true,
        json: false,
        colorize: true,
    },
};

// instantiate a new Winston Logger with the settings defined above
const logger = winston.createLogger({
    transports: [
        new winston.transports.File(options.file),
        new winston.transports.Console(options.console)
    ],
    exitOnError: false, // do not exit on handled exceptions
});

// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
    write: function (message, encoding) {
        // use the 'info' log level so the output will be picked up by both transports (file and console)
        logger.info(message);
    },
};

module.exports = logger;

注意:服务器端的 Winston 完美运行

Client-Side

我想在我的客户端使用 winston angular 6 个应用程序。

示例:在我的一个组件中我有这个。

import * as logger from "winston";
.........
 this.activeRouter.params.subscribe((params) => {
      // tslint:disable-next-line:prefer-const
      let id = params['id'];
      this.moviesService.getReview(id)
        .subscribe(review => {
          console.log(review);
          this.review = review;
        });
    });

如您所见,我正在使用 console.log(review) ,我想使用 Winston 代替控制台日志。

如何在客户端使用Winston logger?我是所有这些东西的新手,我们将不胜感激。

根据这张票:https://github.com/winstonjs/winston/issues/287它几乎可以用于浏览器了?还是基本上准备好了?听起来他们最近开始支持在浏览器环境中登录。

是的,这是可能的,但是浏览器的默认传输非常有限。我建议使用 https://www.npmjs.com/package/winston-transport-browserconsole

npm install winston-transport-browserconsole -S

使用方便,支持记录json个对象:

import * as winston from "winston";
import BrowserConsole from 'winston-transport-browserconsole';

const level = "debug";
winston.configure({
    transports: [
        new BrowserConsole(
            {
                format: winston.format.simple(),
                level,
            },
        ),
    ],
});

winston.debug("DEBUG ", {a: 1, b: "two"});

是 - 它可以(技术上)在浏览器中使用。应该吗?几乎肯定不是(遗憾的是)。 Winston 是一个很棒的节点记录器。但是,强调“for node”。如果你想在客户端使用它,除了 winston 本身之外,你还需要添加一堆节点 polyfills,这相对于其他客户端记录器来说非常大。在 winston 和那些 polyfill 之间,您将显着增加工件的大小。另外,仅供参考的 webpack 5 删除了那些节点 polyfill,因此您需要手动将它们添加回来。