Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert e.printStackTrace() to use log4j instead

Tags:

java

log4j

I am very new to log4j. I do not want to show exception stack trace in my log file such as

java.lang.IllegalArgumentException: nodeRef is a mandatory parameter
at org.alfresco.util.ParameterCheck.mandatory(ParameterCheck.java:42)

These exceptions are written directly to console by using e.printStackTrace() like that

try {
    // something
} catch(Exception e) {
    StringWriter stack = new StringWriter();
    e.printStackTrace(new PrintWriter(stack));
    logger.debug("Caught exception; decorating with appropriate status template : " + stack.toString());
}

I am now customizing a Open Source project, not writing all my programs by myself. So it is impossible to remove e.printStackTrace(); in all of java files.

As far as I know, log which are printed by log4j with logger can be configured by using log4j error level such as info, debug, warn.But how about writing directly to console or file?

How can I configure log4j not to print only exception stacktrace but show other information? Is there a way to solve it out?

like image 526
swemon Avatar asked Aug 30 '12 11:08

swemon


2 Answers

The code

StringWriter stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
logger.debug("Caught exception; decorating with appropriate status template : " + stack.toString());

is just an example of plain wrong usage of the Log4j API. But, if you are stuck with it, there will be nothing for you to do except raise the log level above debug and leave out the entire message.

There may possibly be a way to truncate all log messages, which would somewhat alleviate your problem.

like image 96
Marko Topolnik Avatar answered Nov 11 '22 08:11

Marko Topolnik


Use Logger#error

import org.apache.log4j.Logger;

...

Logger log = Logger.getLogger(Locomotive.class);
log.error("your message", exc);

...
like image 43
ollins Avatar answered Nov 11 '22 08:11

ollins