1

I have a small java program which asks the user to input two dates. I want to package this whole program into a jar file. when I try to execute the jar file via command line and redirecting the output to a log file( like this: java -jar Sample.jar >> Sample.log), all the System.out.println statements and log statements are printed to the external file, not on console. I want to see the System.out.println statements printed on the console and log4j log statements in the external file even if the user redirects the output to log file. Please note that I have set the log4j appender to 'Console'. Any idea on how to do that?

The sample program is below:

public class Sample {

public static void main(String[] arg) {
        logger.debug("start of the main method");
        Scanner in = new Scanner(System.in);
        System.out.println("Please enter start date in the format YYYY-MM-DD");
        String startDate = in.nextLine();
        logger.debug("The entered start date is " + startDate);
        System.out.println("Please enter end date in the format YYYY-MM-DD");
        logger.debug("The entered end date is " + endDate);

    }
}
Tanveer Munir
  • 1,956
  • 1
  • 12
  • 27
Ashok.N
  • 1,327
  • 9
  • 29
  • 64
  • _even if the user redirects the output to log file_ What difference does it make to you if the user decides to redirect the console output when she runs your program? – Abra Mar 13 '19 at 11:06
  • @Abra Yep, it makes sense to me as the user should be asked to enter the dates on the console it self. The dates any way should be entered on the console, not in the file. – Ashok.N Mar 13 '19 at 11:24
  • I believe there is a difference between redirecting standard **output** and redirecting standard **input**. When I write a java application that requires user input, I usually provide a GUI. – Abra Mar 13 '19 at 11:29

1 Answers1

1

Instead of the >> you can use the approach described in this answer. So instead of:

java -jar Sample.jar >> Sample.log

... you could do:

java -jar Sample.jar | tee -a Sample.log

For Windows you can try to use something from: this question or this one

tee can be accessed using using Windows PowerShell. This can be opened from start menu.

This question really helped me in finding a way to access tee command

Ashok.N
  • 1,327
  • 9
  • 29
  • 64
kasptom
  • 2,363
  • 2
  • 16
  • 20
  • `tee` is not available by default. I've linked some other answers related to the Windows – kasptom Mar 13 '19 at 11:20
  • 1
    Your answer helped me a bit to research further on this. I will edit your answer with my findings. Plus one for the answer. Thanks – Ashok.N Mar 13 '19 at 11:39
  • 1
    tee can be accessed using using Windows PowerShell. This can be opened from start menu. – Ashok.N Mar 13 '19 at 12:17