How to create and graph synthetic metrics in SonarQube

How to create and graph synthetic metrics in SonarQube

The good news is THIS IS EASY

The bad news is "You'll have to write a little Java code"

The silver lining is "We both know a good tool for code metrics" :)

Our home page gives an example of a synthetic metric being graphed - Violations per Thousand lines is not a metric from SonarQube - it's a synthetic metric we created.

Github source code

is how we created it


	public static Map<String,SyntheticMetric> populateSynthetics () {
		Map<String,SyntheticMetric> syntheticMetrics = new HashMap<>();
		
		SyntheticMetric violationsPerKLines = new SyntheticMetric() {
			@Override public String getSyntheicName() { return "ViolationsPerKLines";}
			@Override public List<String> getRealMetrics() { List<String> list = new ArrayList<>();  list.add ("violations");  list.add("lines");  return list;}
			@Override public double calculate(Map<String,Double> metrics) {
				double lines = 0;
				Double lineInput = metrics.get("lines");
				if (lineInput != null) lines = lineInput;
				double violations = 0;
				Double violationsInput = metrics.get("violations");
				if (violationsInput != null) violations = violationsInput;
				if ((lines == 0) || (violations == 0)) return 0.0;
				return (1000.0 * violations) / lines;
			}
		};

		syntheticMetrics.put(violationsPerKLines.getSyntheicName(), violationsPerKLines);
		return syntheticMetrics;
	}

Let's break this violationsPerKLines SyntheticMetric down.

getSyntheticName() returns the synthetic metric's name that you'll reference in your json file.


        {"metric":"ViolationsPerKLines","filename":"SonarViolationsPerThousandLines","title":"Violations Per Thousand Lines"}

getRealMetrics() returns the list of real metrics we need to query from SonarQube. (List.of arrives in Java 9 and we're compatible with Java 8, at least until most teams are at Java 11)

calculate() calculates the number to return.

So to create a new synthetic metric, create a new object that implements the SyntheticMetric interface and add it to the syntheticMetrics list, and your new synthetic metric is good to go! (Please consider a code contribution back to the project - we'll thank you publicly and loudly in Twitter and we'll give your code a code review!)