4

I am trying to get the log insights from aws using sdk for javascript v3, I can see that we can only schedule a query using StartQuery and later get results using getQueryResults methods respectively. I came across filterLogEvents method which filter the log events alone with Regex but I need to use the query alone.

Is there any hack to get the results synchronously ?

Vamsi
  • 388
  • 2
  • 12

1 Answers1

1

I used 'aws-sdk' v2 and managed to get query results like this, hope this helps.

const cl = new AWS.CloudWatchLogs({
  region: 'your-region',
})

const params = {
  endTime: new Date().getTime() /* required */ ,
  logGroupName: 'your-log-group-name' /* required */ ,
  queryString: `fields @message, @timestamp
      | parse @message /\\[(?<time>[\\S ]+): (?<msg_type>\\S+)\\/.+\\[(?<task_id>\\S+)\\](?<msg>.+)/
      | filter task_id = '${taskId}'
      | sort @timestamp desc
      | display @timestamp, time,msg_type,msg`,
  startTime: new Date().getTime(),/*start time*/
}


const getResults = (data) => {
    cl.getQueryResults({
        queryId: data.queryId
      }, (_err, _data) => {
        if (_err) {
          console.log(_err, _err.stack)
        } 
        else {
          const res = _data.results ? .map((r) => {
            return {
              timestamp: r.find((el) => el.field === '@timestamp') ? .value,
              type: r.find((el) => el.field === 'msg_type') ? .value,
              msg: r.find((el) => el.field === 'msg') ? .value,
            }
          })
          /*check the status and run the function again*/
          if (_data.status.toLowerCase() === 'running') {
            getResults(data)
          }
        })
    }
    cl.startQuery(params, (err, data) => {
      if (err) {
        console.log(err, err.stack)
      } else {
        getResults(data)
      }
    })