I want to log data in a file which is displayed on java console when I run .jar file

980 views Asked by At

I have a .jar file I am executing that with java -jar file_name.jar.

Then the program outputs to the IDE console, a prompt asking the user for credentials. After authenticating, the program prints database data to the console.

How can I redirect the console data output to a filestream?

I tried adding logger while executing the command java -jar file_name.jar. But no success.

I am not a java person, so I don't have any idea how to do that. Any suggestion or help will be great.

EDIT

Screenshot addded for the GUI screen enter image description here

2

There are 2 answers

7
aurelius On

if it's from java console:

java -jar class.jar <someFile.file> 1>> log.txt
1
aurelius On

since you said that you have access to the jar's sources then the simplest way you can just add the following at startup class:

import java.util.logging.Logger;

Handler handler = new FileHandler("test.log", LOG_SIZE, LOG_ROTATION_COUNT);
Logger logger = Logger.getLogger("MyLogger").addHandler(handler);

and with logger you log what you log in the console.

You can specify your own values for LOG_SIZE and LOG_ROTATION_COUNT

You may, if you want, adjust the logging level to suit.