在 angularjs 应用程序中使用 winston.js

Using winston.js in angularjs application

我们有一个 angularjs 应用程序,我们希望将其任何错误或任何信息记录到服务器(写入文件)。许多建议都指向使用 winston.js。但我不确定如何将 winston.js 与 angularjs 应用程序一起使用。

任何 help/suggestion 都很好。

对于 AngularJS 应用程序,最好的解决方案是为默认的 $log 服务创建一个装饰器,然后包装您的服务器端记录器。

如果您决定不想使用 winston,您想要使用另一个远程记录器,或者编写您自己的记录器,则此方法将起作用。通过使用装饰器——您正在从您的代码中消除它的影响,因为在您的应用程序中您仍将使用默认的 $log 服务。

老实说,winston 看起来像是一个 Nodejs 记录器——我不确定它是否可以在浏览器中运行。

为 winston 添加值提供程序

var winston = require('winston');
app.value('winston', winston);

然后创建装饰器

logDecorator.$inject = ['$provide'];
function logDecorator($provide) {

   $provide.decorator('$log', ['$delegate', 'winston', function($delegate, winston) {

        var origLog = $delegate.log;
        var origDebug = $delegate.debug;
        var origError = $delegate.error;
        // ...

        $delegate.log = function() {
            winston.log(arguments);
            origLog.apply(null, arguments);
        }

        $delegate.debug = function() {
            winston.debug(arguments);
            origDebug.apply(null, arguments);
        }

        $delegate.error = function() {
            winston.error(arguments);
            origError.apply(null, arguments);
        }
    }]
}

app.config(logDecorator);

你可以看到这段代码的去向。您可能有一个更简洁的实现,它只是循环遍历日志级别的字符串数组来生成委托方法。

所以现在您只需像往常一样将消息记录到 $log,它们将通过管道传输到 winston。此外,还将记录任何 angular 或第 3 方模块错误。