下面列出了org.slf4j.ILoggerFactory#ch.qos.logback.core.joran.spi.JoranException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void overrideLoggingConfig() {
URL logbackFile = ITestApplication.class.getResource("/spring-logback.xml");
if (logbackFile != null) {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
// Call context.reset() to clear any previous configuration, e.g. default
// configuration. For multi-step configuration, omit calling context.reset().
context.reset();
configurator.doConfigure(logbackFile);
} catch (JoranException je) {
// StatusPrinter will handle this
}
StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
}
private void init() {
// Assumes LSF4J is bound to logback
context = (LoggerContext) LoggerFactory.getILoggerFactory();
// store the home dir to use for relative paths
context.putProperty("stash.home", homeDir);
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
InputStream is;
is = this.getClass().getClassLoader().getResourceAsStream("logback-test.xml");
if (is != null) {
stashRootLogger.info("Using logback-test.xml for logger settings");
} else {
stashRootLogger.info("Using logback.xml for logger settings");
is = this.getClass().getClassLoader().getResourceAsStream("logback.xml");
}
try {
configurator.doConfigure(is);
} catch (JoranException e) {
System.err.println("Error configuring logging framework" + e);
}
stashRootLogger.info("Logger using stash.home of " + homeDir);
}
public static void loadFileConfig(String configFilePath) throws IOException, JoranException {
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
File externalConfigFile = new File(configFilePath);
if (!externalConfigFile.isFile()) {
throw new IOException("logback config file not exists. configFilePath = " + configFilePath);
}
if (!externalConfigFile.canRead()) {
throw new IOException("logback config file cannot be read. configFilePath = " + configFilePath);
}
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(configFilePath);
StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
}
/**
* @return The list of log levels configured and their settings
*/
@RequestMapping(value = "reset", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<LogResponse> reset() {
final LoggerContext ctx = (LoggerContext) LoggerFactory.getILoggerFactory();
synchronized (ctx) {
File configuration = ConfigurationWatchListUtil.getConfigurationWatchList(ctx).getCopyOfFileWatchList().get(0);
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(ctx);
ctx.reset();
try {
configurator.doConfigure(configuration);
} catch (JoranException e) {
log.error("Error re-applying the configuration");
}
}
return new ResponseEntity<>(listLoggers(ctx), HttpStatus.OK);
}
public void autoConfig() throws JoranException ,IOException{
StatusListenerConfigHelper.installIfAsked(loggerContext);
URL url = findURLOfDefaultConfigurationFile(true);
if (url != null) {
configureByResource(url);
} else {
Configurator c = EnvUtil.loadFromServiceLoader(Configurator.class);
if (c != null) {
try {
c.setContext(loggerContext);
c.configure(loggerContext);
} catch (Exception e) {
throw new LogbackException(String.format("Failed to initialize Configurator: %s using ServiceLoader", c != null ? c.getClass()
.getCanonicalName() : "null"), e);
}
} else {
BasicConfigurator basicConfigurator = new BasicConfigurator();
basicConfigurator.setContext(loggerContext);
basicConfigurator.configure(loggerContext);
}
}
}
@Test
public void testIndependentSpaceLogback() throws JoranException {
URL url1 = LogbackTest.class.getResource("/com/alipay/sofa/rpc/log/logback/log-conf.xml");
LoggerContext loggerContext1 = new LoggerContext();
new ContextInitializer(loggerContext1).configureByResource(url1);
ch.qos.logback.classic.Logger logger1 = loggerContext1.getLogger("com.foo.Bar");
logger1.info("log4j2 - 1");
Assert.assertNotNull(logger1);
//logback logger 2
URL url2 = LogbackTest.class.getResource("/com/alipay/sofa/rpc/log/logback/logback_b.xml");
LoggerContext loggerContext2 = new LoggerContext();
new ContextInitializer(loggerContext2).configureByResource(url2);
Logger logger2 = loggerContext2.getLogger("com.foo.Bar2");
logger2.info("log4j2 - 222");
Assert.assertNotNull(logger2);
Assert.assertNotSame(logger1, logger2);
}
public static void initLog() {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator jc = new JoranConfigurator();
jc.setContext(context);
context.reset();
String env = System.getProperty("system.environment");
if(StringUtils.isBlank(env)) {
System.err.println("get system.environment error");
throw new RuntimeException("can't get env, service stop!");
}
URL tmpConfigFIleStr = Startup.class.getResource("/logback-" + env + ".xml");
try {
System.out.println("start with configFile : " + tmpConfigFIleStr);
jc.doConfigure(tmpConfigFIleStr);
log.info("load logback config --> " + tmpConfigFIleStr.getFile());
} catch (JoranException e) {
System.err.println(tmpConfigFIleStr + " not exist");
throw new RuntimeException(e);
}
}
/**
* Initialize LOGBack from the given URL.
*
* @param url the url pointing to the location of the config file.
* @param installJULBridge set to true to install SLF4J JUL bridge
* @throws IllegalArgumentException if the url points to a non existing location or an error occurs during the parsing operation.
*/
public static void initLogging(URL url, boolean installJULBridge) {
StaticLoggerBinder.getSingleton();
ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector();
LoggerContext loggerContext = selector.getLoggerContext();
loggerContext.stop();
ContextInitializer ctxi = new ContextInitializer(loggerContext);
try {
ctxi.configureByResource(url);
loggerContext.start();
if (installJULBridge) {
//uninstall already present handlers we want to
//continue logging through SLF4J after this point
Logger l = LogManager.getLogManager().getLogger("");
for (Handler h : l.getHandlers()) {
l.removeHandler(h);
}
SLF4JBridgeHandler.install();
}
} catch (JoranException e) {
throw new IllegalArgumentException("exception while initializing LOGBack", e);
}
}
private static void setupLogback() {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
Logger.info("Setting up Logback");
Logger.info("Application running from: {}", Start.getApplicationDirectory().getAbsolutePath());
System.setProperty("application.home", Start.getApplicationDirectory().getAbsolutePath());
File xmlConfig = new File(new File(Start.getApplicationDirectory(), "conf"), "application-logger.xml");
if (xmlConfig.exists()) {
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
context.reset();
configurator.doConfigure(xmlConfig);
} catch (JoranException je) {
// StatusPrinter will handle this
}
}
//System.setOut(new PrintStream(new LoggerOutputStream(Level.INFO, Logger.underlying()), true));
System.setErr(new PrintStream(new LoggerOutputStream(Level.OFF, Logger.underlying()), true));
Logger.info("Logback Setup");
StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
public static void load() throws JoranException {
final String s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<configuration debug=\"true\">\n" +
"\t<appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAppender\">\n" +
"\t\t<encoder>\n" +
"\t\t\t<charset>UTF-8</charset>\n" +
"\t\t\t<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>\n" +
"\t\t</encoder>\n" +
"\t</appender>\n" +
"\t<root level=\"INFO\">\n" +
"\t\t<appender-ref ref=\"STDOUT\"/>\n" +
"\t</root>\n" +
"</configuration>";
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(new ByteArrayInputStream(s.getBytes(Charset.forName("UTF-8"))));
StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
}
public void autoConfig() throws JoranException {
KonkerStatusListenerConfigHelper.installIfAsked(this.loggerContext);
URL url = this.findURLOfDefaultConfigurationFile(true);
if (url != null) {
this.configureByResource(url);
} else {
KonkerLoggerConfigurator c = (KonkerLoggerConfigurator)
EnvUtil.loadFromServiceLoader(KonkerLoggerConfigurator.class);
if (c != null) {
try {
c.setContext(this.loggerContext);
c.configure(this.loggerContext);
} catch (Exception var4) {
throw new LogbackException(String.format("Failed to initialize Configurator: %s using ServiceLoader", new Object[]{c != null ? c.getClass().getCanonicalName() : "null"}), var4);
}
} else {
KonkerLoggerBasicConfigurator.configure(this.loggerContext);
}
}
}
private void configureLogger() throws MalformedURLException, JoranException {
// Check if SLF4J is bound to logback in the current environment
ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
if (!(loggerFactory instanceof LoggerContext)) {
return;
}
LoggerContext context = (LoggerContext) loggerFactory;
ContextInitializer contextInitializer = new ContextInitializer(context);
URL url = contextInitializer.findURLOfDefaultConfigurationFile(false);
if (url == null) {
// The logger context was not initialized using configuration file, initialize it with the logback template.
File twillLogback = new File(Constants.Files.RUNTIME_CONFIG_JAR, Constants.Files.LOGBACK_TEMPLATE);
if (twillLogback.exists()) {
contextInitializer.configureByResource(twillLogback.toURI().toURL());
}
}
KafkaAppender kafkaAppender = getKafkaAppender(context);
kafkaAppender.start();
// Attach the KafkaAppender to the root logger
context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME).addAppender(kafkaAppender);
}
private void initializeLogback() {
Path logbackFilePath = Paths.get(configPath, "logback.xml");
if (logbackFilePath.toFile().exists()) {
try {
// Load logback configuration
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
context.reset();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
configurator.doConfigure(logbackFilePath.toFile());
// Install java.util.logging bridge
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
} catch (JoranException e) {
throw new GossipInitializeException("Misconfiguration on logback.xml, check it.", e);
}
}
}
private static void configureLogger(String logDir, String logLevel, String logbackConf) {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
context.reset();
if (!logDir.endsWith(File.separator))
logDir+= File.separator;
context.putProperty("LOG_DIR", logDir);
context.putProperty("LOG_LEVEL", logLevel);
InputStream is = classloader.getResourceAsStream(logbackConf);
configurator.doConfigure(is);
} catch (JoranException je) {
LOG.warn("Cannot configure logger. Continue to execute the command.", je);
}
StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
final String settings = environment.getProperty("logging.config.src");
if (StringUtils.hasText(settings)) {
try {
final ContextBase context = (ContextBase) StaticLoggerBinder.getSingleton().getLoggerFactory();
final JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
LOG.info("try to update logback configuration to {}", settings);
context.reset();
configurator.doConfigure(new ByteArrayInputStream(settings.getBytes()));
} catch (JoranException e) {
LOG.error("can't load settings", e);
}
}
}
public void testTlsSender() throws JoranException, InterruptedException {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
context.reset();
configurator.doConfigure(this.getClass().getClassLoader().getResourceAsStream("logback-syslog4j-tls.xml"));
Logger logger = context.getLogger("test-tls");
logger.info("test message over tls");
context.stop();
Thread.sleep(100);
final String serverData = serverStream.toString();
assertTrue("Server received: " + serverData, serverData.contains("test message over tls"));
}
/**
* Reloads logging.
*
* @param logbackConfig XML containing the logback configuration
*/
public void reloadLogging(String logbackConfig) {
LoggerContext logContext = (LoggerContext) LoggerFactory.getILoggerFactory();
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(logContext);
logContext.reset();
configurator.doConfigure(new ByteArrayInputStream(logbackConfig.getBytes(Charsets.UTF_8)));
} catch (JoranException je) {
// StatusPrinter will handle this
} catch (Exception ex) {
ex.printStackTrace(); // Just in case, so we see a stacktrace
}
StatusPrinter.printInCaseOfErrorsOrWarnings(logContext);
applicationContext.publishEvent(new LoggingReloadedApplicationEvent(this));
}
/**
* Tests a Logback-access configuration exception in the case where the configuration file is invalid.
*/
@Test
public void logbackAccessConfigurationExceptionWhereConfigurationFileIsInvalid() {
Map<String, Object> properties = new HashMap<>();
properties.put("server.port", findAvailableTcpPort());
properties.put("logback.access.config", "classpath:logback-access.invalid.xml");
SpringApplication application = new SpringApplication(contextConfiguration);
application.setDefaultProperties(properties);
Throwable throwable = catchThrowable(application::run);
Optional<LogbackAccessConfigurationException> exc = findLogbackAccessConfigurationException(throwable);
assertThat(exc).hasValueSatisfying(value ->
assertThat(value)
.hasMessageStartingWith("Could not configure Logback-access:")
.hasMessageContaining("config=[classpath:logback-access.invalid.xml]")
.hasCauseInstanceOf(JoranException.class)
);
}
/**
* Tests a Logback-access configuration exception in the case where the test spring configuration file is invalid.
*/
@Test
public void logbackAccessConfigurationExceptionWhereTestSpringConfigurationFileIsInvalid() {
Map<String, Object> properties = new HashMap<>();
properties.put("server.port", findAvailableTcpPort());
SpringApplication application = new SpringApplication(contextConfiguration);
application.setDefaultProperties(properties);
Throwable throwable = catchThrowable(application::run);
Optional<LogbackAccessConfigurationException> exc = findLogbackAccessConfigurationException(throwable);
assertThat(exc).hasValueSatisfying(value ->
assertThat(value)
.hasMessageStartingWith("Could not configure Logback-access:")
.hasMessageContaining("config=[classpath:logback-access-test-spring.xml]")
.hasCauseInstanceOf(JoranException.class)
);
}
/**
* Tests a Logback-access configuration exception in the case where the main configuration file is invalid.
*/
@Test
public void logbackAccessConfigurationExceptionWhereMainConfigurationFileIsInvalid() {
Map<String, Object> properties = new HashMap<>();
properties.put("server.port", findAvailableTcpPort());
SpringApplication application = new SpringApplication(contextConfiguration);
application.setDefaultProperties(properties);
Throwable throwable = catchThrowable(application::run);
Optional<LogbackAccessConfigurationException> exc = findLogbackAccessConfigurationException(throwable);
assertThat(exc).hasValueSatisfying(value ->
assertThat(value)
.hasMessageStartingWith("Could not configure Logback-access:")
.hasMessageContaining("config=[classpath:logback-access.xml]")
.hasCauseInstanceOf(JoranException.class)
);
}
/**
* Tests a Logback-access configuration exception in the case where the main spring configuration file is invalid.
*/
@Test
public void logbackAccessConfigurationExceptionWhereMainSpringConfigurationFileIsInvalid() {
Map<String, Object> properties = new HashMap<>();
properties.put("server.port", findAvailableTcpPort());
SpringApplication application = new SpringApplication(contextConfiguration);
application.setDefaultProperties(properties);
Throwable throwable = catchThrowable(application::run);
Optional<LogbackAccessConfigurationException> exc = findLogbackAccessConfigurationException(throwable);
assertThat(exc).hasValueSatisfying(value ->
assertThat(value)
.hasMessageStartingWith("Could not configure Logback-access:")
.hasMessageContaining("config=[classpath:logback-access-spring.xml]")
.hasCauseInstanceOf(JoranException.class)
);
}
@Override
public void contextInitialized(ServletContextEvent event) {
// 从web.xml中加载指定文件名的日志配置文件
String logbackConfigLocation = event.getServletContext().getInitParameter(CONFIG_LOCATION);
InputStream fn = event.getClass().getClassLoader().getResourceAsStream(logbackConfigLocation);
if (fn == null) {
return;
}
try {
LoggerContext loggerContext = (LoggerContext) org.slf4j.LoggerFactory.getILoggerFactory();
loggerContext.reset();
JoranConfigurator joranConfigurator = new JoranConfigurator();
joranConfigurator.setContext(loggerContext);
joranConfigurator.doConfigure(fn);
logger.debug("loaded slf4j configure file from " + fn);
} catch (JoranException e) {
logger.error("can loading slf4j configure file from " + fn, e);
}
}
public void testUdpSender() throws JoranException, InterruptedException {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
context.reset();
configurator.doConfigure(this.getClass().getClassLoader().getResourceAsStream("logback-syslog4j-udp.xml"));
Logger logger = context.getLogger("test-udp");
logger.info("test message over udp");
context.stop();
Thread.sleep(100);
final String serverData = serverStream.toString();
assertTrue("Server received: " + serverData, serverData.contains("test message over udp"));
}
public void testTcpSender() throws JoranException, InterruptedException {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
context.reset();
configurator.doConfigure(this.getClass().getClassLoader().getResourceAsStream("logback-syslog4j-tcp.xml"));
Logger logger = context.getLogger("test-tcp");
logger.info("test message over tcp");
context.stop();
Thread.sleep(100);
final String serverData = serverStream.toString();
assertTrue("Server received: " + serverData, serverData.contains("test message over tcp"));
}
@BeforeEach
void setUp() throws JoranException {
LoggerContext context = new LoggerContext();
ContextInitializer contextInitializer = new ContextInitializer(context);
contextInitializer.configureByResource(this.getClass().getResource("/logback-config.xml"));
logger = context.getLogger("root");
appender = (OutputStreamAppender) logger.getAppender("out");
}
protected void configureWith(URL resource) {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext((LoggerContext) loggerFactory);
((LoggerContext) loggerFactory).reset();
// the statusManager keeps a copy of all logback status messages even after reset, so we clear that
((LoggerContext) loggerFactory).getStatusManager().clear();
try {
configurator.doConfigure(resource);
} catch (JoranException ignore) {
}
StatusPrinter.printInCaseOfErrorsOrWarnings((Context) loggerFactory);
}
@Before
public void init() throws JoranException {
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(new File("src/test/resources/logback-example.xml"));
StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
}
private static void initLogback() throws JoranException {
String rocketmqHome = System.getProperty(MixAll.ROCKETMQ_HOME_PROPERTY, System.getenv(MixAll.ROCKETMQ_HOME_ENV));
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(rocketmqHome + "/conf/logback_tools.xml");
}
@Before
public void initLogback() throws JoranException {
InternalLoggerFactory.setCurrentLoggerType(InternalLoggerFactory.LOGGER_SLF4J);
System.setProperty("loggingDir", loggingDir);
ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
JoranConfigurator joranConfigurator = new JoranConfigurator();
joranConfigurator.setContext((Context) iLoggerFactory);
URL logbackConfigFile = Slf4jLoggerFactoryTest.class.getClassLoader().getResource("logback_test.xml");
if (logbackConfigFile == null) {
throw new RuntimeException("can't find logback_test.xml");
} else {
joranConfigurator.doConfigure(logbackConfigFile);
}
}
@Before
public void init() throws JoranException {
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(new File("src/test/resources/logback-example.xml"));
StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
}