You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cryptpad/lib/log.js

107 lines
2.8 KiB
JavaScript

6 years ago
/*jshint esversion: 6 */
var Store = require("./storage/file");
6 years ago
var Logger = module.exports;
/* Every line in the log should contain:
* timestamp
* public key of initiator
* the action
* the event's tag
*/
var messageTemplate = function (type, time, tag, info) {
return JSON.stringify([type.toUpperCase(), time, tag, info]);
};
var noop = function () {};
6 years ago
var write = function (ctx, content) {
if (!ctx.store) { return; }
ctx.store.log(ctx.channelName, content, noop);
6 years ago
};
// various degrees of logging
const logLevels = Logger.levels = ['silly', 'verbose', 'debug', 'feedback', 'info', 'warn', 'error'];
6 years ago
var handlers = {};
['silly', 'debug', 'verbose', 'feedback', 'info'].forEach(function (level) {
handlers[level] = function (ctx, content) { console.log(content); };
});
['warn', 'error'].forEach(function (level) {
5 years ago
handlers[level] = function (ctx, content) { console.error(content); };
});
6 years ago
var noop = function () {};
6 years ago
var createLogType = function (ctx, type) {
if (logLevels.indexOf(type) < logLevels.indexOf(ctx.logLevel)) {
return noop;
}
6 years ago
return function (tag, info) {
if (ctx.shutdown) {
throw new Error("Logger has been shut down!");
}
6 years ago
var time = new Date().toISOString();
var content;
try {
content = messageTemplate(type, time, tag, info);
} catch (e) {
return;
}
if (ctx.logToStdout && typeof(handlers[type]) === 'function') {
handlers[type](ctx, content);
6 years ago
}
write(ctx, content);
};
};
var createMethods = function (ctx) {
var log = {};
logLevels.forEach(function (type) {
log[type] = createLogType(ctx, type);
});
return log;
};
6 years ago
Logger.create = function (config, cb) {
if (typeof(config.logLevel) !== 'string') {
config.logLevel = 'info';
6 years ago
}
var date = new Date();
var launchTime = ('' + date.getUTCFullYear()).slice(-2) + date.toISOString();
var ctx = {
channelName: launchTime,
logFeedback: Boolean(config.logFeedback),
logLevel: config.logLevel,
logToStdout: config.logToStdout,
};
if (!config.logPath) {
console.log("No logPath configured. Logging to file disabled");
var logger = createMethods(ctx);
logger.shutdown = noop;
return void cb(Object.freeze(logger));
}
6 years ago
Store.create({
filePath: config.logPath,
archivePath: config.archivePath,
}, function (err, store) {
if (err) {
throw err;
}
ctx.store = store;
var logger = createMethods(ctx);
logger.shutdown = function () {
delete ctx.store;
ctx.shutdown = true;
store.shutdown();
};
cb(Object.freeze(logger));
6 years ago
});
};