Skip to content
Advertisement

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

I am creating full mean stack app with

NodeJs , Angular 6 , ExpressJs and MongoDB

I have managed to create a server and its working perfectly, instead of using console.log when logging errors in my app I have decided to use Winston Logger here is what I have now

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;

Note: Winston in server side works perfectly

Client-Side

I want to use winston in my client side angular 6 app .

Example: in one of my components i have this.

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;
        });
    });

As you can see I am using console.log(review) , Instead of console log I would like to use Winston .

How to use Winston logger in client-side ? am newbie to all this stuff any help will be apreciated.

Advertisement

Answer

Yeah it is possible, however default transport for browser is very limited. I recommend to use https://www.npmjs.com/package/winston-transport-browserconsole

npm install winston-transport-browserconsole -S

It is easy to use and supports logging json objects:

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"});
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement