You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

log.js 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. const config = require("./configuration.js"),
  2. SDC = require("statsd-client");
  3. /**
  4. * Parse a statsd connection string
  5. * @param {string} url
  6. * @returns {SDC.TcpOptions|SDC.UdpOptions}
  7. */
  8. function parse_statsd_url(url) {
  9. const regex = /^(tcp|udp|statsd):\/\/(.*):(\d+)$/;
  10. const match = url.match(regex);
  11. if (!match)
  12. throw new Error("Invalid statsd connection string, doesn't match " + regex);
  13. const [_, protocol, host, port_str] = match;
  14. const tcp = protocol === "tcp";
  15. const port = parseInt(port_str);
  16. return { tcp, host, port, prefix: "wbo" };
  17. }
  18. /**
  19. * Statsd client to which metrics will be reported
  20. * @type {SDC | null}
  21. * */
  22. let statsd = null;
  23. if (config.STATSD_URL) {
  24. const options = parse_statsd_url(config.STATSD_URL);
  25. console.log("Exposing metrics on statsd server: " + JSON.stringify(options));
  26. statsd = new SDC(options);
  27. }
  28. if (statsd) {
  29. setInterval(function reportHealth() {
  30. statsd.gauge("memory", process.memoryUsage().heapUsed);
  31. }, 30 * 1000);
  32. }
  33. /**
  34. * Add a message to the logs
  35. * @param {string} type
  36. * @param {any} infos
  37. */
  38. function log(type, infos) {
  39. var msg = type;
  40. if (infos) msg += "\t" + JSON.stringify(infos);
  41. if (statsd) {
  42. let stat_name = type;
  43. if (infos.board) stat_name += "." + infos.board;
  44. statsd.increment(stat_name);
  45. }
  46. console.log(msg);
  47. }
  48. /**
  49. * @template {(...args) => any} F
  50. * @param {F} f
  51. * @returns {F}
  52. */
  53. function monitorFunction(f) {
  54. if (!statsd) {
  55. return f;
  56. }
  57. let client = statsd.getChildClient(f.name);
  58. return function () {
  59. let startTime = new Date();
  60. try {
  61. const result = f.apply(null, arguments);
  62. client.increment("ok", 1);
  63. return result;
  64. } catch (e) {
  65. client.increment("err", 1);
  66. throw e;
  67. } finally {
  68. client.timing("time", startTime);
  69. }
  70. };
  71. }
  72. /**
  73. * Report a number
  74. * @param {string} name
  75. * @param {number} value
  76. * @param {{[name:string]: string}=} tags
  77. */
  78. function gauge(name, value, tags) {
  79. if (statsd) statsd.gauge(name, value, tags);
  80. }
  81. module.exports = { log, gauge, monitorFunction };