log4js2
Version:
[](https://travis-ci.org/anigenero/log4js2) [](https://codecov.io/gh/anigenero/log4js2)
408 lines • 11.3 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
const define = require("core-js/library/fn/object/define");
const log_level_1 = require("../const/log.level");
const utility_1 = require("../util/utility");
const date_formatter_1 = require("./date.formatter");
class Formatter {
/**
* @function
* @memberOf formatter
*
* @param {string} layout
*
* @return {string}
*/
static preCompile(layout) {
Formatter._getCompiledLayout(layout);
}
/**
* @function
* @memberOf formatter
*
* @param {string} layout
* @param {ILogEvent} logEvent
*
* @return {string}
*/
static format(layout, logEvent) {
return Formatter._formatLogEvent(Formatter._getCompiledLayout(layout), logEvent);
}
/**
* @function
* @memberOf formatter
*
* @param {ILogEvent} logEvent
*
* @return {string}
*/
static _formatLogger(logEvent) {
return logEvent.logger;
}
/**
* @function
* @memberOf formatter
*
* @param {ILogEvent} logEvent
* @param {Array.<string>} params
*
* @return {string}
*/
static _formatDate(logEvent, params) {
return date_formatter_1.formatDate(logEvent.date, date_formatter_1.DateTimeFormat[params[0]]);
}
/**
* @function
* @memberOf formatter
*
* @param {ILogEvent} logEvent
*
* @return {string}
*/
static _formatException(logEvent) {
let message = '';
if (logEvent.error != null) {
if (logEvent.error.stack) {
const stacks = logEvent.error.stack.split(/\n/g);
message += stacks.reduce((accumulator, value) => accumulator + `\t${value}\n`);
}
else if (logEvent.error.message != null && logEvent.error.message !== '') {
message += `\t${logEvent.error.name}: ${logEvent.error.message}\n`;
}
}
return message;
}
/**
* Formats the file (e.g. test.js) to the file
*
* @private
* @function
* @memberOf formatter
*
* @param {ILogEvent} logEvent
*/
static _formatFile(logEvent) {
if (!logEvent.file) {
Formatter._getFileDetails(logEvent);
}
return logEvent.file;
}
/**
* @function
* @memberOf formatter
*
* @param {ILogEvent} logEvent
*
* @return {string}
*/
static _formatLineNumber(logEvent) {
if (!logEvent.lineNumber) {
Formatter._getFileDetails(logEvent);
}
return `${logEvent.lineNumber}`;
}
/**
* @function
* @memberOf formatter
*
* @param {ILogEvent} logEvent
*
* @return {string}
*/
static _formatColumn(logEvent) {
if (!logEvent.column) {
Formatter._getFileDetails(logEvent);
}
return `${logEvent.column}`;
}
/**
* @function
* @memberOf formatter
*
* @param {ILogEvent} logEvent
* @param {Array.<string>} params
*
* @return {string}
*/
static _formatMapMessage(logEvent, params) {
let message = null;
if (logEvent.properties) {
message = [];
for (const key in logEvent.properties) {
if (params[0]) {
if (params[0] === key) {
message.push(logEvent.properties[key]);
}
}
else {
message.push('{' + key + ',' + logEvent.properties[key] + '}');
}
}
return '{' + message.join(',') + '}';
}
return message;
}
/**
* @function
* @memberOf formatter
*
* @param {ILogEvent} logEvent
*
* @return {string}
*/
static _formatLogMessage(logEvent) {
return logEvent.message;
}
/**
* @function
* @memberOf formatter
*
* @param {ILogEvent} logEvent
*
* @return {string}
*/
static _formatMethodName(logEvent) {
return utility_1.getFunctionName(logEvent.method);
}
/**
* @private
* @function
* @memberOf formatter
*/
static _formatLineSeparator() {
return '\n';
}
/**
* @function
* @memberOf formatter
*
* @param {ILogEvent} logEvent
*
* @return {string}
*/
static _formatLevel(logEvent) {
switch (logEvent.level) {
case log_level_1.LogLevel.FATAL:
return 'FATAL';
case log_level_1.LogLevel.ERROR:
return 'ERROR';
case log_level_1.LogLevel.WARN:
return 'WARN';
case log_level_1.LogLevel.INFO:
return 'INFO';
case log_level_1.LogLevel.DEBUG:
return 'DEBUG';
case log_level_1.LogLevel.TRACE:
default:
return 'TRACE';
}
}
/**
* @function
* @memberOf formatter
*
* @param {ILogEvent} logEvent
*
* @return {string}
*/
static _formatRelative(logEvent) {
return '' + logEvent.relative;
}
/**
* @function
* @memberOf formatter
*
* @param {ILogEvent} logEvent
*
* @return {string}
*/
static _formatSequenceNumber(logEvent) {
return '' + logEvent.sequence;
}
/**
* Get the compiled layout for the specified layout string. If the compiled layout does not
* exist, then we want to create it.
*
* @function
* @memberOf formatter
*
* @param {string} layout
*
* @return {Array.<string|function>}
*/
static _getCompiledLayout(layout) {
if (Formatter._compiledLayouts.has(layout)) {
return Formatter._compiledLayouts.get(layout);
}
return Formatter._compileLayout(layout);
}
/**
* Compiles a layout into an array. The array contains functions
*
* @function
* @memberOf formatter
*
* @param {string} layout
*
* @return {Array.<string|function>}
*/
static _compileLayout(layout) {
const formatArray = layout.match(/(%\w+({\w+}|)|.)/g)
.map((value) => Formatter._getFormatterObject(value));
// set the format array to the specified compiled layout
Formatter._compiledLayouts.set(layout, formatArray);
return formatArray;
}
/**
* @function
* @memberOf formatter
*
* @param {string} formatString
*
* @return {Object|string}
*/
static _getFormatterObject(formatString) {
const result = /%(\w+)(?:{(\w+)})*/g.exec(formatString);
if (result == null) {
return formatString;
}
else if (result.length < 3) {
return {
formatter: Formatter._getFormatterFunction(result[1]),
params: []
};
}
else {
const formatter = Formatter._getFormatterFunction(result[1]);
if (!formatter) {
return null;
}
const params = Formatter._getLayoutTagParams(result[2]);
return {
formatter,
params
};
}
}
/**
* Determines what formatter function has been configured
*
* @function
* @memberOf formatter
*
* @param {string} command
*
* @return {?string}
*/
static _getFormatterFunction(command) {
let regex;
for (const key in Formatter._formatters) {
if (Formatter._formatters.hasOwnProperty(key)) {
regex = new RegExp('^(' + key + ')$');
if (regex.exec(command)) {
return Formatter._formatters[key];
}
}
}
return null;
}
/**
* Gets the layout tag params associated with the layout tag. So, for example, '%d{yyyy-MM-dd}`
* would output an array of ['yyyy-MM-dd']
*
* @private
* @function
*
* @param {string} command
*
* @return {Array.<string>}
*/
static _getLayoutTagParams(command) {
return (command) ? command.split(',') : [];
}
/**
* Handles formatting the log event using the specified formatter array
*
* @private
* @function
*
* @param {Array.<function|string>} formatter
* @param {ILogEvent} logEvent
*
* @return {string}
*/
static _formatLogEvent(formatter, logEvent) {
let response;
let message = '';
const count = formatter.length;
for (let i = 0; i < count; i++) {
if (formatter[i] !== null) {
if (formatter[i] instanceof Object) {
response = formatter[i].formatter(logEvent, formatter[i].params);
if (response != null) {
message += response;
}
}
else {
message += formatter[i];
}
}
}
return message.trim();
}
/**
*
* @private
* @function
* @memberOf formatter
*
* @param {ILogEvent} logEvent
*/
static _getFileDetails(logEvent) {
if (logEvent.logErrorStack) {
const parts = logEvent.logErrorStack.stack.split(/\n/g);
let file = parts[3];
file = file.replace(/at (.*\(|)(file|http|https|)(:|)(\/|)*/, '');
file = file.replace(')', '');
file = file.replace((typeof location !== 'undefined') ? location.host : '', '').trim();
const fileParts = file.split(/:/g);
logEvent.column = fileParts.pop();
logEvent.lineNumber = fileParts.pop();
if (typeof define !== 'undefined') {
const path = require('path');
let appDir = path.dirname(require.main.filename);
if (!fileParts[0].startsWith(appDir)) {
appDir = '';
}
logEvent.filename = fileParts.join(':').replace(appDir, '').replace(/^([\\\/])/, '');
}
else {
logEvent.filename = fileParts.join(':');
}
}
else {
logEvent.column = '?';
logEvent.filename = 'anonymous';
logEvent.lineNumber = '?';
}
logEvent.file = logEvent.filename;
}
}
Formatter._formatters = {
'c|logger': Formatter._formatLogger,
'd|date': Formatter._formatDate,
'ex|exception|throwable': Formatter._formatException,
'F|file': Formatter._formatFile,
'K|map|MAP': Formatter._formatMapMessage,
'L|line': Formatter._formatLineNumber,
'column': Formatter._formatColumn,
'm|msg|message': Formatter._formatLogMessage,
'M|method': Formatter._formatMethodName,
'n': Formatter._formatLineSeparator,
'p|level': Formatter._formatLevel,
'r|relative': Formatter._formatRelative,
'sn|sequenceNumber': Formatter._formatSequenceNumber
};
/** @type {Map} */
Formatter._compiledLayouts = new Map();
exports.Formatter = Formatter;
//# sourceMappingURL=formatter.js.map