क्या मैं कॉन्फ़िगर कर सकता हूं console.log
ताकि लॉग को कंसोल में मुद्रित होने के बजाय किसी फ़ाइल पर लिखा जाए?
क्या मैं कॉन्फ़िगर कर सकता हूं console.log
ताकि लॉग को कंसोल में मुद्रित होने के बजाय किसी फ़ाइल पर लिखा जाए?
जवाबों:
अद्यतन 2013 - यह नोड v0.2 और v0.4 के आसपास लिखा गया था; लॉगिंग के आसपास अब बहुत बेहतर उपयोग हैं। मैं विंस्टन को बहुत सलाह देता हूं
2013 के अंत में अपडेट करें - हम अभी भी विंस्टन का उपयोग करते हैं, लेकिन अब कस्टम ऑब्जेक्ट्स के लॉगिंग और फ़ॉर्मेटिंग के चारों ओर कार्यक्षमता को लपेटने के लिए लकड़हारा लाइब्रेरी के साथ। यहाँ हमारे logger.js https://gist.github.com/rtgibbons/7354879 का एक नमूना है
इस के रूप में सरल होना चाहिए।
var access = fs.createWriteStream(dir + '/node.access.log', { flags: 'a' })
, error = fs.createWriteStream(dir + '/node.error.log', { flags: 'a' });
// redirect stdout / stderr
proc.stdout.pipe(access);
proc.stderr.pipe(error);
console.log(whatever);
अभी भी कंसोल में जाता है, फाइल नहीं।
process.__defineGetter__('stderr', function() { return fs.createWriteStream(__dirname + '/error.log', {flags:'a'}) })
तुम भी बस डिफ़ॉल्ट सांत्वना अधिभार कर सकते हैं।
var fs = require('fs');
var util = require('util');
var log_file = fs.createWriteStream(__dirname + '/debug.log', {flags : 'w'});
var log_stdout = process.stdout;
console.log = function(d) { //
log_file.write(util.format(d) + '\n');
log_stdout.write(util.format(d) + '\n');
};
उपरोक्त उदाहरण डीबग.लॉग और stdout में लॉग करेगा।
संपादित करें: इस पृष्ठ पर क्लेमेंट द्वारा मल्टीपरमीटर संस्करण देखें ।
यदि आप उत्पादन में कुछ तलाश रहे हैं तो विस्टन शायद सबसे अच्छा विकल्प है।
यदि आप बस जल्दी से देव सामान करना चाहते हैं, तो सीधे फ़ाइल में आउटपुट करें (मुझे लगता है कि यह केवल * निक्स सिस्टम के लिए काम करता है):
nohup node simple-server.js > output.log &
>
Windows पर काम करने के साथ-साथ STDOUT को पुनर्निर्देशित करना । nohup
ऐसा नहीं करता।
nohup
* nix, यानी पर खुशी के काम करता है node simple-server.js > output.log
। फिर अगर आप लॉग को फॉलो करना चाहते हैं तो इसके लिखित रूप मेंtail -f output.log
मैं अक्सर कंसोल .log () और कंसोल.रोर () के लिए कई तर्कों का उपयोग करता हूं, इसलिए मेरा समाधान होगा:
var fs = require('fs');
var util = require('util');
var logFile = fs.createWriteStream('log.txt', { flags: 'a' });
// Or 'w' to truncate the file every time the process starts.
var logStdout = process.stdout;
console.log = function () {
logFile.write(util.format.apply(null, arguments) + '\n');
logStdout.write(util.format.apply(null, arguments) + '\n');
}
console.error = console.log;
विंस्टन लॉगिंग के लिए उपयोग किया जाने वाला एक बहुत ही लोकप्रिय एनपीएम-मॉड्यूल है।
यहाँ एक कैसे है।
अपने प्रोजेक्ट में विंस्टन स्थापित करें:
npm install winston --save
यहाँ एक विन्यास तैयार है जिसका उपयोग मैं अपनी परियोजनाओं में अक्सर उपयोग करता हूँ।
/**
* Configurations of logger.
*/
const winston = require('winston');
const winstonRotator = require('winston-daily-rotate-file');
const consoleConfig = [
new winston.transports.Console({
'colorize': true
})
];
const createLogger = new winston.Logger({
'transports': consoleConfig
});
const successLogger = createLogger;
successLogger.add(winstonRotator, {
'name': 'access-file',
'level': 'info',
'filename': './logs/access.log',
'json': false,
'datePattern': 'yyyy-MM-dd-',
'prepend': true
});
const errorLogger = createLogger;
errorLogger.add(winstonRotator, {
'name': 'error-file',
'level': 'error',
'filename': './logs/error.log',
'json': false,
'datePattern': 'yyyy-MM-dd-',
'prepend': true
});
module.exports = {
'successlog': successLogger,
'errorlog': errorLogger
};
और फिर बस आयात करें जहाँ भी आवश्यक हो:
const errorLog = require('../util/logger').errorlog;
const successlog = require('../util/logger').successlog;
तो आप के रूप में सफलता लॉग इन कर सकते हैं:
successlog.info(`Success Message and variables: ${variable}`);
और त्रुटियों के रूप में:
errorlog.error(`Error Message : ${error}`);
यह सभी सफलता-लॉग और त्रुटि-लॉग को लॉग डायरेक्टरी डेट-वार के तहत एक फ़ाइल में लॉग करता है जैसा कि आप यहां देख सकते हैं।
winston
और winston-daily-rotate-file
) की जाँच करें । उन्हें logs
प्रोजेक्ट के रूट डायरेक्टरी में नामित फ़ोल्डर के अंदर बनाया जाना चाहिए । विलंबित उत्तर के लिए मुझे क्षमा करें।
const winston = require('winston');
const winstonRotator = require('winston-daily-rotate-file');
और const errorLog = require('../util/logger').errorlog;
const successlog = require('../util/logger').successlog;
जहाँ आप कुछ लॉग करना चाहते हैं।
const fs = require("fs");
const {keys} = Object;
const {Console} = console;
/**
* Redirect console to a file. Call without path or with false-y
* value to restore original behavior.
* @param {string} [path]
*/
function file(path) {
const con = path ? new Console(fs.createWriteStream(path)) : null;
keys(Console.prototype).forEach(key => {
if (path) {
this[key] = (...args) => con[key](...args);
} else {
delete this[key];
}
});
};
// patch global console object and export
module.exports = console.file = file;
इसका उपयोग करने के लिए, ऐसा कुछ करें:
require("./console-file");
console.file("/path/to.log");
console.log("write to file!");
console.error("also write to file!");
console.file(); // go back to writing to stdout
Console.prototype
कुंजियों पर लूपिंग के बजाय , केवल स्पष्ट रूप से सेट करें this.error
।
console.log
। यह अपने व्यवहार को बदलता है, हालांकि आप कॉल करके पुराने व्यवहार को पुनर्स्थापित कर सकते हैं console.file()
।
यदि यह किसी एप्लिकेशन के लिए है, तो आप लॉगिंग मॉड्यूल का उपयोग करके संभवतः बेहतर होंगे। यह आपको अधिक लचीलापन देगा। कुछ सुझाव।
अभी तक उल्लेखित नहीं है एक और समाधान में Writable
धाराओं को हुक करके process.stdout
और process.stderr
। इस तरह आपको उन सभी कंसोल कार्यों को ओवरराइड करने की आवश्यकता नहीं होती है जो आउटपुट को stdout और stderr पर ले जाते हैं। यह कार्यान्वयन किसी लॉग फ़ाइल में stdout और stderr दोनों को पुनर्निर्देशित करता है:
var log_file = require('fs').createWriteStream(__dirname + '/log.txt', {flags : 'w'})
function hook_stream(stream, callback) {
var old_write = stream.write
stream.write = (function(write) {
return function(string, encoding, fd) {
write.apply(stream, arguments) // comments this line if you don't want output in the console
callback(string, encoding, fd)
}
})(stream.write)
return function() {
stream.write = old_write
}
}
console.log('a')
console.error('b')
var unhook_stdout = hook_stream(process.stdout, function(string, encoding, fd) {
log_file.write(string, encoding)
})
var unhook_stderr = hook_stream(process.stderr, function(string, encoding, fd) {
log_file.write(string, encoding)
})
console.log('c')
console.error('d')
unhook_stdout()
unhook_stderr()
console.log('e')
console.error('f')
इसे कंसोल में प्रिंट करना चाहिए
a
b
c
d
e
f
और लॉग फ़ाइल में:
c
d
अधिक जानकारी के लिए, इस जिस्ट की जाँच करें ।
साधारण मामलों के लिए, हम मानक आउट (STDOUT) और मानक त्रुटि (STDERR) को सीधे '>' और '2> और 1' द्वारा दाखिल करने की धाराओं को पुनर्निर्देशित कर सकते हैं ।
उदाहरण:
// test.js
(function() {
// Below outputs are sent to Standard Out (STDOUT) stream
console.log("Hello Log");
console.info("Hello Info");
// Below outputs are sent to Standard Error (STDERR) stream
console.error("Hello Error");
console.warn("Hello Warning");
})();
नोड test.js> test.log 2> & 1
पोसिक्स मानक के अनुसार, पॉजिटिव पूर्णांक फ़ाइल डिस्क्रिप्टर (0, 1, 2) द्वारा 'इनपुट', 'आउटपुट' और 'एरर' स्ट्रीम की पहचान की जाती है । यानी, स्टडिन 0 है, स्टडआउट 1 है, और स्टेडर 2 है।
'2> & 1' 2 (stderr) से 1 (stdout) तक रीडायरेक्ट करेगा
'>' फ़ाइल (test.log) पर 1 (stdout) से रीडायरेक्ट करेगा
ओवरराइटिंग कंसोल.लॉग जाने का रास्ता है। लेकिन इसके लिए आवश्यक मॉड्यूल में काम करने के लिए, आपको इसे निर्यात करने की भी आवश्यकता है।
module.exports = console;
लॉग फ़ाइल, घूमना और सामान लिखने की परेशानी से खुद को बचाने के लिए, आप एक साधारण लकड़हारा मॉड्यूल का उपयोग करने पर विचार कर सकते हैं जैसे विंस्टन:
// Include the logger module
var winston = require('winston');
// Set up log file. (you can also define size, rotation etc.)
winston.add(winston.transports.File, { filename: 'somefile.log' });
// Overwrite some of the build-in console functions
console.error = winston.error;
console.log = winston.info;
console.info = winston.info;
console.debug = winston.debug;
console.warn = winston.warn;
module.exports = console;
global
ऑब्जेक्ट पर कंसोल गुण को अधिलेखित कर सकते हैं । क्यों करते module.exports
हो
METHOD STDOUT और STDERR
यह दृष्टिकोण आपकी सहायता कर सकता है (मैं अपनी परियोजनाओं में कुछ इसी तरह का उपयोग करता हूं) और कंसोल सहित सभी तरीकों के लिए काम करता हूं। कंसोल, सांत्वना, कंसोल.हेयर, कंसोल.इन
यह विधि फ़ाइल में stdout और stderr में लिखे गए बाइट्स को लिखें। कंसोल बदलने से बेहतर है। कंसोल, सांत्वना। सांत्वना।
var fs= require("fs")
var os= require("os")
var HOME= os.homedir()
var stdout_r = fs.createWriteStream(HOME + '/node.stdout.log', { flags: 'a' })
var stderr_r = fs.createWriteStream(HOME + '/node.stderr.log', { flags: 'a' })
var attachToLog= function(std, std_new){
var originalwrite= std.write
std.write= function(data,enc){
try{
var d= data
if(!Buffer.isBuffer(d))
d= Buffer.from(data, (typeof enc === 'string') ? enc : "utf8")
std_new.write.apply(std_new, d)
}catch(e){}
return originalwrite.apply(std, arguments)
}
}
attachToLog(process.stdout, stdout_r)
attachToLog(process.stderr, stderr_r)
// recommended catch error on stdout_r and stderr_r
// stdout_r.on("error", yourfunction)
// stderr_r.on("error", yourfunction)
कंसोल पर नोडज के एपीआई डॉक्स से सीधे
const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
// custom simple logger
const logger = new Console(output, errorOutput);
// use it like console
const count = 5;
logger.log('count: %d', count);
// in stdout.log: count 5
अब आप कैटरपिलर का उपयोग कर सकते हैं जो एक स्ट्रीम आधारित लॉगिंग प्रणाली है, जिससे आप इसे लॉग इन कर सकते हैं, फिर आउटपुट को अलग-अलग ट्रांसफ़ॉर्म और स्थानों पर पाइप कर सकते हैं।
फ़ाइल में आउटपुट करना उतना ही आसान है:
var logger = new (require('./').Logger)();
logger.pipe(require('fs').createWriteStream('./debug.log'));
logger.log('your log message');
कैटरपिलर वेबसाइट पर पूरा उदाहरण
आप इस npm मॉड्यूल पर भी नज़र डाल सकते हैं: https://www.npmjs.com/package/noogger
सरल और सीधे आगे ...
मैंने आउटपुट स्ट्रीम को मेरी स्ट्रीम पर स्वैप करने का विचार लिया।
const LogLater = require ('./loglater.js');
var logfile=new LogLater( 'log'+( new Date().toISOString().replace(/[^a-zA-Z0-9]/g,'-') )+'.txt' );
var PassThrough = require('stream').PassThrough;
var myout= new PassThrough();
var wasout=console._stdout;
myout.on('data',(data)=>{logfile.dateline("\r\n"+data);wasout.write(data);});
console._stdout=myout;
var myerr= new PassThrough();
var waserr=console._stderr;
myerr.on('data',(data)=>{logfile.dateline("\r\n"+data);waserr.write(data);});
console._stderr=myerr;
loglater.js:
const fs = require('fs');
function LogLater(filename, noduplicates, interval) {
this.filename = filename || "loglater.txt";
this.arr = [];
this.timeout = false;
this.interval = interval || 1000;
this.noduplicates = noduplicates || true;
this.onsavetimeout_bind = this.onsavetimeout.bind(this);
this.lasttext = "";
process.on('exit',()=>{ if(this.timeout)clearTimeout(this.timeout);this.timeout=false; this.save(); })
}
LogLater.prototype = {
_log: function _log(text) {
this.arr.push(text);
if (!this.timeout) this.timeout = setTimeout(this.onsavetimeout_bind, this.interval);
},
text: function log(text, loglastline) {
if (this.noduplicates) {
if (this.lasttext === text) return;
this.lastline = text;
}
this._log(text);
},
line: function log(text, loglastline) {
if (this.noduplicates) {
if (this.lasttext === text) return;
this.lastline = text;
}
this._log(text + '\r\n');
},
dateline: function dateline(text) {
if (this.noduplicates) {
if (this.lasttext === text) return;
this.lastline = text;
}
this._log(((new Date()).toISOString()) + '\t' + text + '\r\n');
},
onsavetimeout: function onsavetimeout() {
this.timeout = false;
this.save();
},
save: function save() { fs.appendFile(this.filename, this.arr.splice(0, this.arr.length).join(''), function(err) { if (err) console.log(err.stack) }); }
}
module.exports = LogLater;
किसी भी संख्या के तर्कों को संभालने के लिए एंड्रेस रिओप्रियो पर सुधार करें
var fs = require('fs');
var util = require('util');
var log_file = fs.createWriteStream(__dirname + '/debug.log', {flags : 'w'});
var log_stdout = process.stdout;
console.log = function(...args) {
var output = args.join(' ');
log_file.write(util.format(output) + '\r\n');
log_stdout.write(util.format(output) + '\r\n');
};
मैं सिर्फ यह करने के लिए एक पैक का निर्माण करता हूं, आशा है कि आप इसे पसंद करेंगे;) https://www.npmjs.com/package/writelog
मैंने अपने लिए बस विंस्टन से उदाहरण लिया और log(...)
विधि जोड़ी (क्योंकि विंस्टन ने इसे नाम दिया info(..)
:
Console.js:
"use strict"
// Include the logger module
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
//
// - Write to all logs with level `info` and below to `combined.log`
// - Write all logs error (and below) to `error.log`.
//
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
//
// If we're not in production then log to the `console` with the format:
// `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
//
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
// Add log command
logger.log=logger.info;
module.exports = logger;
तो बस अपने कोड में उपयोग करें:
const console = require('Console')
अब आप बस अपनी फ़ाइल में सामान्य लॉग फ़ंक्शंस का उपयोग कर सकते हैं और यह एक फ़ाइल बनाएगा और इसे आपके कंसोल (डिबगिंग / डेवलपमेंट) में लॉग इन करेगा। क्योंकि if (process.env.NODE_ENV !== 'production') {
(यदि आप इसे उत्पादन में भी चाहते हैं तो) ...