Frontend logging pattern with Datadog and React Query

Purpose of logging

I think (frontend) logging helps deliver bug-free software to users and monitor the system for security. Firstly, logging helps find trends in user behavior. For example, if a user enters vin number many times in a insurance app. Secondly, logging helps developers find bad actors who are trying to game the system. Thirdly, logging helps us be aware of critical errors. For instance, if user can’t make payment, it is a serious error. Last but not least, logging helps facilitating troubleshooting or locating the root cause.

Coding Pattern for Logging

The app I am working on uses React Query as data layer (we ditched redux). We also use Datadog for frontend logging.

React Query provides a global setLogger function for logging errors. Any errors thrown in any useQuery or useMutation will be logged into the setLogger function.

The pattern I come up with is throw error in useQuery or useMutation with some context info, then in error logger in setLogger, check the error instance and then log to Datadog.

I created a ErrorWithContext subclass of Error, which takes a message and a context object to be logged into Datadog. In React Query hooks, you can throw a generic Error or this ErrorWithContext class. The benefit of using Error class is that you can log the stack trace to Datadog.