layouts.js 9.7 KB

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