NodeJS web 实践 - logging
nodejs的module非常多,可用于log的组建也很多,现在介绍一下对log4js的实践。
https://github.com/nomiddlename/log4js-node
假设已经安装了nodejs,express, npm
(1) create a new express project
? ~/tmp express -e catchy create : catchy create : catchy/package.json create : catchy/app.js create : catchy/public create : catchy/public/images create : catchy/public/javascripts create : catchy/routes create : catchy/routes/index.js create : catchy/routes/user.js create : catchy/public/stylesheets create : catchy/public/stylesheets/style.css create : catchy/views create : catchy/views/index.ejs install dependencies: $ cd catchy && npm install run the app: $ node app
(2) install log4js
? catchy npm install log4js -save
? catchy npm install
(2) write an utility
? catchy touch logUtil.js
/* LogUtil.js */ /** * Logger definition */ var log4js = require(‘log4js‘); var levels = ["INFO","DEBUG","ERROR"] var level = "INFO"; var events = require(‘events‘) var dynamicLogging = new events.EventEmitter() var u = require("util") dynamicLogging.setMaxListeners(50)log4js.configure(‘logs/log4js.json‘, { reloadSecs : 180 } )exports.getLogger = function(name) {var logger = log4js.getLogger(name);logger.setLevel(level);
dynamicLogging.on("levelChange",function(newLevel){ console.log(u.format("logger %s -- > Level : %s ", name, newLevel))
logger.setLevel(newLevel) })
return logger;};
var hasLevel = function(levelName){ var i for(i=0; i<levels.length;i++){ if (levelName === levels[i]) { return true } } return false}var getLevel = function(){ return level}var resetLevel = function(){ dynamicLogging.emit("levelChange", getLevel())}var setLevel = function(_level) {level = _level;};exports.log4js = log4js;exports.setLevel = setLevelexports.hasLevel = hasLevelexports.getLevel = getLevelexports.resetLevel = resetLevel(3) make configurations and log dir
mkdir logs touch logs/log4js.json
log4js.json{ "appenders": [ { "type": "console" }, { "type": "file", "filename": "logs/default.log", "maxLogSize": 204800, "backups": 5 } ] }(4) get loggervar logUtil = require("./logUtil") var logger = logUtil.getLogger("xx") logger.info("foo") logger.debug("foo") logger.error("what?")
note:将log4js做了一点优化: 利用nodejs的事件机制,动态的调整loglevel,无需重启应用。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。