Logging

In a clear way, logging is just a fancy word to define a process of writing down everything you do.

There are several kinds of logging. You may log every operation of an application, log only when errors occur, or log critical operations done by a user, especially if you want to have control of who’s doing what for audit purposes.

Applications can log at a code level for debugging or at a user level for audits and forbidden access register.

Every operating system have routines or services running on the background with the task of taking notes of everything that is happening. This way a SysAdmin can detect security breaches, malfunctions etc

Logging important thing to perform debugging, without logging it becomes very difficult.

You may say like with exception/error it self tell what is the issue in that case why should we need logging, but how would you know what was the root cause of the exception.

winston logging package with protractor

winston library is most used package for logging with node.js, so we would be exploring winston logging module here, Winston provides simple interface and extensible logging-transporter.

install the winston package using npm.


										npm install --save winston 			
										
logging-winston-protractor

Log levels in Winston with protractor :

Logging levels in winston conform to the severity ordering specified by RFC5424: severity of all levels is assumed to be numerically ascending from most important to least important.

Each level is given a specific integer priority. The higher the priority the more important the message is considered to be, and the lower the corresponding integer priority. For example, from 0 to 7 is highest to lowest.

When you set the level as particular level, the logger will capture all that particular logs and above its level logs (I mean more severe than it)

For example : if you set error as log level, then logger will capture error, crit, alert, emerg messages as well.

  • emerg: 0 - This is a show stopper, it will halt the program
  • alert: 1 - it is not a show stopper, so proceeding further may cause issue.
  • crit: 2 - logs critical messages and it may hurt the a particular module
  • error: 3 - logs error messages, if you are expecting something but the system gave same other values
  • warning: 4 - This logs warning messages, these are something like soft error messages and it will not cause much issue with code
  • notice: 5 - this to showcase notice messages to user with protractor
  • info: 6 - Logs all the informational messages in Protractor
  • debug: 7 - Logs the messages for debugging purpose, these are useful while debugging

Setting the level for your logging message can be accomplished in one of two ways. You can pass a string representing the logging level to the log() method or use the level specified methods defined on every winston Logger.

SetUp winston logger

winston provides a default level of logging, but most of the time we want to configure out own logger like what levels to capture, where to push the logs (console or to file)

Steps to setup winston custom logger :

  • Create a file called customlogger.ts in folder, if you are doing this for framework then you should create a folder called logger inside the top most folder
  • Create class inside the customlogger file and name it as CustomLogger
  • 
    export class CutomLogger{			
    


  • Create a static variable called logger (you can crate non-static variable as well) with createLogger as assignment
  • 
    static logger = createLogger({			
    


  • Set the log level and format inside the variable, basically this variable has a function on assignment side
  • 
    level: 'info',
    format: format.simple(),			
    


  • Set where you want to push the log messages, whether to file or to Console or to Both using transports
  • 
    // - Write to all logs with level `info` and above to `combined.log` 
    new transports.File({ filename: 'error.log', level: 'error'}),
    // - Write all logs error (and above) to Console/terminal
    new transports.Console()			
    


Compete code of Custom logger

import {createLogger, format, transports} from 'winston'
const { combine, timestamp, label, prettyPrint } = format;

export class CutomLogger{
    static logger = createLogger({
        level: 'info',
        format: format.simple(),
        transports: [
		
        // - Write to all logs with level `info` and above to `combined.log` 
        new transports.File({ filename: 'combined.log'}),
				// - Write all logs error (and above) to Console/terminal
        new transports.Console()
		
        ]
    });
}
			


Javascript to select dropdown option

Test block for winston Logging in protractor

We have out setUp of winston package in last topic, now I will try to use it along with my protractor script with typescript.

There is no much set up here, you just need to call the variable from the CustomLogger and, use the log or respective level method.

If you are using log() method then you should specify the log level, but if you are using loglevel method then you just need pass message.


import { browser, element, by, ElementFinder, ProtractorBrowser, protractor} from 'protractor'
import {} from "../specs/loge"
import { CutomLogger } from './t';

describe('Protractor Typescript Demo', function() {
	browser.ignoreSynchronization = true; // for non-angular websites
	browser.manage().window().maximize()
	it('Mouse Operations', function() {
		// set implicit time to 30 seconds
		browser.manage().timeouts().implicitlyWait(30000);
		
		browser.get("http://google.com")

		// using general logger
		CutomLogger.logger.log('info', "1 *** infomational");
		CutomLogger.logger.log('warn', "2 *** warning");
		CutomLogger.logger.log('error', "3 *** erroe");

		// using respective loglevel methods
		CutomLogger.logger.info("4 *** informational");
		CutomLogger.logger.warn("5 *** warning");
		CutomLogger.logger.error("6 *** error");
	});
});			


Output of he winston simple logging format simple-logging-winston-protractor

Logging in Protractor using Winston

Json format Logging

In last example, we have used simple logging but sometimes we may need to log it into different format like JSON.

As you are aware that JSON file is platform independent and easy to parse, based on the JSON files we can also form HTML formatted files.

Complete code for JSON format Logger, please don't change the anything in testcase.


import {createLogger, format, transports} from 'winston'
const { combine, timestamp, label, prettyPrint } = format;

export class CutomLogger{
    static logger = createLogger({
        level: 'info',
        format: format.json(),
       
        transports: [
        new transports.File({ filename: 'combined.log'}),
        new transports.Console()
        ]
    });
}			


json-logger-winston-protractor

Format the logging on winston with Protractor

We have seen what should be the file type like simple text or json file formats, but sometimes we may want to set the locations for the items like where timestamp should come, where levels should come, where the log message should come.

We can set the format of the logging using myFormat


										const myFormat = printf(info => {
										  return `${info.timestamp} ${info.level}: ${info.message}`;
										});			
										


${info.timestamp} - Time stamp
${info.level} - level of the logs
${info.message} - log message from the user

In below example I am using simple & JSON logging with winston


import {createLogger, format, transports} from 'winston'
const { combine, timestamp, label, prettyPrint, printf } = format;

export class CutomLogger{
    public static myFormat = printf(info => {
        return `${info.timestamp} ${info.level}: ${info.message}`;
      });

    static logger = createLogger({
        level: 'info',
        format: combine(
            label({ label: 'right meow!' }),
            timestamp(),
            CutomLogger.myFormat
          ),
       
        transports: [
        new transports.File({ filename: 'combined.log'}),
        new transports.Console()
        ]
    });
}		


logging-myformat-winston-protractor

Protractor Interview Questions

 
Join My Facebook Group
Join Group
 

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
Copyright © CherCher Tech