惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LangChain Blog
Scott Helme
Scott Helme
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Stack Overflow Blog
Stack Overflow Blog
Forbes - Security
Forbes - Security
T
The Blog of Author Tim Ferriss
Y
Y Combinator Blog
S
Schneier on Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Cisco Talos Blog
Cisco Talos Blog
N
News | PayPal Newsroom
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Project Zero
Project Zero
Cyberwarzone
Cyberwarzone
Vercel News
Vercel News
M
MIT News - Artificial intelligence
云风的 BLOG
云风的 BLOG
Google Online Security Blog
Google Online Security Blog
Simon Willison's Weblog
Simon Willison's Weblog
MongoDB | Blog
MongoDB | Blog
Martin Fowler
Martin Fowler
T
Tenable Blog
I
InfoQ
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
G
Google Developers Blog
D
DataBreaches.Net
博客园 - Franky
Know Your Adversary
Know Your Adversary
Spread Privacy
Spread Privacy
S
Security @ Cisco Blogs
Hacker News: Ask HN
Hacker News: Ask HN
J
Java Code Geeks
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
F
Full Disclosure
C
Cisco Blogs
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed
C
CXSECURITY Database RSS Feed - CXSecurity.com
The Cloudflare Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
I
Intezer
The GitHub Blog
The GitHub Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
F
Fortinet All Blogs
Jina AI
Jina AI
V
Visual Studio Blog
L
LINUX DO - 热门话题
WordPress大学
WordPress大学
aimingoo的专栏
aimingoo的专栏

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Zero-Code-Change Stacktrace Filtering for Spring Boot: An Infrastructure-Level Integration
Michael Gant · 2026-04-23 · via DEV Community

This article is intended for software architects, senior backend engineers, and platform engineers working on commercial Java systems where stacktraces are often dominated by framework and infrastructure noise. It is particularly relevant for teams using Spring Boot or other layered architectures who want to improve diagnostic clarity without introducing changes to application code.
This article focuses on how to integrate the MgntUtils stacktrace filtering feature at the infrastructure level. The focus is not the filtering algorithm itself, but rather how to integrate it cleanly so it fits naturally into existing commercial systems and development workflows.

Brief feature Recap

We are talking about the stacktrace filtering feature — one of the most widely used utilities of the open-source MgntUtils library.

A detailed technical deep-dive describing the algorithm and its behavior is available in my article “Java Stacktrace filtering utility”, published on LinkedIn and DZone. If you are interested in the internal mechanics, please refer to that piece. This article assumes you already know the value of the feature and want to know how to deploy it.)

In short, the feature provides intelligent stacktrace filtering that removes framework-related noise (Spring, Hibernate, CGLIB proxies, reflection, servlet chains, etc.). It leaves a concise, easy-to-read stacktrace focused strictly on your application-level code, effectively eliminating the dreaded “stacktrace scroll of death” problem.

The Integration Pain Point

In the original article, the recommended usage pattern was to replace logging statements from:
logger.info("Message", e);
to
logger.info("Message" + TextUtils.getStacktrace(e));

However, when a senior architect responsible for platform quality and long-term maintainability sees a recommendation like this, it immediately raises two major NO-GO flags:

  • Massive Refactoring Effort: Replacing every logging statement across an existing commercial codebase is expensive, risky, and nearly impossible to justify to management.
  • Ongoing Maintainability Cost: Developers would need to remember to always use this special logging pattern. Inevitably, some log statements would be written incorrectly, leading to inconsistencies and reducing the value of the solution.

Because of these concerns, even a highly useful feature is often rejected purely due to integration friction.

The Goal of This Article

This article demonstrates an integration approach that resolves these concerns by moving the feature integration to the infrastructure level.

The proposed solution:

  • Requires ZERO changes to your existing application code.
  • Preserves standard logging syntax (developers just log exactly as they always have).
  • Introduces no additional cognitive burden on your team.
  • Remains fully transparent to the application layer.

As a bonus, we will also introduce a hot runtime toggle, allowing Admin or SRE users to enable or disable the filtering dynamically at runtime - without a redeployment or server restart.

An integration example is demonstrated in the MgntUtilsUsage project—a working, out-of-the-box Spring Boot Application with this full infrastructure integration implemented. The project is available as a public GitHub repository.

Integration Steps

For the purposes of this article, we will assume the commercial project is using either Logback (which is the default logging implementation for Spring Boot) or Log4j2. For both of those logging implementations, the proposed integration is roughly the same:

Prerequisite: Since the stacktrace filtering feature is provided by the MgntUtils library, you will first need to include this library in your project. Here are the Maven and Gradle coordinates:

Maven:

<dependency>
    <groupId>com.github.michaelgantman</groupId>
    <artifactId>MgntUtils</artifactId>
    <version>1.7.0.7</version>
</dependency>

Enter fullscreen mode Exit fullscreen mode

Gradle:

implementation("com.github.michaelgantman:MgntUtils:1.7.0.7")

Enter fullscreen mode Exit fullscreen mode

Note: Version 1.7.0.7 is the latest version at the time of writing. To ensure you have the latest release, please check the MgntUtils page on Maven Central.

  1. Write a Java class that will handle any incoming exception using the MgntUtils stacktrace filtering utility.
  2. Register this class with the logging framework to act as a custom exception handler.
  3. Initialize the relevant package prefixes for the MgntUtils stacktrace filtering utility, so it knows which packages should be considered important (which controls how the stacktrace filtering is done).

Integration Steps for Logback

1. Write the Logback Interceptor (The "Magic" Engine)

Logback controls how exceptions are formatted via converters. We will create a custom converter that intercepts the exception, strips out the framework noise using MgntUtils, and returns the clean string.

Create this class in your project:

package com.example.stamboot.config.logging;

import com.mgnt.utils.TextUtils;
import ch.qos.logback.classic.pattern.ThrowableProxyConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.ThrowableProxy;

/**
 * Global Logback interceptor to filter all stack traces using MgntUtils.
 */

public class MgntStackTraceConverter extends ThrowableProxyConverter {
    private static boolean cutTheBS = true;

    @Override
    public String convert(ILoggingEvent event) {
       IThrowableProxy proxy = event.getThrowableProxy();
       if (proxy == null) {
          return "";
       }

       // Extract the raw java.lang.Throwable from Logback's proxy object
       if (proxy instanceof ThrowableProxy) {
          Throwable rawException = ((ThrowableProxy) proxy).getThrowable();
          //remove first new line and add new line at the end
          return TextUtils.getStacktrace(rawException, cutTheBS).substring(1) + "\n";
       }

       // Fallback: If the exception is serialized over a network,
       // fallback to standard Logback formatting.
       return super.convert(event);
    }

    public static synchronized boolean isCutTheBS() {
       return cutTheBS;
    }

    public static synchronized void setCutTheBS(boolean cutTheBs) {
       MgntStackTraceConverter.cutTheBS = cutTheBs;
    }
}

Enter fullscreen mode Exit fullscreen mode

Note that we added two methods here: isCutTheBS() and setCutTheBS(). Those methods are not required by the ThrowableProxyConverter interface, but they will be used for a hot switch that will allow us to programmatically turn the filtering feature on and off without restarting the project.

2. Wire it into logback.xml (or logback-spring.xml)

If you are starting a new project (and not integrating this feature into an existing one), you just need to tell Logback to replace its default exception printing logic (usually denoted by %ex) with your new custom converter. Create a new file named logback.xml and place it in your classpath (if it is a Spring Boot project, place it in your src/main/resources folder):

<configuration>
    <conversionRule conversionWord="ex" 
          converterClass="com.example.stamboot.config.logging.MgntStackTraceConverter" />
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n%ex</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="CONSOLE" />
    </root>
</configuration>

Enter fullscreen mode Exit fullscreen mode

If you are integrating this feature into an existing project, you most likely already have your Logback configuration in a logback.xml or logback-spring.xml file. In this case, you will need to do two things:

A. Add the <conversionRule>
You must add this line near the top of the <configuration> block:

<conversionRule conversionWord="ex" 
converterClass="com.example.stamboot.config.logging.MgntStackTraceConverter" />

Enter fullscreen mode Exit fullscreen mode

B. Update the <pattern> for all Appenders (The Invocation)
Just because you taught Logback the word %ex doesn't mean the appenders are actually using it. You must check the <pattern> strings inside your existing <appender> blocks and make sure they invoke your token.

The Spring Boot Gotcha: By default, standard Logback uses %ex to print exceptions. But if a project is using Spring Boot, developers often copy-paste Spring's default patterns, which use %wEx (Whitespace Throwable Proxy) or %xEx (Extended Throwable Proxy).

If an existing appender looks like this:

<pattern>%d{yyyy-MM-dd} [%thread] %-5level %logger{36} - %msg%n%wEx</pattern>

Enter fullscreen mode Exit fullscreen mode

Your filter will not run, because Logback is looking for the %wEx logic, not your %ex logic! They must change the end of their pattern to use the exact conversionWord you defined in step 1:

<pattern>%d{yyyy-MM-dd} [%thread] %-5level %logger{36} - %msg%n%ex</pattern>

Enter fullscreen mode Exit fullscreen mode

3. Configure your relevant packages

You will need to invoke the method TextUtils.setRelevantPackage("com.example.stamboot.") somewhere in your project initialization to specify which packages should be considered important.

Note that this method supports multiple prefixes. In my example, I used a single prefix ("com.example.stamboot.") since I took it from the MgntUtilsUsage project - a working, out-of-the-box Spring Boot Application with this full infrastructure integration implemented. In that repo, all my code resides in packages that start with that prefix. You will need to set the correct prefix (or multiple prefixes) for your specific project.

For a detailed discussion of this mechanism, see the Java Stacktrace filtering utility article I mentioned above, as well as the Javadoc for the getStacktrace() method.

Important Note: If your project is a Spring Boot project, we will discuss exactly where to place this initialization code for maximum efficiency at the end of the article.

Integration Steps for Log4J2

To replace the default exception formatter in Log4j2 without XML, you just write the converter and annotate it. At compile time, Log4j2 finds it and wires it up automatically.

1. Write the Log4j2 Plugin (The Converter)

Instead of implementing an interface, you extend ThrowablePatternConverter and tag it with Log4j2's @Plugin and @ConverterKeys annotations.

By taking over the keys {"ex", "throwable", "exception"}, you are telling Log4j2: "Anytime a layout pattern asks for an exception, use me instead of the default."

So your class for Log4J2 option will look as follows:

package com.example.stamboot.config.logging;

import com.mgnt.utils.TextUtils;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.pattern.ConverterKeys;
import org.apache.logging.log4j.core.pattern.PatternConverter;
import org.apache.logging.log4j.core.pattern.ThrowablePatternConverter;

/**
 * Global Log4j2 interceptor to filter stack traces using MgntUtils.
 */
@Plugin(name = "MgntStackTraceConverter", category = PatternConverter.CATEGORY)
@ConverterKeys({ "ex", "throwable", "exception" }) // Overrides default tokens
public class MgntStackTraceConverter extends ThrowablePatternConverter {
    private static boolean cutTheBS = true;

    // Log4j2 plugins REQUIRE a static newInstance method to be instantiated!
    public static MgntStackTraceConverter newInstance(final Configuration config, final String[] options) {
        return new MgntStackTraceConverter(config, options);
    }

    protected MgntStackTraceConverter(Configuration config, String[] options) {
        super("MgntThrowable", "throwable", options, config);
    }

    @Override
    public void format(final LogEvent event, final StringBuilder toAppendTo) {
        Throwable rawException = event.getThrown();

        if (rawException != null) {
            // Route the exception through MgntUtils!
            String cleanTrace = TextUtils.getStacktrace(rawException, cutTheBS);
            //remove first new line and add new line at the end
            toAppendTo.append(cleanTrace.substring(1)).append("\n"); 
        }
    }

    public static synchronized boolean isCutTheBS() {
        return cutTheBS;
    }

    public static synchronized void setCutTheBS(boolean cutTheBs) {
        MgntStackTraceConverter.cutTheBS = cutTheBs;
    }
}

Enter fullscreen mode Exit fullscreen mode

2. Wire it into log4j2.xml (or log4j2-spring.xml)

If you are starting a new project with Log4j2, you will create a new log4j2.xml file in your src/main/resources folder.

Because your custom converter uses the @Plugin and @ConverterKeys annotations, Log4j2 absorbs the logic natively. You do not need a complex <conversionRule> mapping like Logback. You simply need to provide the packages attribute in the root configuration tag so Log4j2 knows where to scan for your class:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" packages="com.example.stamboot.config.logging">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout>
                <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n%ex</Pattern>
            </PatternLayout>
        </Console>
    </Appenders>

    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

Enter fullscreen mode Exit fullscreen mode

If you are integrating this feature into an existing project, you most likely already have a log4j2.xml (or log4j2-spring.xml) file. In this case, you only need to verify two things:

A. Add the packages attribute to the root tag
Find your existing <Configuration> tag at the very top of the file and add your package path to it:

<Configuration status="WARN" packages="com.example.stamboot.config.logging">

Enter fullscreen mode Exit fullscreen mode

B. Update the <Pattern> for all Appenders
Just like with Logback, you must check your existing <Pattern> strings. If your project is a Spring Boot application, developers may have copied Spring's default patterns which use %wEx or %xEx.

If an existing appender looks like this:

<Pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n%wEx</Pattern>

Enter fullscreen mode Exit fullscreen mode

Your filter will not trigger! You must change the end of the pattern to use %ex (or %throwable or %exception), which match the @ConverterKeys defined in your Java class:

<Pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n%ex</Pattern>

Enter fullscreen mode Exit fullscreen mode

3. Configure relevant packages

This step is the same regardless of whether you use Logback, Log4j2, or any other logging framework in your project. You will need to invoke the method TextUtils.setRelevantPackage("com.example.stamboot.") somewhere in your project initialization to specify which packages should be considered important. Earlier in the article, we promised to discuss in detail where to place this initialization code if your project is Spring Boot-based. So, as promised, here is the recommendation:

If you are using a modern IoC framework like Spring Boot, you might be tempted to put this initialization inside a Spring component, perhaps using an @EventListener(ContextRefreshedEvent.class) or a @PostConstruct method. Do NOT do this. If you rely on the Spring lifecycle to initialize your stacktrace filter, you create a massive logging blind spot during application startup. In Spring Boot, application startup isn't just server configuration - it is exactly when the framework uses reflection to instantiate and execute your code. Consider the two most common (and painful) startup crashes:

  • The @PostConstruct Crash: Imagine a developer writes a service that pre-loads cache data from the database the moment the bean is created. If loadData() throws a NullPointerException or BadSqlGrammarException, the crash happens before the application context is fully ready.
  • The Bad @Configuration Bean: If a configuration class manually instantiates a bean and throws an exception (e.g., trying to read a missing file or parse a bad JWT secret), Spring wraps your exception in a massive BeanCreationException.

If your prefixes are not set yet because you are waiting for an ApplicationReadyEvent, you will get the dreaded 200-line "Scroll of Death" consisting almost entirely of org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory noise.

The Solution: The main() method

To guarantee your filter is already configured and armed during the most chaotic part of the application lifecycle, you must move the initialization entirely outside of the Spring context. Place it in your pure Java main() method, right before SpringApplication.run(...) is called:

package com.example.stamboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.mgnt.utils.TextUtils;

@SpringBootApplication
public class StamBootApplication {

    public static void main(String[] args) {
        // 1. Arm the stacktrace filter FIRST
        TextUtils.setRelevantPackage("com.example.stamboot.");

        // 2. Start the Spring machinery
        SpringApplication.run(StamBootApplication.class, args);
    }
}

Enter fullscreen mode Exit fullscreen mode

By doing this, MgntUtils will see your application packages on the stack during a startup crash, filter out the 190 lines of Spring Boot factory noise, and point you exactly to the line in your @PostConstruct or @Configuration class that broke the deployment.

On the other hand MgntUtils filtering feature has a built-in safety measure: if your entire stacktrace does NOT contain any lines that match your configured prefixes, the stacktrace is printed in full and not filtered at all. Because of this fail-safe, you do not risk losing important diagnostic information if a crash occurs purely within the framework and does not involve your code.

Bonus Feature: Hot enable/disable filtering switch

Earlier in the article we promised a hot runtime toggle, allowing Admin or SRE users to enable or disable the filtering dynamically at runtime - without a redeployment or server restart. So, here it is.

If you look at our MgntStackTraceConverter class implementation from earlier, we introduced two seemingly redundant methods:

public static synchronized boolean isCutTheBS() {
    return cutTheBS;
}

public static synchronized void setCutTheBS(boolean cutTheBs) {
    MgntStackTraceConverter.cutTheBS = cutTheBs;
}

Enter fullscreen mode Exit fullscreen mode

These methods are the getter and setter for the cutTheBS flag which in our MgntStackTraceConverter implementation controls whether the stacktrace is filtered or not. These methods are our hooks. All we need now is to provide some user interface that will allow user to control this flag.

In our working Spring Boot example (mentioned earlier and discussed below) we provide a REST controller that gives the user two APIs to see the current value of the flag and to change its setting.

Here is the proposed controller implementation:

package com.example.stamboot.config.logging;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("config/log/stacktrace")
public class LoggerConfigController {

  @GetMapping
  public ResponseEntity<String> setFilteringFlag(@RequestParam Boolean filter) {
    MgntStackTraceConverter.setCutTheBS(filter);
    return ResponseEntity.ok(
      "Stacktrace filtering flag is set to: " + MgntStackTraceConverter.isCutTheBS());
  }

  @GetMapping("/filter/status")
  public ResponseEntity<String> getFilteringFlag() {
    return ResponseEntity.ok(
      "Stacktrace filtering flag current value is: " + MgntStackTraceConverter.isCutTheBS());
  }
}

Enter fullscreen mode Exit fullscreen mode

By calling the provided URLs user can:

http://localhost:8080/config/log/stacktrace?filter=true
http://localhost:8080/config/log/stacktrace?filter=false

Important Notes:

  1. Using @GetMapping here is a deliberate trade-off. By definition, GET must be safe (no side effects) and idempotent — it should never mutate state. Using it here is a clear violation of HTTP semantics, and in a real commercial implementation this endpoint should use @PutMapping or @PostMapping. However, for the purposes of this demo, GET allows you to trigger the toggle directly from a browser URL bar with no REST client required. The point this demo is meant to illustrate is the mechanism — that you can expose a runtime configuration toggle with no restart or redeployment — and not the choice of HTTP method.
  2. In our simple demo, these APIs are open to all. In a real-life commercial application, appropriate security measures (such as Spring Security) should be applied to restrict these endpoints to Admin and SRE users only.

Repository with working example

Here is the link to the repository with an out-of-the-box working example: https://github.com/michaelgantman/MgntUtilsUsage

This repo contains a Spring Boot application that uses Logback for logging functionality, which is the Spring Boot default. We recommend you clone the repository and actually run the example. But regardless, let's look at the relevant parts:

How to run the example

  1. Clone the repo from https://github.com/michaelgantman/MgntUtilsUsage, open it in your IDE, and run it.
  2. Once it runs, hit the URL http://localhost:8080/config/log/stacktrace/filter/status to check the current status of the toggle (It is true by default).
  3. Hit the URL http://localhost:8080/log. This URL causes a backend exception with 50% probability. It will either return a message "[Current Timestamp]: No Exception" or "[Current Timestamp]: Exception occurred, check the logs".
  4. If you got "No Exception," re-run the API (refresh your browser) until you get the message "Exception occurred, check the logs". Go to your IDE and see in the console that the exception is indeed printed by the logger and it is cleanly filtered. You will see the following output:
INFO  c.e.s.c.LogFilteringDemoController - Raw Exception:
java.lang.Exception: Demo Exception
at com.example.stamboot.controller.LogFilteringDemoController.callHandler(LogFilteringDemoController.java:49)
at com.example.stamboot.controller.LogFilteringDemoController.logEndPoint(LogFilteringDemoController.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
...

Enter fullscreen mode Exit fullscreen mode

  1. Now run the API http://localhost:8080/config/log/stacktrace?filter=false to switch off the filtering.
  2. Run http://localhost:8080/log again until you get "Exception occurred, check the logs" message. Go back to your IDE and see that the output now is the full "Scroll of Death"
INFO  c.e.s.c.LogFilteringDemoController - Raw Exception:
java.lang.Exception: Demo Exception
at com.example.stamboot.controller.LogFilteringDemoController.callHandler(LogFilteringDemoController.java:49)
at com.example.stamboot.controller.LogFilteringDemoController.logEndPoint(LogFilteringDemoController.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1732)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:750)

Enter fullscreen mode Exit fullscreen mode

Conclusion

As demonstrated in this article, integrating the MgntUtils stacktrace filtering feature at the infrastructure level requires a small one-time effort and results in clean, focused stacktraces across your entire project — without any changes to your application code. Developers on your team will not need to learn any new logging patterns or conventions. The hot runtime toggle provides additional control for Admin and SRE users to manage the feature at runtime without a redeployment. The MgntUtilsUsage repository linked throughout this article contains a fully working example of all of this implemented out of the box.