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

use*_*622 4 javascript node.js express winston angular

我正在创建完整的平均堆栈应用程序

NodeJs、Angular 6、ExpressJs 和 MongoDB

我已经成功地创建了一个服务器并且它工作得很好,而不是console.log在我的应用程序中记录错误时使用我决定在Winston Logger这里使用的是我现在所拥有的

服务器端

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;
Run Code Online (Sandbox Code Playgroud)

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

客户端

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

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

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;
        });
    });
Run Code Online (Sandbox Code Playgroud)

如您所见,我正在使用console.log(review),而不是控制台日志,我想使用Winston.

如何Winston logger在客户端使用?我是所有这些东西的新手,任何帮助都会受到赞赏。

lga*_*nts 8

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


Mar*_*ano 7

是的,这是可能的,但是浏览器的默认传输非常有限。我建议使用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"});
Run Code Online (Sandbox Code Playgroud)