Skip to content

Logging error chains to CloudWatch #348

@mlafeldt

Description

@mlafeldt

I noticed that the Rust runtime currently logs handler errors using {} as the format:

error!("{}", err); // logs the error in CloudWatch

However, the widely used anyhow crate will only include the error chain with {:?} or {:#}:

https://github.com/dtolnay/anyhow/blob/71caf88b78cc3faf2b99ac3d7397a66a7da5a930/src/fmt.rs#L7-L40

Among other things, this means that only the last error will be logged to CloudWatch and that all underlying causes are lost when using with_context to augment errors.

My current solution/workaround is to add an additional log statement like this:

#[tokio::main]
async fn main() -> Result<(), Error> {
    env_logger::try_init()?;

    lambda_runtime::run(handler_fn(|_: Input, _: Context| async {
        let output = handler().await.map_err(|e| {
            error!("{:?}", e); // log error chain to CloudWatch
            e
        })?;
        Ok(output) as Result<Output>
    }))
    .await?;

    Ok(())
}

Of course, this duplicates error logging to some degree and would have to be done in every Lambda function. I wonder if there's a better way of telling the runtime how to log errors?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions