Permalink
Browse files

use log4js

  • Loading branch information...
1 parent a3e2e16 commit 1f171369bd179298f5388bbaf73f091990f4905b @alsotang alsotang committed Dec 7, 2015
Showing with 44 additions and 82 deletions.
  1. +6 −6 app.js
  2. +11 −56 common/logger.js
  3. +2 −1 common/mail.js
  4. +4 −3 common/push.js
  5. +2 −1 common/redis.js
  6. 0 logs/.gitkeep
  7. +12 −10 middlewares/mongoose_log.js
  8. +2 −1 middlewares/proxy.js
  9. +2 −2 middlewares/request_log.js
  10. +2 −2 models/index.js
  11. +1 −0 package.json
View
@@ -52,7 +52,7 @@ if (config.mini_assets) {
try {
assets = require('./assets.json');
} catch (e) {
- console.log('You must execute `make build` before start app when mini_assets is true.');
+ logger.info('You must execute `make build` before start app when mini_assets is true.');
@JacksonTian
JacksonTian Dec 7, 2015 Member

这种不应该到info里。

throw e;
}
}
@@ -163,17 +163,17 @@ if (config.debug) {
app.use(errorhandler());
} else {
app.use(function (err, req, res, next) {
- console.error('server 500 error:', err);
+ logger.error(err);
return res.status(500).send('500 status');
});
}
if (!module.parent) {
app.listen(config.port, function () {
- logger.log('NodeClub listening on port', config.port);
- logger.log('God bless love....');
- logger.log('You can debug your app with http://' + config.hostname + ':' + config.port);
- logger.log('');
+ logger.info('NodeClub listening on port', config.port);
@JacksonTian
JacksonTian Dec 7, 2015 Member

这种也不应该。

+ logger.info('God bless love....');
+ logger.info('You can debug your app with http://' + config.hostname + ':' + config.port);
+ logger.info('');
});
}
View
@@ -1,62 +1,17 @@
-var fs = require('fs');
var config = require('../config');
-if (!fs.existsSync("./log")) {
- fs.mkdirSync("./log");
-}
+var env = process.env.NODE_ENV || "development"
-exports.log = function () {
- writeLog('', 'info', arguments);
-};
-exports.info = function () {
- writeLog(' ', 'info', arguments);
-};
-
-exports.debug = function () {
- writeLog(" ", 'debug', arguments);
-};
-
-exports.warn = function () {
- writeLog(" ", 'warn', arguments);
-};
-
-exports.error = function () {
- writeLog(" ", 'error', arguments);
-};
-
-var env = process.env.NODE_ENV || "development";
-var consolePrint = config.debug && env !== 'test';
-var writeLog = function (prefix, logType, args) {
- var filePrint = logType !== 'debug';
-
- if (!filePrint && !consolePrint) {
- return;
- }
-
- var infos = Array.prototype.slice.call(args);
- var logStr = infos.join(" ");
-
- switch (logType) {
- case "debug":
- logStr = logStr.gray;
- break;
- case 'warn':
- logStr = logStr.yellow;
- break;
- case 'error':
- logStr = logStr.red;
- break;
- }
-
- var line = prefix + logStr;
-
- if (filePrint) {
- fs.appendFile('./log/' + env + '.log', line + "\n");
- }
- if (consolePrint) {
- console.log(line);
- }
-};
+var log4js = require('log4js');
+log4js.configure({
+ appenders: [
+ { type: 'console' },
+ { type: 'file', filename: 'logs/cheese.log', category: 'cheese' }
+ ]
+});
+var logger = log4js.getLogger('cheese');
+logger.setLevel(config.debug && env !== 'test' ? 'DEBUG' : 'ERROR')
+module.exports = logger;
View
@@ -2,6 +2,7 @@ var mailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var config = require('../config');
var util = require('util');
+var logger = require('./logger');
var transporter = mailer.createTransport(smtpTransport(config.mail_opts));
var SITE_ROOT_URL = 'http://' + config.host;
@@ -17,7 +18,7 @@ var sendMail = function (data) {
transporter.sendMail(data, function (err) {
if (err) {
// 写为日志
- console.log(err);
+ logger.error(err);
}
});
};
View
@@ -4,6 +4,7 @@ var JPush = require("jpush-sdk");
var eventproxy = require('eventproxy');
var config = require('../config');
var client = null;
+var logger = require('./logger')
if (config.jpush && config.jpush.masterSecret !== 'YourSecretKeyyyyyyyyyyyyy') {
client = JPush.buildClient(config.jpush);
@@ -47,10 +48,10 @@ exports.send = function (type, author_id, master_id, topic_id) {
.send(function (err, res) {
@JacksonTian
JacksonTian Dec 7, 2015 Member

这种是否debug都应该把err用logger处理。

if (config.debug) {
if (err) {
- console.log(err.message);
+ logger.error(err.message);
} else {
- console.log('Sendno: ' + res.sendno);
- console.log('Msg_id: ' + res.msg_id);
+ logger.info('Sendno: ' + res.sendno);
+ logger.info('Msg_id: ' + res.msg_id);
}
}
});
View
@@ -1,5 +1,6 @@
var config = require('../config');
var Redis = require('ioredis');
+var logger = require('./logger')
var client = new Redis({
port: config.redis_port,
@@ -9,7 +10,7 @@ var client = new Redis({
client.on('error', function (err) {
if (err) {
- console.error('connect to redis error, check your redis config', err);
+ logger.error('connect to redis error, check your redis config', err);
@JacksonTian
JacksonTian Dec 7, 2015 Member

这种估计有错。

@alsotang
alsotang Dec 7, 2015 Member

这种没问题的

process.exit(1);
}
})
View
No changes.
@@ -1,16 +1,18 @@
var mongoose = require('mongoose');
var logger = require('../common/logger');
+var config = require('../config');
-var traceMQuery = function (method, info, query) {
- return function (err, result, millis) {
- var infos = [];
- infos.push(query._collection.collection.name + "." + method.blue);
- infos.push(JSON.stringify(info));
- infos.push((millis + 'ms').green);
+if (config.debug) {
+ var traceMQuery = function (method, info, query) {
+ return function (err, result, millis) {
+ var infos = [];
@JacksonTian
JacksonTian Dec 7, 2015 Member

err都没处理

+ infos.push(query._collection.collection.name + "." + method.blue);
+ infos.push(JSON.stringify(info));
+ infos.push((millis + 'ms').green);
- // var duration = (new Date()) - t;
- logger.debug("MONGO".magenta, infos.join(' '));
+ logger.debug("MONGO".magenta, infos.join(' '));
+ };
};
-};
-mongoose.Mongoose.prototype.mquery.setGlobalTraceFunction(traceMQuery);
+ mongoose.Mongoose.prototype.mquery.setGlobalTraceFunction(traceMQuery);
+}
@@ -1,5 +1,6 @@
var urllib = require('url');
var request = require('request');
+var logger = require('../common/logger')
var ALLOW_HOSTNAME = [
@@ -24,7 +25,7 @@ exports.proxy = function (req, res, next) {
res.set(response.headers);
})
.on('error', function (err) {
- console.error(err);
+ logger.error(err);
})
.pipe(res);
};
@@ -8,12 +8,12 @@ module.exports = function (req, res, next) {
}
var t = new Date();
- logger.log('\n\nStarted', t.toISOString(), req.method, req.url, req.ip);
+ logger.info('\n\nStarted', t.toISOString(), req.method, req.url, req.ip);
res.on('finish', function () {
var duration = ((new Date()) - t);
- logger.log('Completed', res.statusCode, ('(' + duration + 'ms)').green);
+ logger.info('Completed', res.statusCode, ('(' + duration + 'ms)').green);
});
next();
View
@@ -1,11 +1,12 @@
var mongoose = require('mongoose');
var config = require('../config');
+var logger = require('../common/logger')
mongoose.connect(config.db, {
server: {poolSize: 20}
}, function (err) {
if (err) {
- console.error('connect to %s error: ', config.db, err.message);
+ logger.error('connect to %s error: ', config.db, err.message);
@JacksonTian
JacksonTian Dec 7, 2015 Member

这种信息应该放进err.message里,而不是这样打印

@alsotang
alsotang Dec 7, 2015 Member

append 在原来的 err.message 后面?

process.exit(1);
}
});
@@ -22,4 +23,3 @@ exports.Topic = mongoose.model('Topic');
exports.Reply = mongoose.model('Reply');
exports.TopicCollect = mongoose.model('TopicCollect');
exports.Message = mongoose.model('Message');
-
View
@@ -31,6 +31,7 @@
"loader": "2.0.0",
"loader-builder": "1.2.1",
"lodash": "3.10.1",
+ "log4js": "^0.6.29",
"markdown-it": "5.0.2",
"memory-cache": "0.1.4",
"method-override": "2.3.5",

2 comments on commit 1f17136

@JacksonTian
Member

估计你没体会过马哥@dead_horse 写的mini-logger的好。

@alsotang
Member

照着你的部分意见进行了修改

Please sign in to comment.