node.js中将console.log日志内容输出到文件

栏目: Node.js · 发布时间: 7年前

内容简介:node.js在运行时,有时需要将console.log的内容打印输出到文件来调试。可以用以下方法。Linux中可以在启动添加:也可以只输出错误到日志文件,>>代表追加模式。2代表错误输出:

node.js在运行时,有时需要将console.log的内容打印输出到文件来调试。可以用以下方法。

Linux中可以在启动添加:

node script-file.js > log-file.txt

也可以只输出错误到日志文件,>>代表追加模式。2代表错误输出:

node script-file.js 2>>log-file.txt

在node.js中输出:

var fs      = require('fs')
var util    = require('util')

var logPath = 'upgrade.log'
var logFile = fs.createWriteStream(logPath, { flags: 'a' })

console.log = function() {
  logFile.write(util.format.apply(null, arguments) + '\n')
  process.stdout.write(util.format.apply(null, arguments) + '\n')
}

console.error = function() {
  logFile.write(util.format.apply(null, arguments) + '\n')
  process.stderr.write(util.format.apply(null, arguments) + '\n')
}


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Uberland

Uberland

Alex Rosenblat / University of California Press / 2018-11-19 / GBP 21.00

Silicon Valley technology is transforming the way we work, and Uber is leading the charge. An American startup that promised to deliver entrepreneurship for the masses through its technology, Uber ins......一起来看看 《Uberland》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

SHA 加密
SHA 加密

SHA 加密工具