0

In my java code, when an exception occurs, I want to print my specified message to the console and write its stack trace to the log file at the same time. How can I do it? What I want to do is like following;

    try {
        //do something
    } catch (Exception e) {
        logger.error("Exception occured."); //print console "Exception occured
        logger.error("Exception occured", e); //write entire stack trace to log file
    }
  • Maybe this will help: It prints in two different files - an error file and regular file https://stackoverflow.com/a/48363934/1235935 – Saptarshi Basu Jan 15 '19 at 16:39

1 Answers1

0

You have to configure 2 distinct appenders : one for the console output and another for the log file output.
slf4j is an abstraction, not an implementation. So it doesn't provide specific appenders.

You could use logback or log4j2 as implementations. These provide appenders that you are looking for :

LogBack appenders.

Log4J2 appenders

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • I see your point but after your answer I edited my question to avoid misunderstanding. Probably, you mean specifiying multiple appenders in configuration file xml but for the code level I didn't get your point. Could you look my edited question @davidxxx ? – Peanutbutter Jan 15 '19 at 20:30