Flash magazines before shutting down Lambda

I am writing a NodeJS / Typescript registration service for AWS Lambda, and I noticed that there are four ways to complete the lambda function:

  • Default. All callbacks are complete and Lambda will complete the execution.

  • Error. There is an uncaught exception or an unhandled rejection, and it calls Lambda and calls process.exit().

  • Time-out. Lambda runs more than the time specified by the developer.
  • Managed termination. Lambda completes execution by calling context.done(), context.succeed()or context.fail(). This is no longer offered, should be used instead callback().

I want my logger to be able to clear all the logs no matter how Lambda completes, and this is what I used with various completion methods:

  • Default. I wrapped the handler and the callback function to clear the logs before calling the callback function, and it worked perfectly.

    wrap(fn) {
        return () => {
            // Wrap the callback function
            let callbackFunc = arguments[arguments.length - 1];
            let wrappedCallback = this.wrapCallback(callbackFunc);
            arguments[arguments.length - 1] = wrappedCallback;
    
            return fn.apply(this, arguments);
        };
    }
    
    wrapCallback(fn) {
        return () => {
            logger.flush();
            return fn.apply(this, arguments);
        };
    
  • Error. I added code to catch process.exit errors and it worked.

    process.on('unhandledRejection', (reason, p) => {
        logErrorAndFlusgLogs();
    }).on('uncaughtException', err => {
        logErrorAndFlusgLogs();
    }).on('exit', (code) => {
        logErrorAndFlusgLogs();
    });
    

But for “Timeout” and “Controlled completion”, none of the functions work above, and I could not find a way to catch it and clear the logs before Lambda completed, any idea on how to do this? Thank.

+4
source share
1 answer

Timeouts are processed by a lambda container. There is currently no signal or callback, so in this case it is best to set the timer to expire a few minutes before the timeout value in order to clear the logs and stop the lambda yourself.

context.done, context.succeed context.fail:

const { done, succeed, fail } = context;

context.done = (...params) => {
    logErrorAndFlushLogs();
    done(...params);
};

context.succeed = (...params) => {
    logErrorAndFlushLogs();
    succeed(...params);
};

context.fail = (...params) => {
    logErrorAndFlushLogs();
    fail(...params);
};
+3

Source: https://habr.com/ru/post/1695887/


All Articles