layouts.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. 'use strict';
  2. const dateFormat = require('date-format');
  3. const os = require('os');
  4. const util = require('util');
  5. const path = require('path');
  6. const eol = os.EOL || '\n';
  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(
  66. loggingEvent,
  67. loggingEvent.level.colour
  68. ) + util.format(...loggingEvent.data);
  69. }
  70. function messagePassThroughLayout(loggingEvent) {
  71. return util.format(...loggingEvent.data);
  72. }
  73. function dummyLayout(loggingEvent) {
  74. return loggingEvent.data[0];
  75. }
  76. /**
  77. * PatternLayout
  78. * Format for specifiers is %[padding].[truncation][field]{[format]}
  79. * e.g. %5.10p - left pad the log level by 5 characters, up to a max of 10
  80. * Fields can be any of:
  81. * - %r time in toLocaleTimeString format
  82. * - %p log level
  83. * - %c log category
  84. * - %h hostname
  85. * - %m log data
  86. * - %d date in constious formats
  87. * - %% %
  88. * - %n newline
  89. * - %z pid
  90. * - %f filename
  91. * - %l line number
  92. * - %o column postion
  93. * - %s call stack
  94. * - %x{<tokenname>} add dynamic tokens to your log. Tokens are specified in the tokens parameter
  95. * - %X{<tokenname>} add dynamic tokens to your log. Tokens are specified in logger context
  96. * You can use %[ and %] to define a colored block.
  97. *
  98. * Tokens are specified as simple key:value objects.
  99. * The key represents the token name whereas the value can be a string or function
  100. * which is called to extract the value to put in the log message. If token is not
  101. * found, it doesn't replace the field.
  102. *
  103. * A sample token would be: { 'pid' : function() { return process.pid; } }
  104. *
  105. * Takes a pattern string, array of tokens and returns a layout function.
  106. * @return {Function}
  107. * @param pattern
  108. * @param tokens
  109. * @param timezoneOffset
  110. *
  111. * @authors ['Stephan Strittmatter', 'Jan Schmidle']
  112. */
  113. function patternLayout(pattern, tokens) {
  114. const TTCC_CONVERSION_PATTERN = '%r %p %c - %m%n';
  115. const regex = /%(-?[0-9]+)?(\.?[0-9]+)?([[\]cdhmnprzxXyflos%])(\{([^}]+)\})?|([^%]+)/;
  116. pattern = pattern || TTCC_CONVERSION_PATTERN;
  117. function categoryName(loggingEvent, specifier) {
  118. let loggerName = loggingEvent.categoryName;
  119. if (specifier) {
  120. const precision = parseInt(specifier, 10);
  121. const loggerNameBits = loggerName.split('.');
  122. if (precision < loggerNameBits.length) {
  123. loggerName = loggerNameBits.slice(loggerNameBits.length - precision).join('.');
  124. }
  125. }
  126. return loggerName;
  127. }
  128. function formatAsDate(loggingEvent, specifier) {
  129. let format = dateFormat.ISO8601_FORMAT;
  130. if (specifier) {
  131. format = specifier;
  132. // Pick up special cases
  133. if (format === 'ISO8601') {
  134. format = dateFormat.ISO8601_FORMAT;
  135. } else if (format === 'ISO8601_WITH_TZ_OFFSET') {
  136. format = dateFormat.ISO8601_WITH_TZ_OFFSET_FORMAT;
  137. } else if (format === 'ABSOLUTE') {
  138. format = dateFormat.ABSOLUTETIME_FORMAT;
  139. } else if (format === 'DATE') {
  140. format = dateFormat.DATETIME_FORMAT;
  141. }
  142. }
  143. // Format the date
  144. return dateFormat.asString(format, loggingEvent.startTime);
  145. }
  146. function hostname() {
  147. return os.hostname().toString();
  148. }
  149. function formatMessage(loggingEvent) {
  150. return util.format(...loggingEvent.data);
  151. }
  152. function endOfLine() {
  153. return eol;
  154. }
  155. function logLevel(loggingEvent) {
  156. return loggingEvent.level.toString();
  157. }
  158. function startTime(loggingEvent) {
  159. return dateFormat.asString('hh:mm:ss', loggingEvent.startTime);
  160. }
  161. function startColour(loggingEvent) {
  162. return colorizeStart(loggingEvent.level.colour);
  163. }
  164. function endColour(loggingEvent) {
  165. return colorizeEnd(loggingEvent.level.colour);
  166. }
  167. function percent() {
  168. return '%';
  169. }
  170. function pid(loggingEvent) {
  171. return loggingEvent && loggingEvent.pid ? loggingEvent.pid.toString() : process.pid.toString();
  172. }
  173. function clusterInfo() {
  174. // this used to try to return the master and worker pids,
  175. // but it would never have worked because master pid is not available to workers
  176. // leaving this here to maintain compatibility for patterns
  177. return pid();
  178. }
  179. function userDefined(loggingEvent, specifier) {
  180. if (typeof tokens[specifier] !== 'undefined') {
  181. return typeof tokens[specifier] === 'function' ? tokens[specifier](loggingEvent) : tokens[specifier];
  182. }
  183. return null;
  184. }
  185. function contextDefined(loggingEvent, specifier) {
  186. const resolver = loggingEvent.context[specifier];
  187. if (typeof resolver !== 'undefined') {
  188. return typeof resolver === 'function' ? resolver(loggingEvent) : resolver;
  189. }
  190. return null;
  191. }
  192. function fileName(loggingEvent, specifier) {
  193. let filename = loggingEvent.fileName || '';
  194. if (specifier) {
  195. const fileDepth = parseInt(specifier, 10);
  196. const fileList = filename.split(path.sep);
  197. if (fileList.length > fileDepth) {
  198. filename = fileList.slice(-fileDepth).join(path.sep);
  199. }
  200. }
  201. return filename;
  202. }
  203. function lineNumber(loggingEvent) {
  204. return loggingEvent.lineNumber || '';
  205. }
  206. function columnNumber(loggingEvent) {
  207. return loggingEvent.columnNumber || '';
  208. }
  209. function callStack(loggingEvent) {
  210. return loggingEvent.callStack || '';
  211. }
  212. /* eslint quote-props:0 */
  213. const replacers = {
  214. 'c': categoryName,
  215. 'd': formatAsDate,
  216. 'h': hostname,
  217. 'm': formatMessage,
  218. 'n': endOfLine,
  219. 'p': logLevel,
  220. 'r': startTime,
  221. '[': startColour,
  222. ']': endColour,
  223. 'y': clusterInfo,
  224. 'z': pid,
  225. '%': percent,
  226. 'x': userDefined,
  227. 'X': contextDefined,
  228. 'f': fileName,
  229. 'l': lineNumber,
  230. 'o': columnNumber,
  231. 's': callStack,
  232. };
  233. function replaceToken(conversionCharacter, loggingEvent, specifier) {
  234. return replacers[conversionCharacter](loggingEvent, specifier);
  235. }
  236. function truncate(truncation, toTruncate) {
  237. let len;
  238. if (truncation) {
  239. len = parseInt(truncation.substr(1), 10);
  240. return toTruncate.substring(0, len);
  241. }
  242. return toTruncate;
  243. }
  244. function pad(padding, toPad) {
  245. let len;
  246. if (padding) {
  247. if (padding.charAt(0) === '-') {
  248. len = parseInt(padding.substr(1), 10);
  249. // Right pad with spaces
  250. while (toPad.length < len) {
  251. toPad += ' ';
  252. }
  253. } else {
  254. len = parseInt(padding, 10);
  255. // Left pad with spaces
  256. while (toPad.length < len) {
  257. toPad = ` ${toPad}`;
  258. }
  259. }
  260. }
  261. return toPad;
  262. }
  263. function truncateAndPad(toTruncAndPad, truncation, padding) {
  264. let replacement = toTruncAndPad;
  265. replacement = truncate(truncation, replacement);
  266. replacement = pad(padding, replacement);
  267. return replacement;
  268. }
  269. return function (loggingEvent) {
  270. let formattedString = '';
  271. let result;
  272. let searchString = pattern;
  273. /* eslint no-cond-assign:0 */
  274. while ((result = regex.exec(searchString)) !== null) {
  275. // const matchedString = result[0];
  276. const padding = result[1];
  277. const truncation = result[2];
  278. const conversionCharacter = result[3];
  279. const specifier = result[5];
  280. const text = result[6];
  281. // Check if the pattern matched was just normal text
  282. if (text) {
  283. formattedString += text.toString();
  284. } else {
  285. // Create a raw replacement string based on the conversion
  286. // character and specifier
  287. const replacement = replaceToken(conversionCharacter, loggingEvent, specifier);
  288. formattedString += truncateAndPad(replacement, truncation, padding);
  289. }
  290. searchString = searchString.substr(result.index + result[0].length);
  291. }
  292. return formattedString;
  293. };
  294. }
  295. const layoutMakers = {
  296. messagePassThrough: function () {
  297. return messagePassThroughLayout;
  298. },
  299. basic: function () {
  300. return basicLayout;
  301. },
  302. colored: function () {
  303. return colouredLayout;
  304. },
  305. coloured: function () {
  306. return colouredLayout;
  307. },
  308. pattern: function (config) {
  309. return patternLayout(config && config.pattern, config && config.tokens);
  310. },
  311. dummy: function () {
  312. return dummyLayout;
  313. }
  314. };
  315. module.exports = {
  316. basicLayout,
  317. messagePassThroughLayout,
  318. patternLayout,
  319. colouredLayout,
  320. coloredLayout: colouredLayout,
  321. dummyLayout,
  322. addLayout: function (name, serializerGenerator) {
  323. layoutMakers[name] = serializerGenerator;
  324. },
  325. layout: function (name, config) {
  326. return layoutMakers[name] && layoutMakers[name](config);
  327. }
  328. };