Logging with additional fields in web services

Hello :slight_smile: I got a question about logging that I’ve been thinking on for some time, wondering if someone could help me out:

Let’s say I’m writing a new gRPC service with a bunch of endpoints. A pattern that I’ve become fond of is to isolate the core logic from the gRPC related code. So the gRPC handlers will be very simple, and only call other functions/methods that do the main work. I like this style because most of the code becomes independent of gRPC (or http, or kafka, or whatever is the input to the service).

However, there is a problem which I struggle with: logging. I think it is appropriate to log in the gRPC
handler, then we can log an error if an error occurred, or an info message if all is ok. However, the gRPC request usually contains some additional data which would be nice to add to the log statement, which sometimes needs some handling to be extracted. One way to deal with this is to partially handle the request in the gRPC handler before the core logic, but this results in handling parts of the message twice, or it results in sending in the partially handled message plus the full message to the core logic. None of which is ideal, I think.

Has anyone else here struggled with this? Is there a nice way to solve it? Thanks in advance :slight_smile:

Hi @Gharzol

A logging context or a request context that can be sent along to the core logic operations might be one answer to this problem. The goal is to extract the required data from the gRPC request in the handler, save it in a context object, and then send that context object to the core logic methods.

Here’s an example to demonstrate this method:

  1. Create a logging context object that can retain the appropriate gRPC request information. This might be a basic data structure or an object with the necessary fields.

  2. Extract the required data from the request and populate the logging context object in the gRPC handler.

  3. When invoking the core logic functions, pass the logging context object to them.

  4. You may use the logging context object within the core logic functions to log important information along with the processing.

By employing a logging context, you prevent treating parts of the message twice or delivering the partially treated message to the core logic together with the whole message.

I hope this helps! Let me know if you have any further questions.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.