Use the structural search function of Intellij IDEA to smart replace

I've had to migrate an old Java project that wasn't using any log framework to Log4J. I'll describe my Log4J/Slf4J configuration in another post. This post is just to describe how the Structural Search dialog can help you easily find and replace references in your code.

As always this is just a simple example of my personal use case, you can find a complete description of the functionality in the Intellij documentation

The existing statements

My project was full of basic java log statement and stackStraces.

System.out.println("This is an important info!");
...
} catch (Exception e) {
	e.printStackTrace();
	throw e;
}
...

As you can imagine the variable e here can be named anything. This is where the Structural Search can be helpful.

Replacement

We want to replace all printStackTrace with a simple:

log.error(e.getMessage(), e);

replace-exceptions

We simple identify the variables exceptions with: $exception$.printStackTrace(); and replace it by log.error($exception$.getMessage(), $exception$); using the $exception$ variable we defined in the search template.

Add a logger statement in all classes

I'm using Lombok to add a logger at compilation time using https://projectlombok.org/features/log

So I need to add an annotation @Slf4j at to all classes.

structural-search-dialog

I'm using the variables:

And I replace the variable $Slf4j$ with @Slf4J, Intellij will automatically add the missing import and reformat the code.

You can then click the Find button and you will see in a new Find tab a list of all occurences.

You can then decide to Replace All of go one by one. You can even preview the replacement before it occurs:

structural-replacement-preview

structural-replacement-done

← Back to home