Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

log.js 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 !== "udp";
  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. }, 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. const tags = {};
  43. if (infos.board) tags.board = infos.board;
  44. if (infos.original_ip) tags.original_ip = infos.original_ip;
  45. statsd.increment(type, 1, tags);
  46. }
  47. console.log(msg);
  48. }
  49. /**
  50. * @template {(...args) => any} F
  51. * @param {F} f
  52. * @returns {F}
  53. */
  54. function monitorFunction(f) {
  55. if (statsd) return statsd.helpers.wrapCallback(f.name, f);
  56. else return f;
  57. }
  58. /**
  59. * Report a number
  60. * @param {string} name
  61. * @param {number} value
  62. * @param {{[name:string]: string}=} tags
  63. */
  64. function gauge(name, value, tags){
  65. if (statsd) statsd.gauge(name, value, tags);
  66. }
  67. module.exports = { log, gauge, monitorFunction };