ybc126
ybc126

Reputation: 3059

Create log file for Java program

I have a java program for which I created batch file to schedule it after some period to run. I want to generate log file for that program whenever it get loaded, that log file must contain date time and error if any thrown.

How to create log file for Java program?

Upvotes: 0

Views: 30994

Answers (7)

digolloco
digolloco

Reputation: 101

A simple form to create a Log and writes it to a file:

Logger logger = Logger.getLogger(MyClass.class.getName());
FileHandler fileLog = new FileHandler("mylog.log");
logger.addHandler(fileLog);

Then you can use as a normal Logger:

logger.log(Level.INFO, "my log line");
logger.log(Level.WARNING, "ATTENTION warning line");

You can visit this link for more info: http://www.vogella.com/tutorials/Logging/article.html

Upvotes: 0

blackhalo1989
blackhalo1989

Reputation: 31

You have multiple choices:

  • Using command line redirection operators.
  • Use I/O system and manually write to a file.
  • Use log4j
  • Use java.util.logging

Upvotes: 1

Duane
Duane

Reputation: 1990

I've played around with basically the same idea as Marc. Just something simple you could look at for inspiration.

here

Upvotes: 1

marc wellman
marc wellman

Reputation: 5886

Create a new file on the file system withe the FileWriter class and then initiate an I/O stream with BufferedWriter to write into this file:

// create a new file with specified file name
FileWriter fw = new FileWriter("myFile.log");

// create the IO strem on that file
BufferedWriter bw = new BufferedWriter(fw);

// write a string into the IO stream
bw.out("my log entry");

// don't forget to close the stream!
bw.close();

The whole thing must be surrounded with a try/catch in order to catch IO Exception.

Hope this helps.

Upvotes: 1

Autar
Autar

Reputation: 1589

If you need something more complex, see Java documentation for Logging.

Upvotes: 0

manurajhada
manurajhada

Reputation: 5380

Do Study about log4j logger, implement its configurations.

Upvotes: 1

Nick Garvey
Nick Garvey

Reputation: 3000

If your needs are that simple, you can most likely do the logging in the batch file itself.

Do something like the following

date /t >> log_file_path
time /t >> log_file_path
echo Starting execution >> log_file_path
java -jar your_java_app 2>> log_file_path
echo Finished execution >> log_file_path 

The 2>> log_file_path means append the standard error stream to your log file, which will include any uncaught exceptions.

Upvotes: 2

Related Questions