layouts.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. 'use strict';
  2. const dateFormat = require('date-format');
  3. const os = require('os');
  4. const util = require('util');
  5. const eol = os.EOL || '\n';
  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, timezoneOffset) {
  37. return colorize(
  38. util.format(
  39. '[%s] [%s] %s - '
  40. , dateFormat.asString(loggingEvent.startTime, timezoneOffset)
  41. , loggingEvent.level
  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, timezoneOffset) {
  57. return timestampLevelAndCategory(
  58. loggingEvent,
  59. undefined,
  60. timezoneOffset
  61. ) + util.format(...loggingEvent.data);
  62. }
  63. /**
  64. * colouredLayout - taken from masylum's fork.
  65. * same as basicLayout, but with colours.
  66. */
  67. function colouredLayout(loggingEvent, timezoneOffset) {
  68. return timestampLevelAndCategory(
  69. loggingEvent,
  70. loggingEvent.level.colour,
  71. timezoneOffset
  72. ) + util.format(...loggingEvent.data);
  73. }
  74. function messagePassThroughLayout(loggingEvent) {
  75. return util.format(...loggingEvent.data);
  76. }
  77. function dummyLayout(loggingEvent) {
  78. return loggingEvent.data[0];
  79. }
  80. /**
  81. * PatternLayout
  82. * Format for specifiers is %[padding].[truncation][field]{[format]}
  83. * e.g. %5.10p - left pad the log level by 5 characters, up to a max of 10
  84. * Fields can be any of:
  85. * - %r time in toLocaleTimeString format
  86. * - %p log level
  87. * - %c log category
  88. * - %h hostname
  89. * - %m log data
  90. * - %d date in constious formats
  91. * - %% %
  92. * - %n newline
  93. * - %z pid
  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, timezoneOffset) {
  114. const TTCC_CONVERSION_PATTERN = '%r %p %c - %m%n';
  115. const regex = /%(-?[0-9]+)?(\.?[0-9]+)?([[\]cdhmnprzxXy%])(\{([^}]+)\})?|([^%]+)/;
  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, timezoneOffset);
  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, timezoneOffset);
  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. /* eslint quote-props:0 */
  193. const replacers = {
  194. 'c': categoryName,
  195. 'd': formatAsDate,
  196. 'h': hostname,
  197. 'm': formatMessage,
  198. 'n': endOfLine,
  199. 'p': logLevel,
  200. 'r': startTime,
  201. '[': startColour,
  202. ']': endColour,
  203. 'y': clusterInfo,
  204. 'z': pid,
  205. '%': percent,
  206. 'x': userDefined,
  207. 'X': contextDefined
  208. };
  209. function replaceToken(conversionCharacter, loggingEvent, specifier) {
  210. return replacers[conversionCharacter](loggingEvent, specifier);
  211. }
  212. function truncate(truncation, toTruncate) {
  213. let len;
  214. if (truncation) {
  215. len = parseInt(truncation.substr(1), 10);
  216. return toTruncate.substring(0, len);
  217. }
  218. return toTruncate;
  219. }
  220. function pad(padding, toPad) {
  221. let len;
  222. if (padding) {
  223. if (padding.charAt(0) === '-') {
  224. len = parseInt(padding.substr(1), 10);
  225. // Right pad with spaces
  226. while (toPad.length < len) {
  227. toPad += ' ';
  228. }
  229. } else {
  230. len = parseInt(padding, 10);
  231. // Left pad with spaces
  232. while (toPad.length < len) {
  233. toPad = ` ${toPad}`;
  234. }
  235. }
  236. }
  237. return toPad;
  238. }
  239. function truncateAndPad(toTruncAndPad, truncation, padding) {
  240. let replacement = toTruncAndPad;
  241. replacement = truncate(truncation, replacement);
  242. replacement = pad(padding, replacement);
  243. return replacement;
  244. }
  245. return function (loggingEvent) {
  246. let formattedString = '';
  247. let result;
  248. let searchString = pattern;
  249. /* eslint no-cond-assign:0 */
  250. while ((result = regex.exec(searchString)) !== null) {
  251. // const matchedString = result[0];
  252. const padding = result[1];
  253. const truncation = result[2];
  254. const conversionCharacter = result[3];
  255. const specifier = result[5];
  256. const text = result[6];
  257. // Check if the pattern matched was just normal text
  258. if (text) {
  259. formattedString += text.toString();
  260. } else {
  261. // Create a raw replacement string based on the conversion
  262. // character and specifier
  263. const replacement = replaceToken(conversionCharacter, loggingEvent, specifier);
  264. formattedString += truncateAndPad(replacement, truncation, padding);
  265. }
  266. searchString = searchString.substr(result.index + result[0].length);
  267. }
  268. return formattedString;
  269. };
  270. }
  271. const layoutMakers = {
  272. messagePassThrough: function () {
  273. return messagePassThroughLayout;
  274. },
  275. basic: function () {
  276. return basicLayout;
  277. },
  278. colored: function () {
  279. return colouredLayout;
  280. },
  281. coloured: function () {
  282. return colouredLayout;
  283. },
  284. pattern: function (config) {
  285. return patternLayout(config && config.pattern, config && config.tokens);
  286. },
  287. dummy: function () {
  288. return dummyLayout;
  289. }
  290. };
  291. module.exports = {
  292. basicLayout,
  293. messagePassThroughLayout,
  294. patternLayout,
  295. colouredLayout,
  296. coloredLayout: colouredLayout,
  297. dummyLayout,
  298. addLayout: function (name, serializerGenerator) {
  299. layoutMakers[name] = serializerGenerator;
  300. },
  301. layout: function (name, config) {
  302. return layoutMakers[name] && layoutMakers[name](config);
  303. }
  304. };