brefphp / bref

Serverless PHP on AWS Lambda
https://bref.sh
MIT License
3.17k stars 366 forks source link

Cloudwatch doesn't log PHP errors #1649

Closed victorronnow closed 1 year ago

victorronnow commented 1 year ago

Description:

I've deployed my Slim PHP web app using $ serverless deploy with the following configuration in serverless.yml:

service: app

provider:
  name: aws
  region: us-east-1
  environment:
    APP_ENV: 'production'
    STORYBLOK_PUBLIC_TOKEN: '....'
    AWS_S3_BUCKET: !Ref Storage
  iam:
    role:
      statements:
        - Effect: Allow
          Action: s3:*
          Resource:
            - !Sub '${Storage.Arn}'
            - !Sub '${Storage.Arn}/*'

plugins:
  - ./vendor/bref/bref
  - serverless-lift

functions:
  app:
    handler: public/index.php
    runtime: php-82-fpm
    timeout: 28
    events:
      - httpApi: '*'

constructs:
  website:
    type: server-side-website
    assets:
      '/dist/*': public/dist/

resources:
  Resources:
    Storage:
      Type: AWS::S3::Bucket

# Exclude files from deployment
package:
  patterns:
    - '!node_modules/**'
    - '!tests/**'

When accessing my app, I get a blank page with a 500 error response. I've tried to log the php errors with $ serverless logs -f app, but I only receive the following information with no PHP errors, which I need to resolve the issue:

~/www/website
❯ serverless logs -f app       
View, tail, and search logs from all functions with https://dashboard.bref.sh

INIT_START Runtime Version: provided:al2.v22    Runtime Version ARN: arn:aws:lambda:us-east-1::runtime:6c21009b8813291ce404aa6dd6aef448ced6660fa496sdf801823417
[17-Sep-2023 08:17:09] NOTICE: [pool default] 'user' directive is ignored when FPM is not running as root
[17-Sep-2023 08:17:09] NOTICE: fpm is running, pid 10
[17-Sep-2023 08:17:09] NOTICE: ready to handle connections
START
END Duration: 878.97 ms (init: 320.70 ms) Memory Used: 95 MB
START
END Duration: 235.40 ms Memory Used: 95 MB
START
...
END Duration: 240.64 ms Memory Used: 95 MB
START
END Duration: 424.10 ms Memory Used: 95 MB
START
END Duration: 425.95 ms Memory Used: 95 MB
START
victorronnow commented 1 year ago

So it seems that exceptions need to be logged manually when using Slim. I resolved it, by using brefphp/logger and tweaking my custom ErrorHandler. Now the errors are logged in Cloudwatch.

  // ErrorHandler.php
public function __invoke(ServerRequestInterface $request, Throwable $exception)
  {
    ...
    $logger = new \Bref\Logger\StderrLogger();
    $logger->error('Error', ['exception' => $exception]);
    ...
    throw $exception;
  }
// app.php
$errorMiddleware = $app->addErrorMiddleware(true, true, true);
$errorMiddleware->setDefaultErrorHandler(new ErrorHandler(...));