log.js 2.08 KB
var fs = require('fs');
var moment = require('moment');
var helper = require('../lib/helper');
var _ = require('lodash');

/*
 * parameters:
 *   dirname: string
 *   rotation: interger (ms)
 */
function log(dirname, opts) {
    opts = opts || {};
    this.dirname = dirname;
    this.rotation = opts.rotation || 15 * 60 * 1000;
    this.maxsize = opts.maxsize || 20000;
    this.filename = opts.filename || '[log]YYYY-MM-DDTHH-mm-ss[_${count}.txt]';
    this.currentsize = 0;
    this.timestamp = 0;
    this.foldername = 'log/';
    helper.mkdirIfNotExist(`${this.dirname}/${this.foldername}`);
};

/*
 * parameters:
 *   data: any
 */
log.prototype.append = function (data) {
    data = this.formatData(data);
    this.currentsize = this.currentsize + helper.getLengthOfContent(data);
    fs.appendFile(this.getDir(), data, function (err) {});
};

/*
 * parameters:
 *   none
 */
log.prototype.getDir = function () {
    var time = moment(Math.floor((+moment()) / this.rotation) * this.rotation);
    this.resetCurrentSize(time.unix());
    var count = this.getCount();
    time = time.format(this.filename.replace("${count}", count));
    return `${this.dirname}${this.foldername}${time}`;
};

/*
 * parameters:
 *   time_unix: string
 */
log.prototype.resetCurrentSize = function (time_unix) {
    if (time_unix > this.timestamp) {
        this.currentsize = 0
        this.timestamp = time_unix;
    }
};

/*
 * parameters:
 *   none
 */
log.prototype.getCount = function () {
    var count = Math.floor((this.currentsize / this.maxsize) + 1);
    return ((count * 1e-5).toFixed(5)).split('.')[1];
};

/*
 * parameters:
 *   data: any
 */
log.prototype.formatData = function (data) {
    var date = moment().toISOString().trim();
    var timestamp = moment().unix();
    data = this._formatObject(data).trim();
    return `${date} ${timestamp} ${data}\r\n`;
};

/*
 * parameters:
 *   data: any
 */
log.prototype._formatObject = function (data) {
    if (_.isObject(data)) {
        return JSON.stringify(data);
    }
    if (_.isNumber(data)) {
        return toString(data);
    }
    return data;
};

module.exports = log;