Using getAppender() in Logback

2019-08-13 13:03发布

I wrote a custom appender JTableAppender which implements ILoggingEvent. This appender has a public setter setModel(..) to assign a table model to the appender, so I can manipulate the model in doAppend().

The JTableAppender is configurated in an xml file, where I named it TABLE:

<appender name="TABLE" class="blabla.jgwf.test.logger.JTableAppender">
    <!-- encoders are by default assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
    <encoder> 
        <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
        </pattern>
    </encoder>
</appender>

To be able to use the setter from the outside, I tried to get the appender using

Logger logger = (Logger) LoggerFactory.getLogger("blabal");
JTableAppender<ILoggingEvent> appender = (JTableAppender<ILoggingEvent>)logger.getAppender("TABLE");

When I tried to set a model using

appender.setModel(...);

I got a NullPointerException for exactly this line. The getAppender() didn't work as I wish it would.

2条回答
\"骚年 ilove
2楼-- · 2019-08-13 13:20

SOLVED: Use Logger.getRootLogger() instead your local variable 'logger'.

(example)

SMTPAppender emailAppender = 
(SMTPAppender)Logger.getRootLogger().getAppender("SMTPAppender");

doing this, you wont get NullException, and to APPLY changes on your appender then you have to write this: emailAppender.activateOptions();

查看更多
Viruses.
3楼-- · 2019-08-13 13:25

using logback 1.1.3 I had to:

import ch.qos.logback.classic.Logger
import org.slf4j.LoggerFactory    
...
val root: Logger = val root: Logger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME).asInstanceOf[Logger]
val myAppender = root.getAppender("MyAppenderName")
查看更多
登录 后发表回答