layouts.js 13 KB

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