Using getAppender() in Logback

那年仲夏 提交于 2019-12-11 06:28:26

问题


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.


回答1:


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();




回答2:


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")


来源:https://stackoverflow.com/questions/11471202/using-getappender-in-logback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!