Node.js console.log() in txt file - javascript

I have another question (last question). At the moment i am working on a Node.js project and in this I have many console.log() functions. This has worked okay so far but I also want everything that's written to the console to also be written in a log-file. Can someone please help me?
For example:
Console.log('The value of array position [5] is '+ array[5]);
In my real code its a bit more but this should give you an idea.
Thank you hopefully.

Just run the script in your terminal like this...
node script-file.js > log-file.txt
This tells the shell to write the standard output of the command node script-file.js to your log file instead of the default, which is printing it to the console.
This is called redirection and its very powerful. Say you wanted to write all errors to a separate file...
node script-file.js >log-file.txt 2>error-file.txt
Now all console.log are written to log-file.txt and all console.error are written to error-file.txt

I would use a library instead of re-inventing the wheel. I looked for a log4j-type library on npm, and it came up with https://github.com/nomiddlename/log4js-node
if you want to log to the console and to a file:
var log4js = require('log4js');
log4js.configure({
appenders: [
{ type: 'console' },
{ type: 'file', filename: 'logs/cheese.log', category: 'cheese' }
]
});
now your code can create a new logger with
var logger = log4js.getLogger('cheese');
and use the logger in your code
logger.warn('Cheese is quite smelly.');
logger.info('Cheese is Gouda.');
logger.debug('Cheese is not a food.');

const fs = require('fs');
const myConsole = new console.Console(fs.createWriteStream('./output.txt'));
myConsole.log('hello world');
This will create an output file with all the output which can been triggered through console.log('hello world') inside the console.
This is the easiest way to convert the console.log() output into a text file.`

You could try overriding the built in console.log to do something different.
var originalLog = console.log;
console.log = function(str){
originalLog(str);
// Your extra code
}
However, this places the originalLog into the main scope, so you should try wrapping it in a function. This is called a closure, and you can read more about them here.
(function(){
var originalLog = console.log;
console.log = function(str){
originalLog(str);
// Your extra code
})();
To write files, see this stackoverflow question, and to override console.log even better than the way I showed, see this. Combining these two answers will get you the best possible solution.

Just write your own log function:
function log(message) {
console.log(message);
fs.writeFileSync(...);
}
Then replace all your existing calls to console.log() with log().

#activedecay's answer seems the way to go. However, as of april 30th 2018, I have had trouble with that specific model (node crashed due to the structure of the object passed on to .configure, which seems not to work in the latest version). In spite of that, I've managed to work around an updated solution thanks to nodejs debugging messages...
const myLoggers = require('log4js');
myLoggers.configure({
appenders: { mylogger: { type:"file", filename: "path_to_file/filename" } },
categories: { default: { appenders:["mylogger"], level:"ALL" } }
});
const logger = myLoggers.getLogger("default");
Now if you want to log to said file, you can do it just like activedecay showed you:
logger.warn('Cheese is quite smelly.');
logger.info('Cheese is Gouda.');
logger.debug('Cheese is not a food.');
This however, will not log anything to the console, and since I haven't figured out how to implement multiple appenders in one logger, you can still implement the good old console.log();
PD: I know that this is a somewhat old thread, and that OP's particular problem was already solved, but since I came here for the same purpose, I may as well leave my experience so as to help anyone visiting this thread in the future

Here is simple solution for file logging
#grdon/logger
const logger = require('#grdon/logger')({
defaultLogDirectory : __dirname + "/logs",
})
// ...
logger(someParams, 'logfile.txt')
logger(anotherParams, 'anotherLogFile.log')

Related

How to update string in console instead of repeat it [duplicate]

My node.js application has a lot of console logs, which are important for me to see (it's quite a big app so runs for a long time and I need to know that things are still progressing) but I'm ending up with thousands of lines of console logs.
Is it somehow possible to do a console.update that erases/replaces a console line rather than creating a new line?
Try playing with process.stdout methods instead on console:
process.stdout.write("Hello, World");
process.stdout.clearLine(0);
process.stdout.cursorTo(0);
process.stdout.write("\n"); // end the line
TypeScript: clearLine() takes -1, 0, or 1 as a direction parameter with the following meanings:
-1: to the left from cursor.
0: the entire line.
1 - to the right from cursor
Following #michelek's answer, you can use a function somewhat like this:
function printProgress(progress){
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(progress + '%');
}
Sure, you can do this using a module I helped create: fknsrs/jetty
Install via
npm install jetty
Here's a usage example
// Yeah, Jetty!
var Jetty = require("jetty");
// Create a new Jetty object. This is a through stream with some additional
// methods on it. Additionally, connect it to process.stdout
var jetty = new Jetty(process.stdout);
// Clear the screen
jetty.clear();
// write something
jetty.text("hello world");
jetty.moveTo([0,0]);
jetty.text("hello panda");
Jetty is not super useful when used on it's own. It is much more effective when you build some abstraction on top of it to make your jetty calls less verbose.
Just use \r to terminate your line:
process.stdout.write('text\r');
Here's a simple example (wall clock):
setInterval(() => process.stdout.write(`clock: ${new Date()}\r`), 1000);
To write a partial line.
process.stdout.write('text');
process.stdout.write('more');
process.stdout.write('\n'); // end the line
If the volume of output is the real issue then you'll probably to rethink your logging. You could use a logging system that allows selective runtime logging to narrow your output to what you need.
// The sections we want to log and the minimum level
var LOG_LEVEL = 4;
var LOG_SECTIONS = ['section1', 'section2', 'section3'];
function logit(msg, section, level) {
if (LOG_SECTIONS.includes(section) && LOG_LEVEL >= level) {
console.log(section + ':' + msg);
}
}
logit('message 1', 'section1', 4); // will log
logit('message 2', 'section2', 4); // will log
logit('message 3', 'section3', 2); // wont log, below log level
logit('message 4', 'section4', 4); // wont log, not in a log section
if you see stdout exceptions like TypeError: process.stdout.clearLine is not a function in Debug Console window of Visual Studio Code (or Webstorm), run the app as external terminal application instead of internal console. The reason is that Debug Console window is not TTY (process.stdout.isTTY is false). Therefore update your launch configuration in launch.json with "console": "externalTerminal" option.
We can use log-update
const logUpdate = require('log-update');
logUpdate('this will be gone');
logUpdate('this will stay');
Among others, the answer by #michelek does the trick. However, when you start using this, you may run into Exception trouble when output gets redirected to a file or you are in a debugger or running in a linux screen-session, etc. You may see messages such as process.stdout.clearLine is not a function.
Therefore, at least add a test to check that the output is a 'TTY' and is able to do such things as 'clearLine()' and 'cursorTo()':
if (process.stdout.isTTY) {
process.stdout.write("Hello, World");
process.stdout.clearLine(0);
process.stdout.cursorTo(0);
process.stdout.write("\n"); // end the line
}

Alternative to eval() in node script

I am working on a script that runs during our build process in Jenkins right before npm install. My issue is that I need to download a JavaScript file from an external resource and read a variable from it.
unzipper.on('extract', () => {
const content = fs.readFileSync(`${outputDir}/js/en.js`, 'utf8');
eval(content); // Less smellier alternative?
if (obj) {
const str = JSON.stringify(obj);
fs.writeFileSync(`${outputDir}/public/data.json`, str);
} else {
throw 'Variable `obj` not found';
}
});
I know that "eval is evil", but any suggested alternatives I've found online don't seem to work.
I have tried different variations of new Function(obj)(), but Node seems to exit the script after (the if-case never runs).
Ideas?
Since node.js provides the API to talk to the V8 runner directly, it might be a good idea to use it. Basically, it's the API used by node's require under the hood.
Assuming the js file in question contains the variable obj we're interested in, we do the following:
read the code from the file
append ; obj to the code to make sure it's the last expression it evaluates
pass the code to V8 for evaluation
grab the return value (which is our obj):
const fs = require('fs'),
vm = require('vm');
const code = fs.readFileSync('path-to-js-file', 'utf8');
const obj = vm.runInNewContext(code + ';obj');
This answer is heavily based on #georg's comments, but since it helped me I'll provide it as an alternative answer.
Explanation in the comments.
let content = fs.readFileSync(`${outputDir}/js/en.js`, 'utf8');
content += '; module.exports=obj'; // Export "obj" variable
fs.writeFileSync(`${outputDir}/temp`, content); // Create a temporary file
const obj = require(`${outputDir}/temp`); // Import the variable from the temporary file
fs.unlinkSync(`${outputDir}/temp`); // Remove the temporary file

getText is not a function error - Protractor (javascript)

I have node.js installed and protractor installed. I have experience with selenium-webdriver but Protractor is driving me nuts!!! I am also not that familiar with javascript.
This is what my code looks like:
describe('My app', function() {
var result = element(by.id('result-name'));
var enterBtn = element(by.id('enter'));
var clearFieldBtn = element(by.id('clear-field');
it('should bring up components on load', function() {
browser.get(`http://localhost:${process.env.PORT}`);
browser.wait(until.titleContains('Sample App'), 500);
browser.wait(until.presenceOf(browser.element(by.id('my-test-app'))), 500);
expect(enterBtn).isPresent;
});
it('result should equal username', function () {
browser.get(`http://localhost:${process.env.PORT}`);
expect(clearFieldBtn).isPresent;
expect(result.getText()).toEqual('John Smith'); //both tests pass without this line of code
});
});
The last line "expect(result.getText()).toEqual('John Smith');" throws me an error. I get:
expect(...).toEqual is not a function
Any help would be much appreciated. I have spent a couple of hours trying to find a solution and trying different things.
I also wanted to implement the isPresent function how it's done in the api docs which is like this: expect($('.item').isPresent()).toBeTruthy();
I tried to do:
expect(clearFieldBtn).isPresent().toBeTruthy();
But I get that isPresent is not a function...
The expect above that line seems poor. It should read
expect(clearFieldBtn.isPresent()).toBeTruthy();
not sure if that is causing the weird error on the line below...just thought I would throw it out there. All your protractor APIs need be be called within the expect because isPresent is not a attribute of expect
Have you tried these lines:
clearFieldBtn.isPresent().then(function(bln) {
expect(bln).toBe(true);
});
result.getText().then(function(tmpText) {
expect(tmpText).toBe('John Smith');
});
If you still get an error on result.getText(), please check the presence of the result object.

Async.forEach iterator data formatting issue

I am having an issue with the Mongoose fixture loader and I am not sure what is wrong.
When I load my data according to docs such as:
var data = { User: [{name: 'Alex'}, {name: 'Bob'}] };
It does not load. Exploring the code I see that in this file there is an async.forEach iterator which doesn't seem to get triggered. Creating a simple file to test I still cannot get this to work as it should. Evidently the console should print 'User' but it does not. Can someone shed some light on what the issue might be? Note that while I have phrased my question about the async, ultimately I am trying to get the mongoose loader to work so I need to stay within their code structure.
var async = require('async');
var data = { User: [{name: 'Alex'}, {name: 'Bob'}] };
var iterator = function(modelName, next){
// not working
console.log(modelName);
next();
};
async.forEach(data, iterator, function() { });
The pow-mongoose-fixtures module in the NPM repository contains a bug (see bug report).
Your code contains the same bug:
async.forEach(data, ...)
forEach() operates on arrays, but data is an object. In case of the module, it was fixed by using Object.keys() to get an array of keys. You could use it too:
async.forEach(Object.keys(data), ...);
To get mongoose-fixtures working, install the GitHub version:
npm install git://github.com/powmedia/mongoose-fixtures.git
There's a couple of changed you need to make to your code as well:
var fixtures = require('mongoose-fixtures'); // renamed from 'pow-mongoose-fixtures'
var client = mongoose.connect(...);
...
fixtures.load(data, client); // need to pass the client object

Javascript: console logging

I use console.log in my JS files to trace the application.
The problem: logs are in production environment.
How can I remove lines like console.log from code?
P.S. Please do not advice text solutions like find + xargs + grep -v.
For my significant projects, I have my own logging function that internally uses console.log(), but there are no console.log() calls in my code except for the one place in this function. I can then enable or disable logging by changing one variable.
My function is actually a little more involved than this with options to put the output into places other than just the console, but conceptually, it looks like this:
// change this variable to false to globally turn off all logging
var myLoggingEnabled = true;
function myLog() {
if (myLoggingEnabled) {
if (window.console && console.log) {
console.log.apply(this, arguments);
}
}
}
You can then use code like this to log:
myLog(foo);
FYI, for deployed code compactness and performance optimization, I also have a minimization step that removes all calls to myLog() from my code. This is an optimization that I've chosen to take advantage of. Perhaps you could share why you wouldn't also consider this type of optimization.
Well, you can disable them with
console.log=function(){}
But the lines will be there unsless you delete them manually.
If you use Grunt you can add a task so as to remove/comment the console.log statements.
Therefore the console.log are no longer called.
https://www.npmjs.org/package/grunt-remove-logging-calls
Yeah, I had a similar situation, I posted about it here. http://bhavinsurela.com/naive-way-of-overriding-console-log/
This is the gist of the code.
var domainNames =["fiddle.jshell.net"]; // we replace this by our production domain.
var logger = {
force:false,
original:null,
log:function(obj)
{
var hostName = window.location.hostname;
if(domainNames.indexOf(hostName) > -1)
{
if(window.myLogger.force === true)
{
window.myLogger.original.apply(this,arguments);
}
}else {
window.myLogger.original.apply(this,arguments);
}
},
forceLogging:function(force){
window.myLogger.force = force;
},
original:function(){
return window.myLogger.original;
},
init:function(){
window.myLogger.original = console.log;
console.log = window.myLogger.log;
}
}
window.myLogger = logger;
console.log("this should print like normal");
window.myLogger.init();
console.log("this should not print");
window.myLogger.forceLogging(true);
console.log("this should print now");

Categories