नोड: कंसोल के बजाय किसी फ़ाइल में लॉग इन करें


174

क्या मैं कॉन्फ़िगर कर सकता हूं console.logताकि लॉग को कंसोल में मुद्रित होने के बजाय किसी फ़ाइल पर लिखा जाए?


1
सकता है, लेकिन लंबे समय तक उत्पादन क्षुधा के लिए, यह सिर्फ एक विशिष्ट दिन के लिए लॉग खोजने के लिए मुश्किल होगा, है ना? @ क्रेकर

जवाबों:


72

अद्यतन 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);

1
Nvm, इसका मतलब है कि प्रक्रिया मुझे लगता है ... यह कैसे काम करता है? console.log(whatever);अभी भी कंसोल में जाता है, फाइल नहीं।
trusktr

12
एक हालिया बदलाव के कारण, आप stderr.pipe () को अब और कॉल नहीं कर सकते हैं - यह अब लगता है:process.__defineGetter__('stderr', function() { return fs.createWriteStream(__dirname + '/error.log', {flags:'a'}) })
damianb

15
व्यक्तिगत रूप से मैं विंस्टन के बारे में अच्छी तरह से स्पष्ट करूँगा। हमने इसे एक साल से अधिक समय तक उपयोग किया है, और आखिरकार इसे पूरी तरह से हटाने का फैसला किया है क्योंकि यह हमारे उत्पादन वातावरण में कई मुद्दों का कारण बन रहा था। लगता है कि यह परियोजना अब बहुत खराब बनी हुई है। जब तक आपके हाथ में एक समस्या सूची है। कई मुद्दों पर अन्य उपयोगकर्ताओं द्वारा सबमिट किए गए अनुरोध हैं, लेकिन प्रोजेक्ट मेंटेनर्स को इनको मर्ज करने में समय नहीं लग रहा है। विकल्पों के लिए नोड-बनियान और कैटरपिलर देखने लायक हो सकते हैं।
12 अक्टूबर को 12

यह बताता है कि अनुरक्षक उत्तरदायी नहीं हैं। मैंने सोचा था कि यह Nodejitsu लोगों द्वारा बनाए रखा गया था। हमने एक दिन में एक लाख से अधिक पृष्ठ दृश्य खींचने वाली कई साइटों पर इसका उपयोग किया है और लॉगिंग के साथ कोई समस्या नहीं है। हो सकता है कि यह लॉग इन किया जा रहा है और इसकी मात्रा के साथ क्या करना है।
रयान गिबन्स

1
ऐसा लगता है कि अप्रैल 2015 तक विंस्टन अद्यतित है और गतिविधि का एक अच्छा सौदा प्राप्त कर रहा है।
माइक ग्रेस

180

तुम भी बस डिफ़ॉल्ट सांत्वना अधिभार कर सकते हैं।

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 में लॉग करेगा।

संपादित करें: इस पृष्ठ पर क्लेमेंट द्वारा मल्टीपरमीटर संस्करण देखें


9
मैं अधिलेखित कंसोल .log को परेशान नहीं करूंगा। बस अपना स्वयं का फ़ंक्शन बनाएं जो एक विशिष्ट फ़ाइल में लॉग करता है।
एलेक्जेंडर मिल्स

इसके अलावा यह कई मापदंडों के लिए काम नहीं करता है। एग कंसोल.लॉग (पी 1, पी 2, पी 3)
user603749

10
बहुत बढ़िया जवाब! इसके अलावा, यदि आप कई कंसोल.लॉग तर्कों को कैप्चर करना चाहते हैं, तो बस 'd' के स्थान पर 'आर्ग्युमेंट्स' ऑब्जेक्ट को पकड़ो - developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
चार्ट

@AlexMills हाय, शायद आप इस पर एक उदाहरण प्रदान कर सकते हैं कि वास्तव में यह कैसे किया जाएगा?
जोनाथन

6
लेकिन मुझे हर js फ़ाइल में यह करने की आवश्यकता है, क्या इसे वैश्विक बनाना संभव है?
स्टैकडेव

60

यदि आप उत्पादन में कुछ तलाश रहे हैं तो विस्टन शायद सबसे अच्छा विकल्प है।

यदि आप बस जल्दी से देव सामान करना चाहते हैं, तो सीधे फ़ाइल में आउटपुट करें (मुझे लगता है कि यह केवल * निक्स सिस्टम के लिए काम करता है):

nohup node simple-server.js > output.log &

7
>Windows पर काम करने के साथ-साथ STDOUT को पुनर्निर्देशित करना । nohupऐसा नहीं करता।
ब्रैड

1
यह बिना nohup* nix, यानी पर खुशी के काम करता है node simple-server.js > output.log। फिर अगर आप लॉग को फॉलो करना चाहते हैं तो इसके लिखित रूप मेंtail -f output.log
nast pasty

यह काम नहीं किया 2hen मैं तर्क के लिए इस प्रक्रिया को पारित कर दिया गया था
otzap

उत्पादन में ऐसा करने का नकारात्मक पक्ष क्या है?
मार्सेलिनो

1
आपके ओएस के आधार पर btw, कि "करो-कुछ-के बारे में" बस लॉग रोटेशन हो सकता है, जो एक अच्छा समाधान है imo - abdussamad.com/archives/541-Log-rotation-in-CentOS-Linux.html
ferr

58

मैं अक्सर कंसोल .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;

32

विंस्टन लॉगिंग के लिए उपयोग किया जाने वाला एक बहुत ही लोकप्रिय एनपीएम-मॉड्यूल है।

यहाँ एक कैसे है।
अपने प्रोजेक्ट में विंस्टन स्थापित करें:

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}`);

यह सभी सफलता-लॉग और त्रुटि-लॉग को लॉग डायरेक्टरी डेट-वार के तहत एक फ़ाइल में लॉग करता है जैसा कि आप यहां देख सकते हैं।
लॉग डाइरकोट्री


लॉग कंसोल में दिखाई देते हैं। और तुरंत कोई फ़ाइल नहीं बनाई गई है !! क्या मैं कुछ भूल रहा हूँ ?
निगेलन

1
क्या आप संभवतः अपना कॉन्फिगर शेयर कर सकते हैं? या जैसा आपने सुझाव दिया था, क्या आपने उसका उपयोग किया? यदि कॉन्फ़िगरेशन ठीक है तो एक बार आयात ( winstonऔर winston-daily-rotate-file) की जाँच करें । उन्हें logsप्रोजेक्ट के रूट डायरेक्टरी में नामित फ़ोल्डर के अंदर बनाया जाना चाहिए । विलंबित उत्तर के लिए मुझे क्षमा करें।
keshavDulal

@ निगेलन आपने इसे कैसे ठीक किया? मैं उसी मुद्दे का सामना कर रहा हूं।
user2180794

@ user2180794 निगेलन की टिप्पणी के ऊपर मेरी टिप्पणी पर एक नज़र डालें। अगर आप अभी भी इसे पूरा नहीं कर सकते हैं तो हमें बताएं।
केशवदुलल

1
लकड़हारा उपयोग के शीर्ष पर इन जोड़ने के लिए मत भूलना const winston = require('winston'); const winstonRotator = require('winston-daily-rotate-file'); और const errorLog = require('../util/logger').errorlog; const successlog = require('../util/logger').successlog; जहाँ आप कुछ लॉग करना चाहते हैं।
केशवदुलल

14
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
अमीर रीमेक

इससे कंसोल.लॉग टूट जाता है?
G_V

यह टूटता नहीं है console.log। यह अपने व्यवहार को बदलता है, हालांकि आप कॉल करके पुराने व्यवहार को पुनर्स्थापित कर सकते हैं console.file()
अमीर रीवा

10

यदि यह किसी एप्लिकेशन के लिए है, तो आप लॉगिंग मॉड्यूल का उपयोग करके संभवतः बेहतर होंगे। यह आपको अधिक लचीलापन देगा। कुछ सुझाव।


3
अब आपका log4js लिंक टूट गया है। इस बारे में कैसा है? github.com/nomiddlename/log4js-node
जो हिल्डब्रांड

1
हाँ, मुझे लगता है कि परियोजना हाथ से चली गई। धन्यवाद।
मार्को

6

अभी तक उल्लेखित नहीं है एक और समाधान में 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

अधिक जानकारी के लिए, इस जिस्ट की जाँच करें ।


सही उत्तर।
नीक वोंग

6

साधारण मामलों के लिए, हम मानक आउट (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) से रीडायरेक्ट करेगा


5

ओवरराइटिंग कंसोल.लॉग जाने का रास्ता है। लेकिन इसके लिए आवश्यक मॉड्यूल में काम करने के लिए, आपको इसे निर्यात करने की भी आवश्यकता है।

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हो
r3wt

3

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)

मैं अपने npm मॉड्यूल में इसका उपयोग करने जा रहा हूं और इस कोड को आपके लिए विशेषता देता हूं। क्या यह अच्छा है?
r3wt

2

कंसोल पर नोडज के एपीआई डॉक्स से सीधे

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

1

अब आप कैटरपिलर का उपयोग कर सकते हैं जो एक स्ट्रीम आधारित लॉगिंग प्रणाली है, जिससे आप इसे लॉग इन कर सकते हैं, फिर आउटपुट को अलग-अलग ट्रांसफ़ॉर्म और स्थानों पर पाइप कर सकते हैं।

फ़ाइल में आउटपुट करना उतना ही आसान है:

var logger = new (require('./').Logger)();
logger.pipe(require('fs').createWriteStream('./debug.log'));
logger.log('your log message');

कैटरपिलर वेबसाइट पर पूरा उदाहरण



0

मैंने आउटपुट स्ट्रीम को मेरी स्ट्रीम पर स्वैप करने का विचार लिया।

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;

0

किसी भी संख्या के तर्कों को संभालने के लिए एंड्रेस रिओप्रियो पर सुधार करें

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');
};


0

मैंने अपने लिए बस विंस्टन से उदाहरण लिया और 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') {(यदि आप इसे उत्पादन में भी चाहते हैं तो) ...


क्या वाइनस्टोन कचरे का एक गुच्छा "संदेश" और लॉग स्तर की तरह नहीं जोड़ता?
G_V

@G_V तुम्हारा क्या मतलब है? winston बहुत लचीला है, आप इसे कॉन्फ़िगर कर सकते हैं ... क्या आप देख रहे हैं ... github.com/winstonjs/winston#formats ?
टेकअप बिजनेस
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.