How to make logging asynchronous

611 views
Skip to first unread message

Vasavi Kaza

unread,
Apr 4, 2016, 10:55:50 PM4/4/16
to nodejs
Hi,

Created a custom winston logger. It works fine logging to console and file. However, all my log messages are printed once at the beginning of the code instead of wating step by step to execute. Especially, these print the log statements farther in the code than the failed statement that ends the program. How do I fix this.  Could not find how to resolve this. New to nodejs and in learning process. May be a silly question but please help. 

Thanks,
Vasavi Kaza

Paul Spaulding

unread,
Apr 6, 2016, 8:59:33 AM4/6/16
to nodejs
Tough to say without seeing code, but it sounds like this sort of thing:

logger.info('msg1'); // this gets logged 1st
someAsyncFunc
(function(){ // callback
l

});
logger
.info('msg2');  //this gets logged 2nd

Peter Ferak

unread,
Apr 6, 2016, 8:59:33 AM4/6/16
to nodejs
Depends mostly on how you write your javascript code. Can you give some samples?

One way to solve it is to use the synchronous methods, which are provided by most node modules (instead of their async counterparts using callbacks). 

Good luck.

Ezequiel Carrizo

unread,
Apr 6, 2016, 1:47:48 PM4/6/16
to nodejs
as @Peter Ferak pointed, it depends on your code, you should read the basics about JavaScript and Asynchronous vs synchronous execution.


A working example so you can see how it really works.

console.log('calling some async function');

setTimeout
(function(){
    console
.log('Async function 1 finished');
},4);


console.log('calling some async function 2');

setTimeout
(function(){
    console
.log('Async function 2 finished');
},2);


See it working: https://jsfiddle.net/2x5oLx51/ 
Reply all
Reply to author
Forward
0 new messages