Search code examples
javascriptnode.jsloggingaws-lambdaamazon-cloudwatch

Filter console.error and console.log on CloudWatch


I have a lambda function that have console.error and console.log which node.js print stderr and stdout respectively.

But when I go to CloudWatch, I get something like this:

2017-12-29 11:08:16.889 (+00:00) I can log with console.log
2017-12-29 11:08:16.889 (+00:00) I can log with console.error

It doesn't seem like they make any differentiation.

Am I missing something? Is there any way to check their difference, which wouldn't involve manually adding prefixes?


Solution

  • As this question was somehow popular I'll answer myself with the solution I applied.

    AWS Lambda just doesn't differentiate between console.log and console.error in CloudWatch.

    The only way is really to interject the functions inside the lambda with this for example:

    const originalConsoleError = console.error;
    const originalConsoleLog = console.log;
    
    console.error = function (message) {
      originalConsoleError(`ERROR: ${message}`);
    };
    
    console.log = function (message) {
      originalConsoleLog(`INFO: ${message}`);
    };
    
    // Example usage
    console.log('This is an informational message');
    console.error('This is an error message');
    
    2017-12-29 11:08:16.889 (+00:00) INFO: This is an informational message
    2017-12-29 11:08:16.889 (+00:00) ERROR: This is an error message
    

    And then if we want to filter we can use CloudWatch Insights:

    fields @timestamp, @message
    | filter @message like /INFO:/ or @message like /ERROR:/
    | sort @timestamp desc