0

I want to write the exceptions that appear in a file. I'm using the mylogger class. The problem is that every time i run the app and an exception is caught the other exceptions are deleted from the file.

here is the mylogger class

public class MyLogger {

static private FileHandler fileTxt;

static private SimpleFormatter formatterTxt;

private Logger logger;

public void setup() throws IOException {
    logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);

    logger.setLevel(Level.INFO);

    fileTxt = new FileHandler("Logging.txt");

    // create a TXT formatter
    formatterTxt = new SimpleFormatter();
    fileTxt.setFormatter(formatterTxt);

    logger.addHandler(fileTxt);
}

public void log(Exception e) {
    logger.info("test");
}

public void logClientReporting(String string) {
    // TODO Auto-generated method stub
    logger.info(string);
}

public void logSocket(String string) {
    // TODO Auto-generated method stub
    logger.info(string);
}
}

I call setup in the main class.

Here is how i call the log methods:

catch (Exception e) {
        // TODO: handle exception
        System.err.println("JSON Exception in getAvailableDesings");
        logger.logSocket(e.toString());
    }
2
  • 1
    Have you tried new FileHandler("Logging.txt", true); ? IIRC, the default for append is false, could be wrong, though. Commented Aug 19, 2015 at 9:53
  • that worked. Thank's Commented Aug 19, 2015 at 11:02

1 Answer 1

1

I think the problem is in the constructor used in initializing FileHandler. FileHandler has multiple constructors, one of them takes a second argument a boolean called append, which should be true to append new logs not overwrite them. so it should be:

fileTxt = new FileHandler("Logging.txt", true);

And a quick advice if I may, use logging libraries and don't try to rewrite things. I recommend apache log4j2, or slf4j which gives you great options for logging. you define the pattern, what format to print (like date in the beginning of the log for example), time/file size constraints, when to roll over files again and many other options.

Sign up to request clarification or add additional context in comments.

1 Comment

Of course, yes, I would also suggest using Log4j2, which probably has more features than you'll ever need. SLF4J is just a logging facade, which is nice for frameworks, etc. but probably overkill for clearly defined projects that will not have to cope with changing environments, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.