Explain use of levels in winston logger - javascript

Hey i am using this winston logger,
kindly explain use of level inside the transports, what will happen if i use logger with info while logging, do i have to use debug while i log my data.
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
level: 'debug',
json: true
}),
new (winston.transports.File)({
name: 'order_check',
filename: './logs/order_check.log',
level: 'debug'
})
]
});
logger.log("info","request body");

The level inside your transport indiciates the minimum logging level that transport will "listen out for"
From the documentation:
https://github.com/winstonjs/winston#logging-levels
Each level is given a specific integer priority. The higher the priority the more important the message is considered to be
{ error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5 }
So, in your example, your transports are configured for debug: 4
This means it will log levels
4 (debug)
3 (verbose)
2 (info)
1 (warn)
0 (error)
A good use case for this would be to set one transport (Console, for example) to debug and your other to info.
This would output all debug information to the console, but log only info to file, preventing log file clutter.

the logging level reflects the importance of the logging message
for example, debug is used for non important messages, used for debugging only
info is used for something more important
if you set the logging level to debug then the logs will show debug and info messages (and higher)
if you set the logging level to info then the logs will show only info messages (and higher) - you wont see the debug messages - this helps to avoid clutter in the logs and prevents too much info being shown in the logs in a production environment

Related

How to temporarily disable log4js logging in javascript?

There are a few third party libraries that are using log4js to output their logs. I know it sounds counter-intuitive but I would like to disable these logs temporarily to be able to investigate an issue that I have.
How do I temporarily disable log4js logs temporarily in code in javascript? Specifically nodejs.
In log4js 5.3.0 (not sure how many versions back it's the same) you can do this by turning everything off temporarily at the root logger, which affects every other logger:
log4js.getLogger().level = 'off';
A full example:
#!/bin/env node
const log4js = require('log4js');
log4js.configure({
appenders: {
out: { type: "stdout" }
},
categories: {
default: {
appenders: [ "out" ],
level: "info"
}
}
});
const rootLogger = log4js.getLogger();
const log = log4js.getLogger('foo');
log.info('this is on - turning off');
rootLogger.level = 'off';
log.info('this is off - turning back on');
rootLogger.level = 'info';
log.info('this is back on');
Which gives you:
[2019-11-13T22:00:37.541] [INFO] foo - this is on - turning off
[2019-11-13T22:00:37.544] [INFO] foo - this is back on
In the app.js file of my nodejs application I place the following code to temporarily disable log4js logs from thirdparty libraries.
const log4js = require('log4js')
log4js.configure({})
This works for disabling the logs.

I am finding trouble using log4js-protractor-appender

My log4js.js file code
'use strict';
var log4js = require('log4js');
var log4jsGen = {
getLogger: function getLogger() {
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file('./ApplicationLogs.log'), 'logs');
var logger = log4js.getLogger('logs');
return logger;
}
};
module.exports = log4jsGen;
My conf.js file(specific to appender section only)
"appenders": [{
"type": "log4js-protractor-appender",
"append": 'false',
"maxLogSize": 20480,
"backups": 3,
"category": "relative-logger"
}],
Problem:
1) IS there a way that the logs will get overwritten in each run.
2) Why log4js-protractor-appender is not working, instead log4js is working, the merit of the previous is that it resolves the promises which is passed as an argument.
Thats a great question. Yes log4js-protractor-appender is awesome. It is built specially for Protractor based environments and it places all logger command in Protractor Control flow and resolves Protractor promises before logging.
You were using it incorrectly. The appender options are not part of Protractor config options but can be integrated. The approach you have is a little old one and I have updated by blog post
These are the steps as an answer to your question-2
Step 1: Install log4js npm module
Step 2: Install log4js-protractor-appender module
Step 3: Add the logger object creation logic in protractor beforeLaunch() and assign it onto ​​browser protractor global object
'use strict';
var log4js = require('log4js');
beforeLaunch:function(){
if (fs.existsSync('./logs/ExecutionLog.log')) {
fs.unlink('./logs/ExecutionLog.log')
}
log4js.configure({
appenders: [
{ type: 'log4js-protractor-appender', category: 'protractorLog4js' },
{
type: "file",
filename: './logs/ExecutionLog.log',
category: 'protractorLog4js'
}
]
});
},
onPrepare: function() {
browser.logger = log4js.getLogger('protractorLog4js');
},
Step 4: Use logger object in your tests by accessing through browser.logger
describe('sample test', function(){
it('Sample Check', function(){
browser.get("http://www.protractortest.org/#/");
browser.logger.info("Testing Log4js");
browser.sleep(5000);
browser.logger.info('Displayed text is:', browser.getCurrentUrl());
var elm = element(by.css('.lead'))
browser.logger.info('Displayed text is:', elm.getText());
});
});
But one thing to note is - This appender is just an console appender and will not be able to write to file. The file will still contain unresolved promises
Sample Output:
[21:54:23] I/local - Starting selenium standalone server...
[21:54:23] I/launcher - Running 1 instances of WebDriver
[21:54:25] I/local - Selenium standalone server started at http://192.168.1.5:60454/wd/hub
Started
[2017-02-03 21:54:30.905] [INFO] protractorLog4js - Testing Log4js
[2017-02-03 21:54:35.991] [INFO] protractorLog4js - Displayed text is: http://www.protractortest.org/#/
[2017-02-03 21:54:36.143] [INFO] protractorLog4js - Displayed text is: Protractor is an end-to-end test framework for Angular and AngularJS applications. Protractor runs tests against your application running in a real browser, interacting with it as a user would.
.
Answer to your Question 1: How to overwrite logs each run. I added a simple logic in beforeLaunch() to delete old logs if they exist and its part of the code snippet I pasted above
I have check this issue with and followed the steps mentioned in Answer 1 and it works for me.
Earlier I was getting log output in Console only but now I am getting log in console and file also.
I corrected the file path passing and Set type: "file" in log4js configure in conf file.
Log4js in Conf file
Log appender in file
Please let me know if you face any issue again.
Thanks

Node logging and error handling

I've created Node js with express and currently I use the console.log to log message and morgan for expresss...for production use what is recommended approach to use for error handling and logging ,there is recommended modules to use?
Examples will be very useful!
I try with the following
module.exports = function () {
var logger = new winston.Logger({
levels: {
info: 1
},
transports: [
new (winston.transports.File)({
level: 'info',
filename: path.join(process.cwd(), '/logs/log.json'),
})
]
});
}
I have used winston in the past quite effectively. In the below excerpt we are creating a custom log level called info such that we can call logger.info to log messages. I believe there are numerous default levels defined on winston which are well documented.
The second part is to define a transport. In winston this is essentially a storage device for your logs. You can define multiple transports in the array including Console logging, File logging, Rotated file logging, etc... These are all well documented here. Im my example I have created a file transport where the log file is located under log/logs.json within the root of the application. Every time I now call logger.info('blah blah blah') I will see a new log entry in the file.
var winston = require('winston'),
, path = require('path')
// Log to file.
var logger = new winston.Logger({
levels: {
info: 1
},
transports: [
new (winston.transports.File)({
level: 'info',
filename: path.join(process.cwd(), '/log/logs.json'),
})
]
});
// Write to log.
logger.info("something to log");

Tests result as successful, although errors are found during Tests

I have set up my test environment as described here with QunitJS + PhantomJS + GruntJS: http://jordankasper.com/blog/2013/04/automated-javascript-tests-using-grunt-phantomjs-and-qunit/
Everything works fine, but I have the problem that, my Grunt Task finishes without errors, although errors are found. This is crucial for my build process. Due to the Test results the build either fails or succeeds. But in my case the build always succeeds. Any Ideas why grunt doesn't exit with failure when errors found?
qunit Task of the grunt file:
module.exports = {
services: {
options: {
urls: [
'http://localhost:8000/tests/services.html'
],
timeout: 20000,
force: true
}
},
gui: {
options: {
urls: [
'http://localhost:8000/tests/gui.html'
],
timeout: 20000,
force: true
}
}
};
Output:
Please consider that I cant upload more info due to confidental issues.
You are asking 'why does Grunt continue and when the tests fail?' The answer is 'because you are asking it to'.
The force option controls whether the QUnit task fails if there are failing tests. Setting it to true as you have done tells Grunt to continue even if there are failing tests. Try setting it to false, or removing it altogether as false is the default.

BusterJS freezes when a lib is included

I have the following setup:
buster.js:
var config = module.exports;
config["web-module"] = {
autoRun: true,
environment: "browser",
rootPath: ".",
libs: [
//"app/webroot/src/lib/underscore.js"
],
sources: [
],
tests: [
"buster_simpletest.js"
]
};
buster_simpletest.js:
buster.testCase("My thing", {
"states the obvious": function () {
console.log("TEST");
assert(true);
}
});
This setup runs fine and I get the expected console output:
Chrome 24.0.1312.57, Windows Server 2008 R2 / 7:
Passed: Chrome 24.0.1312.57, Windows Server 2008 R2 / 7 My thing states the obvious
[LOG] TEST
1 test case, 1 test, 1 assertion, 0 failures, 0 errors, 0 timeouts.
Finished in 0.004s
However, it doesn't as soon as I include any of the libs (I tried underscore.js, jQuery and several others.)
I don't get a single line of console output. No error, no nothing. It simply freezes there.
I also tried to disable autoRun and include a run.js which calls buster.run();, but the result was the same.
Does anyone know what's wrong here?
Thanks in advance for your help.
Edit:
Ok I tested some more and it seems to have problems with the folder depth. Here is my folder structure:
root
- buster.js
- buster_simpletest.js
- underscore.js
- a
- underscore.js
- b
- underscore.js
And here's my testing result:
libs: [
//"underscore.js" // works
//"a/underscore.js" // works
//"a/b/underscore.js" // freezes
//"a/b/xunderscore.js" // Error: "Failed loading configuration: "a/b/xunderscore.js" matched no files or resources"
]
As you can see it freezes as soon as I have depth of 2 folders. Although it is able to find the file, as I get an error if I try to include an invalid file.
Edit 2:
Seems to be a bug with windows only. The same setup works fine on our linux machine.
I guess we have to wait for proper windows support.

Categories

Resources