Stop digging through unreadable logs: A general guide to logging
By: Rani Giro
Introduction
We’ve all been there: a production request fails, and you’re suddenly diving into a sea of disjointed log lines. You’re fishing for a trace here, a timestamp there, praying that you can manually stitch together the story of what actually happened.
Let’s face it: Standard logging is an observability disaster. It’s hard to read, nearly impossible to debug quickly, and—worst of all—it’s incredibly expensive. Ingesting thousands of separate log.info lines for every minor event burns through your cloud budget while providing very little signal.
What You’ll Learn in This Article
- The “Context Gap” Problem: Why standard sequential logs make debugging in production a nightmare and how to fix it.
- Request Aggregation: How to use Spring Boot’s @RequestScope to collect full request lifecycles into a single source of truth.
- The Orchestration Layer: Implementing a Middleware to automatically capture metadata, durations, and exceptions without manual boilerplate.
- Developer Experience: Using the RequestAwareService pattern to give your entire backend instant logging capabilities with zero dependency injection.
Better Together – Aggregated Request Logging.
Instead of spraying lines everywhere, you collect everything into a single “container” during the request lifecycle. When the request finishes, you ship it as one comprehensive, structured JSON object.
Implementation Example
The Orchestrator (LoggerMiddleware): This captures the start, the end, and any exceptions in between. This happens before each request that comes in.
//LoggerMiddleware.java
@Slf4j
@Component
public class LoggerMiddleware extends OncePerRequestFilter{
@Autowired
protected RequestLoggerService requestLogger;
@Override
protected void doFilterInternal(
@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull FilterChain filterChain
){
// Before the request, we add request metadata.
long startTime = System.currentTimeMillis();
HashMap<String,Object> reqInfo = new HashMap<>();
reqInfo.put("method", request.getMethod());
reqInfo.put("path", request.getRequestURI());
reqInfo.put("session_id", request.getRequestedSessionId());
reqInfo.put("protocol", request.getProtocol());
reqInfo.put("is_secure", request.isSecure());
requestLogger.log("request", reqInfo);
try {
// Call the request.
filterChain.doFilter(request, response);
}catch(Exception e){
HashMap<String,Object> errorInfo = new HashMap<>();
errorInfo.put("message",e.getMessage());
errorInfo.put("cause", e.getCause());
requestLogger.log("error", errorInfo);
}finally {
// After the request call finished.
Object exception = request.getAttribute("jakarta.servlet.error.exception");
if (exception instanceof Throwable) {
HashMap<String, Object> errorDetails = new HashMap<>();
errorDetails.put("message", ((Throwable) exception).getMessage());
requestLogger.log("exception", errorDetails);
}
long duration = System.currentTimeMillis() - startTime;
HashMap<String,Object> respInfo = new HashMap<>();
respInfo.put("request_time_ms", duration);
respInfo.put("status", response.getStatus());
requestLogger.log("response", respInfo);
requestLogger.publish();
}
}
The Central Warehouse (LoggerService): This manages the data and handles the logging logic.
// LoggerService.java
@Slf4j
@Service
public class LoggerService {
private final ObjectMapper objectMapper = new ObjectMapper();
private static final ConcurrentHashMap<String, ConcurrentHashMap<String, Object>> logs = new ConcurrentHashMap<>();
public void log(String requestId, String key, Object val) {
// Insert the Request "log" into the log repositroy.
logs.computeIfAbsent(requestId, id -> new ConcurrentHashMap<>())
.put(key, val);
}
public void publish(String requestURI, String requestId) {
// Remove logs that are published.
var requestLogs = logs.remove(requestId);
if (requestLogs == null) {
return;
}
try {
// Actually log the object.
log.info(objectMapper.writeValueAsString(requestLogs));
} catch (Exception e) {
log.error("Failed to publish logs", e);
}
}
}
The Request wrapper (RequestLoggerService): This calls the Logger service and automatically attaches the Request id so all aggregated data belong to the same request. This works concurrently. Notice we use the @RequestScope annotation which is Spring Boot “magic”, that allows us to get the request context.
//RequestLoggerService.java
@Component
@RequestScope
public class RequestLoggerService {
private final String requestId;
private final LoggerService logger;
private final String requestURI;
public RequestLoggerService(HttpServletRequest request,LoggerService logger){
this.requestId = request.getRequestId();
this.logger = logger;
this.requestURI = request.getRequestURI();
}
public void log(String key, Object val){
if(this.requestId == null){
System.err.println("Failed to log, null request id.");
return;
}
logger.log(this.requestId, key, val);
}
public void publish(){
if(this.requestId == null){
System.err.println("Failed to log, null request id.");
return;
}
logger.publish(this.requestURI,this.requestId);
}
}
Developer Experience (RequestAwareService): A simple base class that gives any business logic service instant access to the logger without the headache of manual Dependency Injection in every file. We can use the logger by doing class SomeCustomClass extends RequestAwareService.
public abstract class RequestAwareService{
@Autowired
protected RequestLoggerService requestLogger;
}
Solving the Cost & Noise Problem
There is a slight problem with this approach, storing detailed logs for every “200 OK” request is often a waste of money. We solve this by aggregating data into one object, you can implement Smart Sampling or Conditional Logging at the finish line.
Final Thoughts
Moving from “log-spraying” to Contextual Aggregation is more than just a technical tweak, it’s a mindset shift from simple Logging to true Observability.
By treating your logs as structured data objects rather than a stream of disjointed text, you gain:
- Speed: Debugging a production incident takes seconds when the entire context is in one JSON block.
- Sanity: No more manual “session ID” stitching across thousands of lines.
- Savings: You stop paying to store thousands of redundant log lines for healthy requests and focus your budget where it matters: the errors.
If you are building high-scale applications, this pattern is a game-changer for both your developer experience and your infrastructure bill.
Connect: 👥 Linkedin ⭐ Github“Writing is how I learn; sharing is how we grow.” I’m Rani, and I’m on a mission to break down complex technologies into practical insights. If you value curiosity and clear problem-solving, let's build something together.