package com.ankurm.structuredlogging;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * placeOrder() logs exactly once, using the SLF4J 2.x fluent API's
 * addKeyValue() for fields that belong to this one call, and MDC for a
 * field (tenant) that should ride along with every log line for the
 * duration of the request - both end up as top-level members of the
 * structured JSON line once logging.structured.format.console is set to
 * a built-in format, with no extra code at the call site.
 */
@Service
public class OrderService {

    private static final Logger log = LoggerFactory.getLogger(OrderService.class);

    public void placeOrder(String orderId, String tenant, BigDecimal amount) {
        MDC.put("tenant", tenant);
        try {
            log.atInfo()
                    .addKeyValue("orderId", orderId)
                    .addKeyValue("amount", amount)
                    .log("order placed");
        } finally {
            MDC.remove("tenant");
        }
    }
}
