"use strict"; var path = require('path') , log4js = require('../lib/log4js'); log4js.configure( { appenders: [ { type: "file", filename: "important-things.log", maxLogSize: 10*1024*1024, // = 10Mb numBackups: 5, // keep five backup files compress: true, // compress the backups encoding: 'utf-8', mode: parseInt('0640', 8), flags: 'w+' }, { type: "dateFile", filename: "more-important-things.log", pattern: "yyyy-MM-dd-hh", compress: true }, { type: "stdout" } ] } ); var logger = log4js.getLogger('things'); logger.debug("This little thing went to market"); logger.info("This little thing stayed at home"); logger.error("This little thing had roast beef"); logger.fatal("This little thing had none"); logger.trace("and this little thing went wee, wee, wee, all the way home.");
使用rotating-file-streamnode
var path = require('path'); var fs = require('fs'); var rfs = require('rotating-file-stream'); var logDirectory = __dirname; function Wpad(num) { return (num > 9 ? "" : "0") + num; } /** * [Wgenerator 建立文件名函數] * @Author Wdd * @DateTime 2017-02-22T10:13:39+0800 * 日誌會保留一個月的:由於日誌文件名是隻使用日期,9月8號的日誌就會覆蓋8月8號的日誌 * 文件的格式是gzip * 文件名例如:22-log.gizp */ function Wgenerator(time, index) { if(! time){ return "temp-log.txt.gzip"; } return "/storage/"+ Wpad(time.getDate()) +"-log.txt.gzip"; } var accessLogStream = rfs(Wgenerator, { interval: '1d', // 週期爲1天 path: logDirectory, compress: 'gzip' , rotationTime:true }); /** * [exports description] * @Author Wdd * @DateTime 2017-02-22T10:24:06+0800 * 使用方式: * 1. 安裝rotating-file-stream * 2. 在根目錄下建立一個文件夾,例如logs。而後把access-log.js放進去 * 3. 在app.js中var mylog = require('./logs/access-log'); * 4. 在app = express(); 後添加一句 app.use(mylog); * 5. 日誌文件會自動生成在./logs/storage文件夾下面,當天的日誌會保存在暫存的./logs/temp-log.gzip裏 */ module.exports = function(req, res, next){ req._startTime = new Date(); res.once('finish', function(){ var msg = ""; //hostname msg = process.env.hostname+" "; // 時間 msg += new Date()+" "; // 請求方式 msg += req.method+" "; // 響應狀態碼 msg += res.statusCode+" "; // sessionId msg += req.headers.sessionid+" "; // 響應時長 msg += new Date() - req._startTime ; // 請求路徑 msg += " " + req.originalUrl +'\n\r\n\r'; accessLogStream.write(msg); }); next(); };