Search Sreeni's Insights

Filter by content type
technical October 29, 2019 6 min read

How to use structured logs in e-commerce? A worked example - Part 5

A worked e-commerce checkout example with agreed property names, BeginScope, log levels by failure and the queries which answer support questions.

Share:

How to use structured logs in e-commerce? A worked example - Part 5

Theory is easy to agree on, and it is difficult to apply when you sit in front of a real checkout flow. A customer clicks “Place order”, the request goes through the web application, the basket service, the payment gateway, the stock service and the shipping service, and something fails in the middle. The customer calls the support, and the support asks “what happened to my order?”. In the previous article, we discussed the correlation, the exceptions and the sensitive data. In this article, we are going to apply the guidelines to an e-commerce checkout, with the property names, the log levels, the code and the queries. This is an illustrative scenario to explain the idea, not a real system.

TL;DR Summary

  • Agree on a small set of property names for the e-commerce concepts (order, cart, customer, product, payment) and reuse them in every service.
  • Use OrderId as the correlation property, and open a BeginScope once at the start of the checkout, so all the downstream log entries carry it.
  • A declined payment of one customer is an Error or a Warning, the payment gateway being down for everybody is Fatal.
  • Hash the customer identifiers and mask the email and the card related data before logging.
  • With the properties in place, the support question “what happened to order O-1001?” is one query.

The scenario

Assume an online shop with a checkout flow of the following steps,

StepComponentWhat can go wrong
1. Validate the basketBasket serviceItem is out of stock, price changed
2. Reserve the stockStock serviceStock service is not reachable
3. Take the paymentPayment gateway (third party)Payment is declined, gateway is down
4. Create the shipmentShipping serviceAddress is not valid
5. Confirm the orderOrder serviceDatabase is not reachable

The following diagram depicts the flow. All the services which run inside the checkout share one scope, and the payment gateway is a third party outside it,

E-commerce checkout with one scope
E-commerce checkout with one scope

The support team gets calls like “my payment was taken, but I didn’t get the confirmation”. Without structured logs, someone has to search the text of five services and guess which entries belong to this customer.

Which properties do we log?

Let us decide the property names first. The names are the column names of our data set, so they must be the same in every service,

PropertyExamplePurposeNote
OrderIdO-1001Correlation id for the whole checkoutAvailable once the order is created. Before that, use CartId
CartIdC-5589Correlation id before the order exists
CustomerIdhash of the customer idGroup the entries of a customerHash it. Don’t log the name or the email
ProductIdP-778Which product the entry is about
PaymentProviderProviderAWhich payment gateway
DeclineReasonInsufficientFundsWhy the payment was declinedUse a fixed list of values, not free text
ChannelWeb, MobileWhere the order came from

Info: Just like the portfolio import example in the Part 4, the OrderId is not available in the first step. We use CartId there, and then both of them are logged once the order is created, so we can join the two halves.

How to write the logs?

We open a scope at the start of the checkout, so every downstream log entry (in the same process) has the properties. We don’t need to pass the order id to the stock or the payment code just for logging,

public async Task<OrderResult> PlaceOrderAsync(Order order)
{
    using (_logger.BeginScope(new Dictionary<string, object>
    {
        ["OrderId"] = order.Id,
        ["CartId"] = order.CartId,
        ["CustomerId"] = order.CustomerId.Hash(),
        ["Channel"] = order.Channel
    }))
    {
        _logger.LogInformation("Order received with {ItemCount} items and total {OrderTotal} {Currency}",
            order.Items.Count, order.Total, order.Currency);

        await _stockService.ReserveAsync(order);

        var payment = await _paymentService.TakePaymentAsync(order);
        if (payment.IsDeclined)
        {
            _logger.LogWarning("Payment declined by {PaymentProvider} with reason {DeclineReason}",
                payment.Provider, payment.DeclineReason);
            return OrderResult.PaymentDeclined(payment.DeclineReason);
        }

        _logger.LogInformation("Payment taken by {PaymentProvider}", payment.Provider);
        // create the shipment and confirm the order
    }
}

A few points to notice in this code,

  • The message templates are written with named properties, not with string concatenation or interpolation. Otherwise, the values will not be stored as properties.
  • The OrderId is not repeated in every statement, the scope adds it.
  • The CustomerId is hashed before it is logged (refer the Part 4), and the email and the card number are not logged at all.
  • DeclineReason comes from a fixed list, so we can group by it.

Warning: Don’t write $"Payment declined by {provider}" (string interpolation) in the log statement. It creates a plain text message and the property is lost. Always pass the values as the parameters.

Which log level for which failure?

The failure level depends on how many customers are impacted, as we discussed in the Part 4,

SituationLevelReason
Item is out of stock for one customerWarningExpected business situation, one request is impacted
One customer’s payment is declinedWarning or ErrorOne request is impacted. Use Error if it is not an expected decline
Address validation failedErrorInput or business validation of one request
Payment gateway is not reachable for everybodyFatalThe checkout is not working for the whole application
Order database is downFatalA dependent component is unavailable and the application is not usable

In Microsoft.Extensions.Logging, the Serilog Fatal level is called as LogCritical. All the Fatal entries should trigger an alert to the product team, so we know about a broken checkout before the customers tell us.

How to answer the support question?

Now the support asks “what happened to order O-1001?”. In Application Insights, it is one query,

traces
| where timestamp >= ago(1h)
| where customDimensions.OrderId == "O-1001"
| order by timestamp asc

In Seq (we will see it in the Part 7), the same is a filter on the property,

OrderId = 'O-1001'

And the business can ask a different question from the same data, “why are the payments declined today?”,

traces
| where timestamp >= ago(1d)
| where isnotempty(tostring(customDimensions.DeclineReason))
| summarize Declines = count() by DeclineReason = tostring(customDimensions.DeclineReason), PaymentProvider = tostring(customDimensions.PaymentProvider)
| order by Declines desc

Note: Traces are subject to the sampling rate of Application Insights (refer the Part 3 of the Application Insights guidelines). When you need the exact counts for the business, collect them as custom events with 100% sampling. Use the structured logs for the diagnosis.

What do we get at the end?

BeforeAfter
Search the text of five services and guessOne query on OrderId
”Payment declined” is a sentenceDeclineReason and PaymentProvider are columns we can group by
Customer data may leak in the messageCustomer id is hashed, email and card data are not logged
We know about a broken gateway from the customersA Fatal entry triggers an alert

Wrap up

In this article, we have looked at an e-commerce checkout, the property names to agree on, how to write the logs with BeginScope, how to select the log level for each failure, and the queries which answer the support and the business questions. I really appreciate that you took the time to read this article. In the next article, I will walk you through the use case of the mutual fund world: which client of which product is viewing which fund, sub-fund and share class, and which internal service is using which index.

Related Posts