Skip to content

Commit

Permalink
Fix parsing key-values from prefixed log lines
Browse files Browse the repository at this point in the history
Another silly error, this time forgetting that I was still requesting
logcat lines with the default prefixes, ie the stuff before the opening
brace here:

D/screenshot_request(26711): {name=beta}
  • Loading branch information
rtyley committed Feb 28, 2012
1 parent 59b5c0b commit 5364150
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class OnDemandScreenshotService {

Expand Down Expand Up @@ -124,19 +126,27 @@ private void takeScreenshotFor(String logLine) {
}
}

private static final Pattern KEY_VALUE_HOLDER_PATTERN = Pattern.compile("\\{(.*)\\}$");

/**
* Parse the logline into key-value pairs. The logline format is comma-separated
* key-value pairs surrounded by curly braces, ie:
*
* {foo=bar,name=ARandomName}
*
* The logline can also be prefixed with data like '02-28 11:37:49.629 D/screenshot_request(26711): '
* depending on what you pass to the '-v' logcat option
*/
static Map<String, String> keyValueMapFor(String logLine) {
Map<String, String> keyValueMap = new HashMap<String, String>();
if (logLine.startsWith("{") && logLine.endsWith("}")) {
for (String keyValuePair : logLine.substring(1, logLine.length()-1).split(",")) {
Matcher matcher = KEY_VALUE_HOLDER_PATTERN.matcher(logLine);
if (matcher.find()) {
for (String keyValuePair : matcher.group(1).split(",")) {
int separatorIndex = keyValuePair.indexOf("=");
if (separatorIndex > 0) {
keyValueMap.put(keyValuePair.substring(0, separatorIndex), keyValuePair.substring(separatorIndex+1));
String key = keyValuePair.substring(0, separatorIndex);
String value = keyValuePair.substring(separatorIndex + 1);
keyValueMap.put(key, value);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@

public class OnDemandScreenshotServiceTest {

@Test
public void shouldParseLogLineWithPrefixFields() {
assertThat(keyValueMapFor("02-28 11:37:49.629 D/screenshot_request(26711): {name=beta}"),
IsMap.containingOnly("name", "beta"));
}

@Test
public void shouldParseLogLineWithKeyValue() {
assertThat(keyValueMapFor("{name=ConfigureMorseActivity-SOS}"),
Expand Down

0 comments on commit 5364150

Please sign in to comment.