metrics.mjs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { collectDefaultMetrics, register, Gauge } from 'prom-client'
  2. import { toSafeInteger } from 'lodash-es'
  3. export default {
  4. customMetrics: {},
  5. async init () {
  6. if (WIKI.config.metrics.isEnabled) {
  7. WIKI.logger.info('Initializing metrics...')
  8. register.setDefaultLabels({
  9. WIKI_INSTANCE: WIKI.INSTANCE_ID
  10. })
  11. collectDefaultMetrics()
  12. this.customMetrics.groupsTotal = new Gauge({
  13. name: 'wiki_groups_total',
  14. help: 'Total number of groups',
  15. async collect() {
  16. const total = await WIKI.db.groups.query().count('* as total').first()
  17. this.set(toSafeInteger(total.total))
  18. }
  19. })
  20. this.customMetrics.pagesTotal = new Gauge({
  21. name: 'wiki_pages_total',
  22. help: 'Total number of pages',
  23. async collect() {
  24. const total = await WIKI.db.pages.query().count('* as total').first()
  25. this.set(toSafeInteger(total.total))
  26. }
  27. })
  28. this.customMetrics.tagsTotal = new Gauge({
  29. name: 'wiki_tags_total',
  30. help: 'Total number of tags',
  31. async collect() {
  32. const total = await WIKI.db.tags.query().count('* as total').first()
  33. this.set(toSafeInteger(total.total))
  34. }
  35. })
  36. this.customMetrics.usersTotal = new Gauge({
  37. name: 'wiki_users_total',
  38. help: 'Total number of users',
  39. async collect() {
  40. const total = await WIKI.db.users.query().count('* as total').first()
  41. this.set(toSafeInteger(total.total))
  42. }
  43. })
  44. WIKI.logger.info('Metrics ready [ OK ]')
  45. } else {
  46. this.customMetrics = {}
  47. register.clear()
  48. }
  49. return this
  50. },
  51. async render (res) {
  52. try {
  53. res.contentType(register.contentType)
  54. res.send(await register.metrics())
  55. } catch (err) {
  56. res.status(500).end(err.message)
  57. }
  58. }
  59. }