keymetrics / pm2-io-js-api

PM2.io API Client for Javascript
http://docs.api.cloud.pm2.io/index.html
Apache License 2.0
28 stars 13 forks source link

How to start an action? #75

Closed AlloryDante closed 3 years ago

AlloryDante commented 3 years ago

Hello, I discovered that I cannot receive logs until I start a triggerPM2 action with startLogging as action to start.I have discovered this as I can receive logs only if I have the pm2.io "Show Logs" window open.This does the startLogging automatically for me, but I dont know how to start loging using this specific library.

Could someone please help?

Unitech commented 3 years ago

Hi,

Here is the relevant code from app.pm2.io frontend:

 async [COLLECT_LOGS](
    { state, commit, dispatch, getters },
    { bucketId = state.currentBucketId, serverName, appName },
  ) {
    function startLogging() {
      return km.actions.triggerPM2Action(bucketId, {
        method_name: 'startLogging',
        server_name: serverName,
        app_name: appName,
      })
    }

    await startLogging()

    return new Observable(observer => {
      // Keep starting logging every 100 seconds, because logging stops after 120 seconds
      const intervalId = setInterval(startLogging, 100000)

      const stopListening = listenRealtimeEvents(state.buckets[bucketId].bucket, {
        '*:logs'(res) {
          if (appName) {
            res = res.filter(
              log => log.process.name === appName && log.process.server === serverName,
            )
          }
          res.forEach(log => observer.next(log))
        },
      })

      return () => {
        km.actions.triggerPM2Action(bucketId, {
          method_name: 'stopLogging',
          server_name: serverName,
          app_name: appName,
        })

        stopListening()
        clearInterval(intervalId)
      }
    })
  },

Listen realtime events:

export function listenRealtimeEvents(bucket, events) {
  for (const event in events) io.realtime.on(`${bucket.public_id}:${event}`, events[event])
  return () => {
    for (const event in events) io.realtime.off(`${bucket.public_id}:${event}`, events[event])
  }
}

In the example code the variable km is an instance of: https://www.npmjs.com/package/@pm2/js-api

To get an access token when using @pm2/js-api go to: https://app.pm2.io/profile Then go to token tab, create a token (button top right) and give maximum permissions.

Let me know if you need extra infos

AlloryDante commented 3 years ago

Thank you.You solved my issue.Youre the best.