Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change log format of Cloudwatch logs from Lambda (Node.js)

If I do console.log('message') in my code, it shows up in Cloudwatch as
2017-03-16T18:58:21.823Z 863c835c-0a7a-11e7-9140-e5018d6e5029 message.

Is there any way to remove the automatic formatting so that Cloudwatch just displays the argument I pass to console.log?

like image 961
maniciam Avatar asked Mar 16 '17 20:03

maniciam


People also ask

Can you edit a CloudWatch log?

As you probably already know,Cloud-watch helps to record the logs of all aws services. Cloud-watch Log streams helps to listen the event automatically without any triggers. Using this Cloudwatch Log streams we can able to edit the cloud-watch logs.


2 Answers

Inside your handler you can overwrite console.log to write directly to stdout:

var util = require('util')

module.exports.handler = function (event, context, done) {
  console.log = function () {
    var args = Array.prototype.slice.call(arguments)
    process.stdout.write(args.map(function (arg) {
      return util.isPrimitive(arg) ? String(arg) : util.inspect(arg)
    }).join(' '))
  }

  // the rest of your handler...
}
like image 178
idbehold Avatar answered Oct 31 '22 05:10

idbehold


This code helped me to get rid of '<awsRequestId> <logLevel>' when we do console.log

const { Console } = require('console');
console.log = new Console({ stdout: process.stdout, stderr: process.stderr }).log;
like image 26
Sky Watcher Avatar answered Oct 31 '22 04:10

Sky Watcher