tags:

views:

49

answers:

2

Hi,

when you write

logger.error("message", exception);

log4j produces the message and the complete stack trace :

Aug  9 06:26:13 10.175.60.14 myPrefix: [error] [TP-Processor114] [my.class.Name] message : exception
at fatherOfException
at fatherof_fatherOfException
at fatherof_fatherof_fatherOfException
...

my conversion pattern is

log4j.appender.syslog.layout.ConversionPattern=myPrefix: [%p] [%t] [%c] [%x] - %m%n

So, is it possible to prefix every line with myPrefix, as :

    Aug  9 06:26:13 10.175.60.14 myPrefix: [error] [TP-Processor114] [my.class.Name] message : exception
myPrefix    at fatherOfException
myPrefix    at fatherof_fatherOfException
myPrefix    at fatherof_fatherof_fatherOfException
    ...

When I grep my logs on myPrefix, i don't see the stack trace. We have many different prefixes (one per module)

Thanks in advance.

+1  A: 

Write a wrapper function to do it for you.

private void writeToLogs(String message, Exception excp) {
    logger.error("myPrefix\t" + message, excp);
}
Mike
Thanks for the tip, but this is not what I'm looking for. 1st, it will do several log instead of one. 2nd, I'm working on a pretty big project and I can't imagine changing every logger.log by something else. Finally, your solution won't prefix the "at" line with the prefix. I am looking for a log4j configuration solution.
Jean-Philippe Caruana
O ok sorry about that. I'm not too familiar with log4j but when I did a quick Google on it I found this, http://logging.apache.org/log4j/1.2/manual.html, you might have already seen it but if you scroll down to Configuration about half way down that might help. Sorry I couldn't help more.
Mike
@Mike no problem !
Jean-Philippe Caruana
+1  A: 

You can write your own implementation of org.apache.log4j.spi.ThrowableRenderer:

http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/spi/ThrowableRenderer.html

Then, edit your log4j configuration:

log4j.throwableRenderer=your-custom-class-name

The ThrowableRenderer returns an array of Strings. Here's your code:

List<String> l = new LinkedList<String>();
for (StackTraceElement ste: t.getStackTrace())
{
    l.add("myPrefix " + ste.toString());
}
return (String[]) l.toArray();
Isaac