Using Java 8 to prevent excessively large logs

Make string manipulation your friend with this latest Java 8 tutorial. Lukas Eder shows us how using the truncate method can help prevent bugs in editors and generally make dev life a little easier.
This post was originally published over at jooq.org, a blog focusing on all things open source, Java and software development from the perspective of jOOQ.
Some logs are there to be consumed by machines and kept forever.
Other logs are there just to debug and to be consumed by humans. In the latter case, you often want to make sure that you don’t produce too much logs, especially not too wide logs, as many editors and other tools have problems once line lengths exceed a certain size (e.g. this Eclipse bug).
String manipulation used to be a major pain in Java, with lots of tedious-to-write loops and branches, etc. No longer with Java 8!
The following truncate
method will truncate all lines within a string to a certain length:
public String truncate(String string) { return truncate(string, 80); } public String truncate(String string, int length) { return Seq.of(string.split("\n")) .map(s -> StringUtils.abbreviate(s, 400)) .join("\n"); }
The above example uses jOOQ 0.9.4 and Apache Commons Lang, but you can achieve the same using vanilla Java 8, of course:
public String truncate(String string) { return truncate(string, 80); } public String truncate(String string, int length) { return Stream.of(string.split("\n")) .map(s -> s.substring(0, Math.min(s.length(), length))) .collect(Collectors.joining("\n")); }
The above when truncating logs to length 10, the above program will produce:
Input
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Output
Lorem ipsum dolor... incididunt ut lab... nostrud exercitat... Duis aute irure d... fugiat nulla pari... culpa qui officia...
Happy logging!