我是否可以配置console.log,以便将日志写入文件,而不是打印在控制台中?
当前回答
我自己简单地从温斯顿的例子,并添加了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'){(如果你想让它也在生产环境中)…
其他回答
Winston是一个非常流行的用于日志记录的npm模块。
这里有一个操作指南。 在你的项目中安装温斯顿:
npm install winston --save
这里有一个现成的配置,我经常在我的项目中使用它作为utils下的logger.js。
/**
* 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}`);
它还将所有的成功日志和错误日志记录在logs目录下的一个文件中,如您在这里看到的那样。
我经常使用很多参数console.log()和console.error(),所以我的解决方案是:
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;
Rudy Huynh的解决方案对我来说非常有效。我添加了一点,让它吐出带有今天日期和时间的文件。
var dateNow = new Date();
var timeNow = dateNow.getHours() + '-' + dateNow.getMinutes();
var logPath = "log/" + dateNow.toDateString() + ' -' + ' Start Time - ' + timeNow + ".log"
consoleLogToFile({
logFilePath: logPath
});
它不是很优雅,但这样它将保存不同的,易于阅读的日志文件,而不是只是更新相同的“default.log”文件。
对于未来的用户。@keshavDulal答案不适用于最新版本。而且我无法找到针对最新版本3.3.3中报告的问题的适当修复。
不管怎样,在研究了一下之后,我终于把它修好了。下面是温斯顿3.3.3版本的解决方案
安装winston和winston-daily-rotate-file
npm install winston
npm install winston-daily-rotate-file
创建一个新文件utils/logger.js
const winston = require('winston');
const winstonRotator = require('winston-daily-rotate-file');
var logger = new winston.createLogger({
transports: [
new (winston.transports.DailyRotateFile)({
name: 'access-file',
level: 'info',
filename: './logs/access.log',
json: false,
datePattern: 'yyyy-MM-DD',
prepend: true,
maxFiles: 10
}),
new (winston.transports.DailyRotateFile)({
name: 'error-file',
level: 'error',
filename: './logs/error.log',
json: false,
datePattern: 'yyyy-MM-DD',
prepend: true,
maxFiles: 10
})
]
});
module.exports = {
logger
};
然后在任何你想要使用日志导入模块的文件
const logger = require('./utils/logger').logger;
像下面这样使用记录器:
logger.info('Info service started');
logger.error('Service crashed');
你可以使用nodejs的Console构造函数
const mylog = new console.Console(
fs.createWriteStream("log/logger.log"),
fs.createWriteStream("log/error.log")
);
然后你就可以像使用普通的控制台类一样使用它了,例如:
mylog.log("Ok!"); // Will be written into 'log/logger.log'
mylog.error("Bad!"); // Will be written into 'log/error.log'
推荐文章
- 有没有办法修复包锁。json lockfileVersion所以npm使用特定的格式?
- 如何使用npm全局安装一个模块?
- 如何在SQL Server Management Studio中查看查询历史
- 实时http流到HTML5视频客户端的最佳方法
- 使用node.js下载图像
- Node.js Express中的HTTP GET请求
- Node.js:将文本文件读入数组。(每一行都是数组中的一项。)
- Python中带有回溯的日志异常
- npm犯错!错误:EPERM:操作不允许,重命名
- Node Sass还不支持当前环境:Linux 64位,带false
- 我如何添加环境变量启动。VSCode中的json
- 解析错误:无法读取文件“…/tsconfig.json”.eslint
- 在Node.js中'use strict'语句是如何解释的?
- 当WebSockets可用时,为什么要使用AJAX ?
- 使用过程。TypeScript中的env