首页 > 解决方案 > 如何在平均堆栈应用程序中使用温斯顿记录器

问题描述

我正在努力在我的平均堆栈应用程序中使用“winston”记录器。我的目标是:我想使用两个记录器(现在)。一个用于 http 请求日志记录,它将被写入 request.log 文件,另一个将是应用程序日志记录,它将被写入 app.log 文件。我填写了每一个教程,但我无法让它工作。

我已经在我的应用程序中安装了依赖项“winston”和“morgan”,并在下面winston.js的文件中配置并加载到 app.js 中。

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

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

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

var reqLogger = winston.createLogger({
    transports: [
        new winston.transports.File(options.requestLog),
    ],
    exitOnError: false, // do not exit on handled exceptions
});

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

module.exports = appLogger;
module.exports = reqLogger;

这我加载到app.js文件中,如下所示:

var morgan = require('morgan');
var winston = require('./config/winston');
app.use(morgan('combined', { stream: winston.stream }));

因此,我可以将请求日志重定向到 request.log 和应用程序日志。我现在有两个问题:

如何在我的应用程序 *.component.ts 文件中使用 `appLogger' 实例?在互联网上的任何地方,我都看到以下代码:

var logger = require('winston'); 
logger.debug("blah blah blah");

但是当我在我的 *.component.ts 文件中使用相同的文件时,我遇到了以下错误:

TS2304: Cannot find name 'require'

请帮帮我。我们不能将“winston”记录器与打字稿文件一起使用吗?在平均堆栈应用程序中进行服务器端日志记录(ts 文件和 js 文件)的最佳方法是什么?

标签: typescriptmean-stackwinston

解决方案


推荐阅读