0

I have a RuntimeException called DuplicateEdgeException which is thrown when the user provides duplicate edges to the graph. And I am not handling this exception and just throwing it when that event occurs.

I am logging the error in the DuplicateEdgeException class as shown below:

import org.apache.logging.log4j.LogManager;

import org.apache.logging.log4j.Logger;

public class DuplicateEdgeException extends RuntimeException {

    static final Logger log = LogManager.getLogger(DuplicateEdgeException.class.getName());
    
    public DuplicateEdgeException(int idx1, int idx2, boolean isDirected) {
        super("Duplicate edge ("+idx1+","+idx2+") provided for "+(!isDirected? "un":"")+"directed graph.");
        log.error("Duplicate edge ("+idx1+","+idx2+") provided for "+(!isDirected? "un":"")+"directed graph.");
    }
    
}

In the log4j2.properties file, I have added a file appender, console appender, and (additivity = false) to the logger that is for the package that contains this DuplicateEdgeException. Also, there is a root-level logger that contains just the console appender. As a result when the exception occurs log message is sent to both the file and the console output. In addition, Java's logging of the exception is also occurring.

My requirement is to allow only the Java's logging of the stack trace to the console output and the logs from log4j2 should occur only to the file for the exceptions. Can anyone please explain how to achieve this and it would be better if I could log the stack trace itself to the log file ?

Also, provide some insights on how to log exceptions in Java using log4j2.

Shri
  • 109
  • 9
  • Your logging should not be mixed into the exception class itself. Keep them separate and use an invocation that logs the stack trace for maximum info. You need to look into 'additivity' / 'additive' – g00se Sep 09 '22 at 07:52

0 Answers0