Search code examples
javaplaywright

Java: How to print log before and after a method invocation?


I am writing an application in Java using the playwright library. I've created some static methods, like performBankAccountDetail, that executes a certain navigation or just invokes some methods of the object "page".

 Page page = context.newPage();
 System.out.println("[+] - Account detail (start) "+dtf.format(now));
 HomePage.performBankAccountDetail(page);
 System.out.println("[+] - Account detail (end) "+dtf.format(now));

 System.out.println("[+] - Documents detail (start) "+dtf.format(now));
 DocumentsSequence.documentsVisualization(page);
 System.out.println("[+] - Documents detail (end) "+dtf.format(now));

On every invocation of performBankAccountDetail I have to print the time and date before and after the invocation.

In my code those two lines (print before and after) are repeated for several actions.

With this method I am repeating the same code except for a string. What is the best method to reduce the number of lines of same code in the described scenario?


Solution

  • If I understand your question correctly, you basically want aspect-oriented programming (for example a framework such as AspectJ). If you feel such a framework would be too heavy for your need, you can easily write such functionality for yourself using lambda's.

    Something like this:

    package com.myapp.aspect;
    
    import java.util.function.Supplier;
    
    public class MiniWrapper {
    
        public static void wrap(Runnable function) {
            System.out.println("Before invocation");
            function.run();
            System.out.println("After invocation");
        }
    
    
        public static <T> T wrap(Supplier<T> function) {
            System.out.println("Before invocation");
            T result = function.get();
            System.out.println("After invocation");
            return result;
        }
    }
    

    You can then use above class as follows:

    package com.myapp;
    
    import static com.myapp.aspect.MiniWrapper.*;
    
    public class TestSO {
    
        public static void main(String[] args) {
            wrap(TestSO::someMethod);
            wrap(() -> someOtherMethod("Hello"));
            wrap(() -> someOtherMethod("Who are you?"));
            String result = wrap(()-> concatter("1","2","3"));
            System.out.println(result);
        }
    
        public static void someMethod() {
            System.out.println("Hello method!");
        }
    
        public static void someOtherMethod(String param) {
            System.out.println("Some Other method with param: " + param );
        }
    
        public static String concatter(String first, String second, String third) {
            return first + second + third;
        }
    }
    

    I think using a decent library would be the better way going forward.