简体   繁体   中英

Which functions should I use to read aws lambda log

Once my lambda run is finished, I am getting this payload as a result:

{
  "version": "1.0",
  "timestamp": "2020-09-30T19:20:03.360Z",
  "requestContext": {
    "requestId": "2de65baf-f630-48a7-881a-ce3145f1127d",
    "functionArn": "arn:aws:lambda:us-east-2:044739556748:function:puppeteer:$LATEST",
    "condition": "Success",
    "approximateInvokeCount": 1
  }, 
  "responseContext": {
    "statusCode": 200,
    "executedVersion": "$LATEST"
  } 
}

I would like to read logs of my run from cloudwatch and also memory usage which I can see in lambda monitoring tab: 在此处输入图片说明

How can do it via sdk? Which functions should I use?

I am using nodejs.

You need to discover the log stream name that has been assigned to the Lambda function invocation. This is available inside the Lambda function's context .

exports.handler = async (event, context) => {
  console.log('context', context);
};

Results in the following log:

context { callbackWaitsForEmptyEventLoop: [Getter/Setter],
  succeed: [Function],
  fail: [Function],
  done: [Function],
  functionVersion: '$LATEST',
  functionName: 'test-log',
  memoryLimitInMB: '128',
  logGroupName: '/aws/lambda/test-log',
  logStreamName: '2020/10/03/[$LATEST]f123a3c1bca123df8c12e7c12c8fe13e',
  clientContext: undefined,
  identity: undefined,
  invokedFunctionArn: 'arn:aws:lambda:us-east-1:123456781234:function:test-log',
  awsRequestId: 'e1234567-6b7c-4477-ac3d-74bc62b97bb2',
  getRemainingTimeInMillis: [Function: getRemainingTimeInMillis] }

So, the CloudWatch Logs stream name is available in context.logStreamName . I'm not aware of an API to map a Lambda request ID to a log stream name after the fact, so you may need to return this or somehow persist the mapping.

Finding logs of a specific request-id can be done via AWS cloudwatch API.

You can use [filterLogEvents][1] API to extract (using regex) the relevant START and REPORT logs to gather the relevant information of the memory usage (You will also get the log stream name in the response for future use).

If you want to gather all the relevant logs of a specific invocation you will need to query create pairs of START and REPORT logs and query for all the logs in the specific timeframe between them on a specific log stream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM