Laravel 8 logging AWS Cloudwatch

Tram Ho


Logging is an extremely important thing, and Cloudwatch is a pretty good visualization and query logging platform from AWS, surely systems on AWS often log to this email, today I would like to introduce how to make Laravel 8 can easily push log to Cloudwatch, let’s get started

How to implement

Install packages

Create class CloudWatchLoggerFactory to create a custom drive that pushes to cloudwatch

In config/logging.php, add custom driver setting for this type of log

Choose a reasonable exception to push to cloudwatch, here I will edit it in app/Exceptions/Handler.php, this is where laravel supports us to customize the entire Exception handling process, including logging error and response format API error, like 404 error, what 500 error is returned, … for my part, I attached the request param to the error, so we will capture exactly which request has been requested. cause errors, more convenient for debugging.

As you can see, common errors like RouteNotFoundException or NotFoundHttpException or ValidationException, are caused by the user entering the wrong url or form input, so it’s not important enough for us to log back to investigate :#)

Error log function add request param:

Don’t forget to choose the correct logging driver for the environment you need to log cloudwatch (usually STG and PROD)

Add 2 helpers to make logging in code more convenient

How to filter on Cloudwatch convenient for reading logs

Based on the log above, I have a few more convenient ways to query the log

  • query log get the last 20

  • query get number of messages containing Exception within 1h

  • query log does not contain Exception

  • query read error log coming from product API


Hope logging cloudwatch with laravel will be extremely easy for you, thanks for reading

Share the news now