Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions DISCARD_CLASSES_PATTERN_MATCHING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# discardClasses Pattern Matching

The `discardClasses` configuration has been enhanced to support pattern matching using wildcards.

## Features

### Exact Matching (Backward Compatible)
Works exactly as before for exact class names:
```java
config.setDiscardClasses(new String[] {
"com.example.CustomException",
"java.io.IOException"
});
```

### Wildcard Patterns
Now supports glob-style wildcards:

**`*` - Matches any characters (including dots)**
```java
config.setDiscardClasses(new String[] {
"com.example.*" // Matches all classes in com.example package
});
// Matches: com.example.CustomException, com.example.OtherException, etc.
```

**`?` - Matches a single character**
```java
config.setDiscardClasses(new String[] {
"com.example.Exception?"
});
// Matches: com.example.Exception1, com.example.ExceptionX
// Does not match: com.example.Exception, com.example.Exception12
```

### Combined Patterns
Mix exact matches and wildcards:
```java
config.setDiscardClasses(new String[] {
"java.io.*", // All java.io exceptions
"com.*.CustomException", // CustomException in any com.* package
"org.example.SpecificException" // Exact match
});
```

## Appender Compatibility

The BugsnagAppender continues to work exactly as before. When setting discard classes through the appender:

```xml
<appender name="BUGSNAG" class="com.bugsnag.BugsnagAppender">
<discardClasses>com.example.*,java.io.IOException</discardClasses>
</appender>
```

Or programmatically:
```java
appender.setDiscardClass("com.example.*");
appender.setDiscardClass("java.io.IOException");
```

The appender internally converts these to the Configuration's pattern set format.

## Implementation Details

- Patterns without wildcards are treated as exact matches (using `Pattern.quote()` internally)
- Special regex characters are properly escaped
- The `getDiscardClasses()` method returns the original pattern strings (not compiled regex patterns)
- Pattern matching is case-sensitive
- Empty or null patterns are safely ignored
87 changes: 79 additions & 8 deletions bugsnag/src/main/java/com/bugsnag/Configuration.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;

@SuppressWarnings("visibilitymodifier")
public class Configuration {
Expand All @@ -38,7 +38,8 @@ public class Configuration {
private EndpointConfiguration endpoints;
private Delivery sessionDelivery;
private String[] redactedKeys = new String[] {"password", "secret", "Authorization", "Cookie"};
private String[] discardClasses;
private Set<Pattern> discardClasses = new HashSet<Pattern>();
private Set<String> discardClassPatterns = new HashSet<String>();
Comment thread
richardelms marked this conversation as resolved.
Outdated
private Set<String> enabledReleaseStages = null;
private String[] projectPackages;
private String releaseStage;
Expand Down Expand Up @@ -74,12 +75,16 @@ boolean shouldNotifyForReleaseStage() {
}

boolean shouldIgnoreClass(String className) {
if (discardClasses == null) {
if (discardClasses == null || discardClasses.isEmpty()) {
return false;
}

List<String> classes = Arrays.asList(discardClasses);
return classes.contains(className);
for (Pattern pattern : discardClasses) {
if (pattern.matcher(className).matches()) {
return true;
}
}
return false;
}

void addCallback(Callback callback) {
Expand Down Expand Up @@ -253,11 +258,77 @@ public void setRedactedKeys(String[] redactedKeys) {
}

public String[] getDiscardClasses() {
return discardClasses;
return discardClassPatterns.toArray(new String[0]);
}

/**
* Set which exception classes should be ignored (not sent) by Bugsnag.
* Supports glob-style wildcards: * (matches any characters) and ? (matches single character).
Comment thread
richardelms marked this conversation as resolved.
Outdated
*
* @param discardClasses a list of exception class patterns to ignore
*/
public void setDiscardClasses(String[] discardClasses) {
this.discardClasses = discardClasses;
this.discardClasses.clear();
this.discardClassPatterns.clear();
if (discardClasses != null) {
for (String pattern : discardClasses) {
if (pattern != null && !pattern.isEmpty()) {
// Store original pattern string
this.discardClassPatterns.add(pattern);
// Convert glob-style wildcards to regex
String regex = convertToRegex(pattern);
this.discardClasses.add(Pattern.compile(regex));
}
}
}
}

/**
* Converts a glob-style pattern to a regex pattern.
* Supports * (matches any characters) and ? (matches single character).
* If the pattern doesn't contain wildcards, it's treated as an exact match.
*
* @param pattern the glob-style pattern
* @return the regex pattern
*/
private String convertToRegex(String pattern) {
// If the pattern doesn't contain wildcards, match exactly
if (!pattern.contains("*") && !pattern.contains("?")) {
return Pattern.quote(pattern);
}

StringBuilder regex = new StringBuilder();
for (int i = 0; i < pattern.length(); i++) {
char ch = pattern.charAt(i);
switch (ch) {
case '*':
regex.append(".*");
break;
case '?':
regex.append(".");
break;
case '.':
case '(':
case ')':
case '+':
case '|':
case '^':
case '$':
case '@':
case '%':
case '[':
case ']':
case '{':
case '}':
case '\\':
regex.append('\\').append(ch);
break;
default:
regex.append(ch);
break;
}
}
return regex.toString();
}

public Set<String> getEnabledReleaseStages() {
Expand Down
114 changes: 114 additions & 0 deletions bugsnag/src/test/java/com/bugsnag/ConfigurationDiscardClassesTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package com.bugsnag;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Before;
import org.junit.Test;

/**
* Test for Configuration.shouldIgnoreClass with pattern matching
*/
public class ConfigurationDiscardClassesTest {

private Configuration config;

@Before
public void setUp() {
config = new Configuration("test-api-key");
}

@Test
public void testExactMatch() {
config.setDiscardClasses(new String[] {"com.example.CustomException"});

assertTrue(config.shouldIgnoreClass("com.example.CustomException"));
assertFalse(config.shouldIgnoreClass("com.example.OtherException"));
}

@Test
public void testWildcardMatch() {
config.setDiscardClasses(new String[] {"com.example.*"});

assertTrue(config.shouldIgnoreClass("com.example.CustomException"));
assertTrue(config.shouldIgnoreClass("com.example.OtherException"));
assertTrue(config.shouldIgnoreClass("com.example."));
assertFalse(config.shouldIgnoreClass("com.other.Exception"));
}

@Test
public void testMultipleWildcards() {
config.setDiscardClasses(new String[] {"com.*.Exception"});

assertTrue(config.shouldIgnoreClass("com.example.Exception"));
assertTrue(config.shouldIgnoreClass("com.other.Exception"));
assertFalse(config.shouldIgnoreClass("com.example.CustomException"));
}

@Test
public void testQuestionMarkWildcard() {
config.setDiscardClasses(new String[] {"com.example.Exception?"});

assertTrue(config.shouldIgnoreClass("com.example.Exception1"));
assertTrue(config.shouldIgnoreClass("com.example.ExceptionX"));
assertFalse(config.shouldIgnoreClass("com.example.Exception"));
assertFalse(config.shouldIgnoreClass("com.example.Exception12"));
}

@Test
public void testMultiplePatterns() {
config.setDiscardClasses(new String[] {
"java.io.*",
"com.example.CustomException",
"org.*.SpecialException"
});

assertTrue(config.shouldIgnoreClass("java.io.IOException"));
assertTrue(config.shouldIgnoreClass("java.io.FileNotFoundException"));
assertTrue(config.shouldIgnoreClass("com.example.CustomException"));
assertTrue(config.shouldIgnoreClass("org.apache.SpecialException"));
assertTrue(config.shouldIgnoreClass("org.springframework.SpecialException"));
assertFalse(config.shouldIgnoreClass("com.example.OtherException"));
}

@Test
public void testGetDiscardClassesReturnsOriginalPatterns() {
String[] patterns = new String[] {"com.example.*", "java.io.IOException"};
config.setDiscardClasses(patterns);

String[] retrieved = config.getDiscardClasses();
assertEquals(2, retrieved.length);

// Check that patterns are returned (not regex)
boolean hasWildcard = false;
boolean hasExact = false;
for (String pattern : retrieved) {
if (pattern.equals("com.example.*")) {
hasWildcard = true;
}
if (pattern.equals("java.io.IOException")) {
hasExact = true;
}
}
assertTrue(hasWildcard);
assertTrue(hasExact);
}

@Test
public void testEmptyAndNullPatterns() {
config.setDiscardClasses(new String[] {});
assertFalse(config.shouldIgnoreClass("com.example.Exception"));

config.setDiscardClasses(null);
assertFalse(config.shouldIgnoreClass("com.example.Exception"));
}

@Test
public void testSpecialCharactersAreEscaped() {
config.setDiscardClasses(new String[] {"com.example.Exception$Inner"});

assertTrue(config.shouldIgnoreClass("com.example.Exception$Inner"));
assertFalse(config.shouldIgnoreClass("com.example.ExceptionXInner"));
}
}
18 changes: 18 additions & 0 deletions features/fixtures/logback/ignored_class_wildcard_config.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml" />

<appender name="BUGSNAG" class="com.bugsnag.BugsnagAppender">
<apiKey>a35a2a72bd230ac0aa0f52715bbdc6aa</apiKey>
<releaseStage>production</releaseStage>
<appVersion>1.0.0</appVersion>

<discardClass>java.lang.*</discardClass>

<endpoint>http://localhost:9339/notify</endpoint>
</appender>

<root level="INFO">
<appender-ref ref="BUGSNAG"/>
</root>
</configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.bugsnag.mazerunner.scenarios;

import com.bugsnag.Bugsnag;

/**
* Attempts to send ignored handled exceptions using wildcard patterns to Bugsnag,
* which should not result in any operation.
*/
public class IgnoredExceptionWildcardScenario extends Scenario {

public IgnoredExceptionWildcardScenario(Bugsnag bugsnag) {
super(bugsnag);
}

@Override
public void run() {
// Use wildcard pattern to ignore all RuntimeException and its subclasses
bugsnag.setDiscardClasses("java.lang.*");

// These should all be ignored due to the wildcard pattern
bugsnag.notify(new RuntimeException("Should never appear"));
bugsnag.notify(new IllegalArgumentException("Should never appear"));
bugsnag.notify(new IllegalStateException("Should never appear"));

// This should also be sent but will be ignored due to pattern
Comment thread
richardelms marked this conversation as resolved.
Outdated
try {
throw new NullPointerException("Should never appear");
} catch (Exception e) {
bugsnag.notify(e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.bugsnag.mazerunner.scenarios;

import com.bugsnag.Bugsnag;

/**
* Tests multiple wildcard patterns working together.
* Uses both * and ? wildcards along with exact matches.
*/
public class MultipleWildcardPatternsScenario extends Scenario {

public MultipleWildcardPatternsScenario(Bugsnag bugsnag) {
super(bugsnag);
}

@Override
public void run() {
// Set multiple patterns: wildcards and exact matches
bugsnag.setDiscardClasses(
"java.io.*", // All java.io exceptions
"java.lang.IllegalStateException", // Exact match
"java.lang.Illegal*" // All IllegalXException classes
);

// These should all be ignored
bugsnag.notify(new java.io.IOException("Should be ignored - java.io.*"));
bugsnag.notify(new java.io.FileNotFoundException("Should be ignored - java.io.*"));
bugsnag.notify(new IllegalStateException("Should be ignored - exact match"));
bugsnag.notify(new IllegalArgumentException("Should be ignored - java.lang.Illegal*"));

// This should be sent (not matching any pattern)
bugsnag.notify(new RuntimeException("Should be sent"));
}
}
Loading