layouts.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. const dateFormat = require('date-format');
  2. const os = require('os');
  3. const util = require('util');
  4. const path = require('path');
  5. const debug = require('debug')('log4js:layouts');
  6. const styles = {
  7. // styles
  8. bold: [1, 22],
  9. italic: [3, 23],
  10. underline: [4, 24],
  11. inverse: [7, 27],
  12. // grayscale
  13. white: [37, 39],
  14. grey: [90, 39],
  15. black: [90, 39],
  16. // colors
  17. blue: [34, 39],
  18. cyan: [36, 39],
  19. green: [32, 39],
  20. magenta: [35, 39],
  21. red: [91, 39],
  22. yellow: [33, 39]
  23. };
  24. function colorizeStart(style) {
  25. return style ? `\x1B[${styles[style][0]}m` : '';
  26. }
  27. function colorizeEnd(style) {
  28. return style ? `\x1B[${styles[style][1]}m` : '';
  29. }
  30. /**
  31. * Taken from masylum's fork (https://github.com/masylum/log4js-node)
  32. */
  33. function colorize(str, style) {
  34. return colorizeStart(style) + str + colorizeEnd(style);
  35. }
  36. function timestampLevelAndCategory(loggingEvent, colour) {
  37. return colorize(
  38. util.format(
  39. '[%s] [%s] %s - ',
  40. dateFormat.asString(loggingEvent.startTime),
  41. loggingEvent.level.toString(),
  42. loggingEvent.categoryName
  43. ),
  44. colour
  45. );
  46. }
  47. /**
  48. * BasicLayout is a simple layout for storing the logs. The logs are stored
  49. * in following format:
  50. * <pre>
  51. * [startTime] [logLevel] categoryName - message\n
  52. * </pre>
  53. *
  54. * @author Stephan Strittmatter
  55. */
  56. function basicLayout(loggingEvent) {
  57. return timestampLevelAndCategory(loggingEvent) + util.format(...loggingEvent.data);
  58. }
  59. /**
  60. * colouredLayout - taken from masylum's fork.
  61. * same as basicLayout, but with colours.
  62. */
  63. function colouredLayout(loggingEvent) {
  64. return timestampLevelAndCategory(loggingEvent, loggingEvent.level.colour) + util.format(...loggingEvent.data);
  65. }
  66. function messagePassThroughLayout(loggingEvent) {
  67. return util.format(...loggingEvent.data);
  68. }
  69. function dummyLayout(loggingEvent) {
  70. return loggingEvent.data[0];
  71. }
  72. /**
  73. * PatternLayout
  74. * Format for specifiers is %[padding].[truncation][field]{[format]}
  75. * e.g. %5.10p - left pad the log level by 5 characters, up to a max of 10
  76. * both padding and truncation can be negative.
  77. * Negative truncation = trunc from end of string
  78. * Positive truncation = trunc from start of string
  79. * Negative padding = pad right
  80. * Positive padding = pad left
  81. *
  82. * Fields can be any of:
  83. * - %r time in toLocaleTimeString format
  84. * - %p log level
  85. * - %c log category
  86. * - %h hostname
  87. * - %m log data
  88. * - %d date in constious formats
  89. * - %% %
  90. * - %n newline
  91. * - %z pid
  92. * - %f filename
  93. * - %l line number
  94. * - %o column postion
  95. * - %s call stack
  96. * - %x{<tokenname>} add dynamic tokens to your log. Tokens are specified in the tokens parameter
  97. * - %X{<tokenname>} add dynamic tokens to your log. Tokens are specified in logger context
  98. * You can use %[ and %] to define a colored block.
  99. *
  100. * Tokens are specified as simple key:value objects.
  101. * The key represents the token name whereas the value can be a string or function
  102. * which is called to extract the value to put in the log message. If token is not
  103. * found, it doesn't replace the field.
  104. *
  105. * A sample token would be: { 'pid' : function() { return process.pid; } }
  106. *
  107. * Takes a pattern string, array of tokens and returns a layout function.
  108. * @return {Function}
  109. * @param pattern
  110. * @param tokens
  111. * @param timezoneOffset
  112. *
  113. * @authors ['Stephan Strittmatter', 'Jan Schmidle']
  114. */
  115. function patternLayout(pattern, tokens) {
  116. const TTCC_CONVERSION_PATTERN = '%r %p %c - %m%n';
  117. const regex = /%(-?[0-9]+)?(\.?-?[0-9]+)?([[\]cdhmnprzxXyflos%])(\{([^}]+)\})?|([^%]+)/;
  118. pattern = pattern || TTCC_CONVERSION_PATTERN;
  119. function categoryName(loggingEvent, specifier) {
  120. let loggerName = loggingEvent.categoryName;
  121. if (specifier) {
  122. const precision = parseInt(specifier, 10);
  123. const loggerNameBits = loggerName.split('.');
  124. if (precision < loggerNameBits.length) {
  125. loggerName = loggerNameBits.slice(loggerNameBits.length - precision).join('.');
  126. }
  127. }
  128. return loggerName;
  129. }
  130. function formatAsDate(loggingEvent, specifier) {
  131. let format = dateFormat.ISO8601_FORMAT;
  132. if (specifier) {
  133. format = specifier;
  134. // Pick up special cases
  135. switch (format) {
  136. case 'ISO8601':
  137. case 'ISO8601_FORMAT':
  138. format = dateFormat.ISO8601_FORMAT;
  139. break;
  140. case 'ISO8601_WITH_TZ_OFFSET':
  141. case 'ISO8601_WITH_TZ_OFFSET_FORMAT':
  142. format = dateFormat.ISO8601_WITH_TZ_OFFSET_FORMAT;
  143. break;
  144. case 'ABSOLUTE':
  145. process.emitWarning(
  146. "Pattern %d{ABSOLUTE} is deprecated in favor of %d{ABSOLUTETIME}. " +
  147. "Please use %d{ABSOLUTETIME} instead.",
  148. "DeprecationWarning", "log4js-node-DEP0003"
  149. );
  150. debug("DEPRECATION: Pattern %d{ABSOLUTE} is deprecated and replaced by %d{ABSOLUTETIME}.");
  151. // falls through
  152. case 'ABSOLUTETIME':
  153. case 'ABSOLUTETIME_FORMAT':
  154. format = dateFormat.ABSOLUTETIME_FORMAT;
  155. break;
  156. case 'DATE':
  157. process.emitWarning(
  158. "Pattern %d{DATE} is deprecated due to the confusion it causes when used. " +
  159. "Please use %d{DATETIME} instead.",
  160. "DeprecationWarning", "log4js-node-DEP0004"
  161. );
  162. debug("DEPRECATION: Pattern %d{DATE} is deprecated and replaced by %d{DATETIME}.");
  163. // falls through
  164. case 'DATETIME':
  165. case 'DATETIME_FORMAT':
  166. format = dateFormat.DATETIME_FORMAT;
  167. break;
  168. // no default
  169. }
  170. }
  171. // Format the date
  172. return dateFormat.asString(format, loggingEvent.startTime);
  173. }
  174. function hostname() {
  175. return os.hostname().toString();
  176. }
  177. function formatMessage(loggingEvent) {
  178. return util.format(...loggingEvent.data);
  179. }
  180. function endOfLine() {
  181. return os.EOL;
  182. }
  183. function logLevel(loggingEvent) {
  184. return loggingEvent.level.toString();
  185. }
  186. function startTime(loggingEvent) {
  187. return dateFormat.asString('hh:mm:ss', loggingEvent.startTime);
  188. }
  189. function startColour(loggingEvent) {
  190. return colorizeStart(loggingEvent.level.colour);
  191. }
  192. function endColour(loggingEvent) {
  193. return colorizeEnd(loggingEvent.level.colour);
  194. }
  195. function percent() {
  196. return '%';
  197. }
  198. function pid(loggingEvent) {
  199. return loggingEvent && loggingEvent.pid ? loggingEvent.pid.toString() : process.pid.toString();
  200. }
  201. function clusterInfo() {
  202. // this used to try to return the master and worker pids,
  203. // but it would never have worked because master pid is not available to workers
  204. // leaving this here to maintain compatibility for patterns
  205. return pid();
  206. }
  207. function userDefined(loggingEvent, specifier) {
  208. if (typeof tokens[specifier] !== 'undefined') {
  209. return typeof tokens[specifier] === 'function' ? tokens[specifier](loggingEvent) : tokens[specifier];
  210. }
  211. return null;
  212. }
  213. function contextDefined(loggingEvent, specifier) {
  214. const resolver = loggingEvent.context[specifier];
  215. if (typeof resolver !== 'undefined') {
  216. return typeof resolver === 'function' ? resolver(loggingEvent) : resolver;
  217. }
  218. return null;
  219. }
  220. function fileName(loggingEvent, specifier) {
  221. let filename = loggingEvent.fileName || '';
  222. if (specifier) {
  223. const fileDepth = parseInt(specifier, 10);
  224. const fileList = filename.split(path.sep);
  225. if (fileList.length > fileDepth) {
  226. filename = fileList.slice(-fileDepth).join(path.sep);
  227. }
  228. }
  229. return filename;
  230. }
  231. function lineNumber(loggingEvent) {
  232. return loggingEvent.lineNumber ? `${loggingEvent.lineNumber}` : '';
  233. }
  234. function columnNumber(loggingEvent) {
  235. return loggingEvent.columnNumber ? `${loggingEvent.columnNumber}` : '';
  236. }
  237. function callStack(loggingEvent) {
  238. return loggingEvent.callStack || '';
  239. }
  240. /* eslint quote-props:0 */
  241. const replacers = {
  242. c: categoryName,
  243. d: formatAsDate,
  244. h: hostname,
  245. m: formatMessage,
  246. n: endOfLine,
  247. p: logLevel,
  248. r: startTime,
  249. '[': startColour,
  250. ']': endColour,
  251. y: clusterInfo,
  252. z: pid,
  253. '%': percent,
  254. x: userDefined,
  255. X: contextDefined,
  256. f: fileName,
  257. l: lineNumber,
  258. o: columnNumber,
  259. s: callStack
  260. };
  261. function replaceToken(conversionCharacter, loggingEvent, specifier) {
  262. return replacers[conversionCharacter](loggingEvent, specifier);
  263. }
  264. function truncate(truncation, toTruncate) {
  265. let len;
  266. if (truncation) {
  267. len = parseInt(truncation.substr(1), 10);
  268. // negative truncate length means truncate from end of string
  269. return len > 0 ? toTruncate.slice(0, len) : toTruncate.slice(len);
  270. }
  271. return toTruncate;
  272. }
  273. function pad(padding, toPad) {
  274. let len;
  275. if (padding) {
  276. if (padding.charAt(0) === '-') {
  277. len = parseInt(padding.substr(1), 10);
  278. // Right pad with spaces
  279. while (toPad.length < len) {
  280. toPad += ' ';
  281. }
  282. } else {
  283. len = parseInt(padding, 10);
  284. // Left pad with spaces
  285. while (toPad.length < len) {
  286. toPad = ` ${toPad}`;
  287. }
  288. }
  289. }
  290. return toPad;
  291. }
  292. function truncateAndPad(toTruncAndPad, truncation, padding) {
  293. let replacement = toTruncAndPad;
  294. replacement = truncate(truncation, replacement);
  295. replacement = pad(padding, replacement);
  296. return replacement;
  297. }
  298. return function (loggingEvent) {
  299. let formattedString = '';
  300. let result;
  301. let searchString = pattern;
  302. /* eslint no-cond-assign:0 */
  303. while ((result = regex.exec(searchString)) !== null) {
  304. // const matchedString = result[0];
  305. const padding = result[1];
  306. const truncation = result[2];
  307. const conversionCharacter = result[3];
  308. const specifier = result[5];
  309. const text = result[6];
  310. // Check if the pattern matched was just normal text
  311. if (text) {
  312. formattedString += text.toString();
  313. } else {
  314. // Create a raw replacement string based on the conversion
  315. // character and specifier
  316. const replacement = replaceToken(conversionCharacter, loggingEvent, specifier);
  317. formattedString += truncateAndPad(replacement, truncation, padding);
  318. }
  319. searchString = searchString.substr(result.index + result[0].length);
  320. }
  321. return formattedString;
  322. };
  323. }
  324. const layoutMakers = {
  325. messagePassThrough () {
  326. return messagePassThroughLayout;
  327. },
  328. basic () {
  329. return basicLayout;
  330. },
  331. colored () {
  332. return colouredLayout;
  333. },
  334. coloured () {
  335. return colouredLayout;
  336. },
  337. pattern (config) {
  338. return patternLayout(config && config.pattern, config && config.tokens);
  339. },
  340. dummy () {
  341. return dummyLayout;
  342. }
  343. };
  344. module.exports = {
  345. basicLayout,
  346. messagePassThroughLayout,
  347. patternLayout,
  348. colouredLayout,
  349. coloredLayout: colouredLayout,
  350. dummyLayout,
  351. addLayout (name, serializerGenerator) {
  352. layoutMakers[name] = serializerGenerator;
  353. },
  354. layout (name, config) {
  355. return layoutMakers[name] && layoutMakers[name](config);
  356. }
  357. };