Jyo Jyo - 4 months ago 22
AngularJS Question

Using winston.js in angularjs application

We are having an angularjs application, for which we want to log any errors or any info to server(writing to file). Lots of suggestions are pointing to using winston.js. But I am not sure how to use the winston.js with the angularjs application.

Any help/suggestion would be great.


For an AngularJS application the best solution would be to create a decorator for the default $log service that would then wrap your serverside logger.

This approach will work if you decide you don't want to use winston, you want to use another remote logger, or write your own. By using the decorator -- you are removing the impact of this from your code, as within your application you will still use the default $log service.

Because to be honest, winston looks like it is a Nodejs logger -- I am not sure it will work in the browser.

Add a value provider for winston

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

Then create your decorator

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() {
            origLog.apply(null, arguments);

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

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


You can see where this code is going. You can probably have a much cleaner implimentation that just cycles through a string array array of log levels to generate the delegate methods.

So now you just log your messages to $log as usual, and they will be piped to winston. In addition, any angular or 3rd party module errors will be logged as well.