Node.js 日志记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12016474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js Logging
提问by syv
Is there any library which will help me to handle logging in my Node.Js application? All I want to do is, I want to write all logs into a File and also I need an options like rolling out the file after certain size or date.
是否有任何库可以帮助我处理 Node.Js 应用程序的日志记录?我想要做的就是,我想将所有日志写入一个文件,并且我还需要一个选项,例如在特定大小或日期之后推出文件。
I have incorporated log4js im trying to keep all the configuration details in one file and use only the methods in other application files for ease of maintenance. But it doesnt work as expected. Here is what I'm trying to do
我已经合并了 log4js,我试图将所有配置细节保存在一个文件中,并仅使用其他应用程序文件中的方法以方便维护。但它没有按预期工作。这是我想要做的
var log4js = require('log4js');
log4js.clearAppenders()
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file('test.log'), 'test');
var logger = log4js.getLogger('test');
logger.setLevel('ERROR');
var traceLogger = function (message) {
logger.trace('message');
};
var errorLogger = function (message) {
logger.trace(message);
};
exports.trace = traceLogger;
exports.error = errorLogger;
I have included this file in other files and tried
我已将此文件包含在其他文件中并尝试
log.error ("Hello Error Message");
But it is not working. Is there anything wrong in this ?
但它不起作用。这有什么问题吗?
回答by Charlie Key
Winstonis a pretty good logging library. You can write logs out to a file using it.
Winston是一个非常好的日志库。您可以使用它将日志写出到文件中。
Code would look something like:
代码看起来像:
var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({ json: false, timestamp: true }),
new winston.transports.File({ filename: __dirname + '/debug.log', json: false })
],
exceptionHandlers: [
new (winston.transports.Console)({ json: false, timestamp: true }),
new winston.transports.File({ filename: __dirname + '/exceptions.log', json: false })
],
exitOnError: false
});
module.exports = logger;
You can then use this like:
然后你可以像这样使用它:
var logger = require('./log');
logger.info('log to file');
回答by Mathew Kurian
Scribe.JS Lightweight Logger
Scribe.JS 轻量级记录器
I have looked through many loggers, and I wasn't able to find a lightweight solution - so I decided to make a simple solution that is posted on github.
我查看了许多记录器,但找不到轻量级解决方案 - 所以我决定制作一个发布在 github 上的简单解决方案。
- Saves the file which are organized by user, date, and level
- Gives you a pretty output (we all love that)
- Easy-to-use HTML interface
- 保存按用户、日期和级别组织的文件
- 给你一个漂亮的输出(我们都喜欢)
- 易于使用的 HTML 界面
I hope this helps you out.
我希望这能够帮到你。
Online Demo
在线演示
http://bluejamesbond.github.io/Scribe.js/
http://bluejamesbond.github.io/Scribe.js/
Secure Web Access to Logs
对日志的安全 Web 访问


Prints Pretty Text to Console Too!
也可以将漂亮的文本打印到控制台!


Web Access
网络访问


Github
GitHub
回答by Tho
Log4jsis one of the most popular logging library for nodejs application.
Log4js是最流行的 nodejs 应用程序日志库之一。
It supports many cool features:
它支持许多很酷的功能:
- Coloured console logging
- Replacement of node's console.log functions (optional)
- File appender, with log rolling based on file size
- SMTP, GELF, hook.io, Loggly appender
- Multiprocess appender (useful when you've got worker processes)
- A logger for connect/express servers
- Configurable log message layout/patterns
- Different log levels for different log categories (make some parts of your app log as DEBUG, others only ERRORS, etc.)
- 彩色控制台日志记录
- 替换节点的 console.log 功能(可选)
- 文件附加器,根据文件大小进行日志滚动
- SMTP、GELF、hook.io、Loggly 附加程序
- 多进程附加程序(当你有工作进程时很有用)
- 用于连接/快速服务器的记录器
- 可配置的日志消息布局/模式
- 不同日志类别的不同日志级别(将应用程序的某些部分记录为 DEBUG,其他部分仅为 ERRORS 等)
Example:
例子:
Installation:
npm install log4jsConfiguration (
./config/log4js.json):{"appenders": [ { "type": "console", "layout": { "type": "pattern", "pattern": "%m" }, "category": "app" },{ "category": "test-file-appender", "type": "file", "filename": "log_file.log", "maxLogSize": 10240, "backups": 3, "layout": { "type": "pattern", "pattern": "%d{dd/MM hh:mm} %-5p %m" } } ], "replaceConsole": true }Usage:
var log4js = require( "log4js" ); log4js.configure( "./config/log4js.json" ); var logger = log4js.getLogger( "test-file-appender" ); // log4js.getLogger("app") will return logger that prints log to the console logger.debug("Hello log4js");// store log in file
安装:
npm install log4js配置 (
./config/log4js.json):{"appenders": [ { "type": "console", "layout": { "type": "pattern", "pattern": "%m" }, "category": "app" },{ "category": "test-file-appender", "type": "file", "filename": "log_file.log", "maxLogSize": 10240, "backups": 3, "layout": { "type": "pattern", "pattern": "%d{dd/MM hh:mm} %-5p %m" } } ], "replaceConsole": true }用法:
var log4js = require( "log4js" ); log4js.configure( "./config/log4js.json" ); var logger = log4js.getLogger( "test-file-appender" ); // log4js.getLogger("app") will return logger that prints log to the console logger.debug("Hello log4js");// store log in file
回答by sam100rav
You can also use npmlog by issacs, recommended in https://npmjs.org/doc/coding-style.html.
你也可以通过 issacs 使用 npmlog,推荐在 https://npmjs.org/doc/coding-style.html。
You can find this module here https://github.com/isaacs/npmlog
你可以在这里找到这个模块 https://github.com/isaacs/npmlog
回答by Alexander Jeyaraj
The "logger.setLevel('ERROR');" is causing the problem. I do not understand why, but when I set it to anything other than "ALL", nothing gets printed in the file. I poked around a little bit and modified your code. It is working fine for me. I created two files.
“logger.setLevel('ERROR');” 导致问题。我不明白为什么,但是当我将它设置为“ALL”以外的任何内容时,文件中不会打印任何内容。我稍微浏览了一下并修改了您的代码。它对我来说很好。我创建了两个文件。
logger.js
记录器.js
var log4js = require('log4js');
log4js.clearAppenders()
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file('test.log'), 'test');
var logger = log4js.getLogger('test');
logger.setLevel('ERROR');
var getLogger = function() {
return logger;
};
exports.logger = getLogger();
logger.test.js
记录器.test.js
var logger = require('./logger.js')
var log = logger.logger;
log.error("ERROR message");
log.trace("TRACE message");
When I run "node logger.test.js", I see only "ERROR message" in test.log file. If I change the level to "TRACE" then both lines are printed on test.log.
当我运行“node logger.test.js”时,我在 test.log 文件中只看到“错误消息”。如果我将级别更改为“TRACE”,那么这两行都会打印在 test.log 上。
回答by vinesh
Winston is strong choice for most of the developers. I have been using winston for long. Recently I used winston with with papertrail which takes the application logging to next level.
Winston 是大多数开发人员的不二之选。我一直在使用 winston。最近我将 winston 与 papertrail 一起使用,它将应用程序日志记录提升到一个新的水平。
Here is a nice screenshot from their site.
这是他们网站上的一个很好的截图。
How its useful
它如何有用
you can manage logs from different systems at one place. this can be very useful when you have two backend communicating and can see logs from both at on place.
Logs are live. you can see realtime logs of your production server.
Powerful search and filter
you can create alerts to send you email if it encounters specific text in log.
您可以在一处管理来自不同系统的日志。当您有两个后端通信并且可以在原地查看两个后端的日志时,这可能非常有用。
日志是实时的。您可以查看生产服务器的实时日志。
强大的搜索和过滤功能
如果遇到日志中的特定文本,您可以创建警报以向您发送电子邮件。
and you can find more http://help.papertrailapp.com/kb/how-it-works/event-viewer/
你可以找到更多http://help.papertrailapp.com/kb/how-it-works/event-viewer/
A simple configuration using winston,winston-expressand winston-papertrailnode modules.
使用winston,winston-express和winston-papertrailnode 模块的简单配置。
import winston from 'winston';
import expressWinston from 'express-winston';
//
// Requiring `winston-papertrail` will expose
// `winston.transports.Papertrail`
//
require('winston-papertrail').Papertrail;
// create winston transport for Papertrail
var winstonPapertrail = new winston.transports.Papertrail({
host: 'logsX.papertrailapp.com',
port: XXXXX
});
app.use(expressWinston.logger({
transports: [winstonPapertrail],
meta: true, // optional: control whether you want to log the meta data about the request (default to true)
msg: "HTTP {{req.method}} {{req.url}}", // optional: customize the default logging message. E.g. "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}"
expressFormat: true, // Use the default Express/morgan request formatting. Enabling this will override any msg if true. Will only output colors with colorize set to true
colorize: true, // Color the text and status code, using the Express/morgan color palette (text: gray, status: default green, 3XX cyan, 4XX yellow, 5XX red).
ignoreRoute: function (req, res) { return false; } // optional: allows to skip some log messages based on request and/or response
}));
I hope this helps someone manage their logs !!
我希望这有助于有人管理他们的日志!!
回答by rohit kamal
A 'nodejslogger' module can be used for simple logging. It has three levels of logging (INFO, ERROR, DEBUG)
“nodejslogger”模块可用于简单的日志记录。它具有三个级别的日志记录(INFO、ERROR、DEBUG)
var logger = require('nodejslogger')
logger.init({"file":"output-file", "mode":"DIE"})
D : Debug, I : Info, E : Error
D:调试,I:信息,E:错误
logger.debug("Debug logs")
logger.info("Info logs")
logger.error("Error logs")
The module can be accessed at : https://www.npmjs.com/package/nodejslogger
该模块可以在以下位置访问:https: //www.npmjs.com/package/nodejslogger
回答by Roland Maio
Observe that errorLoggeris a wrapper around logger.trace. But the level of logger is ERRORso logger.tracewill not log its message to logger's appenders.
观察errorLogger周围的包装logger.trace。但是 logger 的级别是ERROR因此logger.trace不会将其消息记录到logger的附加程序。
The fix is to change logger.traceto logger.errorin the body of errorLogger.
解决方法是改变logger.trace到logger.error在体内errorLogger。

