Skip to content

Feature request: flush buffer on uncaught error - class method decorator #3635

Closed
@dreamorosi

Description

@dreamorosi

Use case

In #3617 we have implemented a mechanism to buffer logs. The next step in the implementation is to allow customers to flush the buffer whenever there's an uncaught error thrown in the handler scope. This will be an opt-in feature and this item focuses on implementing this behavior for the class method decorator.

Solution/User Experience

As mentioned, this will be an opt-in feature. Customers will be able to enable it by passing a new option to the decorator called flushBufferOnUncaughtError:

const logger = new Logger({
  logLevel: 'WARN',
  bufferConfig: {
    maxBytes: 1024,
  }
});

class Lambda {
  @logger.injectLambdaContext({
    flushBufferOnUncaughtError: true, // default is false
  })
  async handler(event: unknown) {
    logger.debug('I am a debug'); // buffered
    logger.info('I am an info'); // NOT buffered
    
    throw new Error('I am an error'); // this causes the buffer to be flushed
  }
}

In terms of implementation, we'll have to refactor the current decorator implementation here.

Contrary to the ones in #3633, the changes for the decorator should be fairly straightforward. Currently we have a try/catch block in which we are actually not handling the catch block, but only the finally one:

let result: unknown;
try {
  result = await originalMethod.apply(this, [event, context, callback]);
} finally {
  if (options?.clearState || options?.resetKeys) loggerRef.resetKeys();
}

return result;

we should refactor this to something like:

try {
  return await originalMethod.apply(this, [event, context, callback]);
} catch (error) {
  // if log buffering is enabled, flush the buffer here
} finally {
  if (options?.clearState || options?.resetKeys) loggerRef.resetKeys();
}

In order to add the new config option to the decorator, you'll have to add it to the corresponding type here. Depending on whether you work on this or #3633 first, you might already have the type available.

Other than that, we should make sure the new code is covered by unit tests and the new type in the options is documented with comments.

Alternative solutions

N/A

Acknowledgment

Future readers

Please react with 👍 and your use case to help us understand customer demand.

Metadata

Metadata

Assignees

Labels

completedThis item is complete and has been merged/shippedfeature-requestThis item refers to a feature request for an existing or new utilityloggerThis item relates to the Logger Utility

Type

No type

Projects

Status

Shipped

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions