layouts.js 12 KB

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