Question

I've made an application and exported it as jar file.

If the jar-application crashes for some reason I want it to generate a crash-log text file with the error.

If I run the application in Eclipse, then eclipse always tells me where it crashed, can I get the same kind of message in a text-file instead when running the application as a jar?

I run my jar-file by typing this: java -jar MyApplication.jar

Can I add something to this command in order to generate a crash-log if a crash occurs?

Thanks!

Was it helpful?

Solution

I used this solution in the end, which works exactly like I want it to. Everytime the application crashes it saves the exception in a text file in a subfolder named "crashlogs" with the date and time as filename.

Just added this code at the start of my main function

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");

        String filename = "crashlogs/"+sdf.format(cal.getTime())+".txt";

        PrintStream writer;
        try {
            writer = new PrintStream(filename, "UTF-8");
            writer.println(e.getClass() + ": " + e.getMessage());
            for (int i = 0; i < e.getStackTrace().length; i++) {
                writer.println(e.getStackTrace()[i].toString());
            }

        } catch (FileNotFoundException | UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    }
});

OTHER TIPS

you can use logging framework like log4j

simple example Java

import org.apache.log4j.Logger;

import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class log4jExample{
  /* Get actual class name to be printed on */
  static Logger log = Logger.getLogger(
                      log4jExample.class.getName());

  public static void main(String[] args)
                throws IOException,SQLException{

     log.debug("Hello this is an debug message");
     log.info("Hello this is an info message");
  }
}

log4j.properties

# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n

If you want to do it without loging

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top