@Test 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-syslog-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 static void load(String externalConfigFileLocation) throws IOException, JoranException { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); File externalConfigFile = new File(externalConfigFileLocation); if (!externalConfigFile.exists()) { throw new IOException("Logback External Config File Parameter does not reference a file that exists"); } else { if (!externalConfigFile.isFile()) { throw new IOException("Logback External Config File Parameter exists, but does not reference a file"); } else { if (!externalConfigFile.canRead()) { throw new IOException("Logback External Config File exists and is a file, but cannot be read."); } else { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure(externalConfigFileLocation); StatusPrinter.printInCaseOfErrorsOrWarnings(lc); } } } }
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); } }
@Test 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-syslog-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")); }
@Test 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-syslog-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")); }
@PostConstruct public void initializeLogback() { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); InputStream is = InitLogback.class.getClassLoader().getResourceAsStream("tasfe-logback.xml"); if (is == null) return; JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); try { configurator.doConfigure(is); } catch (JoranException e) { e.printStackTrace(); } }
protected void captureOutput() throws IOException, JoranException { System.setProperty("ROOT_APPENDER", "JSON_CONSOLE"); LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.reset(); JoranConfigurator configurator = new JoranConfigurator(); InputStream configStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("logback.xml"); configurator.setContext(loggerContext); configurator.doConfigure(configStream); configStream.close(); baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); System.setOut(ps); }
private void writeLogsOnFileAndConsole() { loggers.debug("****Configuring Logger****"); try { if(Platform.isRunning()){ System.setProperty(HYDROGRAPH_INSTALLATION_LOCATION, Platform.getInstallLocation().getURL().getPath()); ClassLoader loader = new URLClassLoader(new URL[] {new File(Platform.getInstallLocation().getURL().getPath() + LOG_DIR).toURI().toURL()}); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); URL url = Loader.getResource(CLASSIC_FILE, loader); if (url != null) { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure(url); lc.start(); } loggers.debug("****Logger Configured Successfully****"); } } catch(MalformedURLException|JoranException exception){ loggers.error("Failed to configure the logger {}", exception); } }
private void initializeLogging() { String graviteeHome = System.getProperty("gravitee.home"); String logbackConfiguration = graviteeHome + File.separator + "config" + File.separator + "logback.xml"; File logbackConfigurationfile = new File(logbackConfiguration); // If logback configuration available, load it, else, load default logback configuration if (logbackConfigurationfile.exists()) { System.setProperty("logback.configurationFile", logbackConfigurationfile.getAbsolutePath()); StaticLoggerBinder loggerBinder = StaticLoggerBinder.getSingleton(); LoggerContext loggerContext = (LoggerContext) loggerBinder.getLoggerFactory(); loggerContext.reset(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(loggerContext); try { configurator.doConfigure(logbackConfigurationfile); } catch( JoranException e ) { e.printStackTrace(); } // Internal status data is printed in case of warnings or errors. StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); } }
public void load(File... configList) throws JoranException { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); for (File config : configList) { if (config.exists()) { if (config.isFile()) { if (config.canRead()) { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); // 設定をクリアして再読み込み context.reset(); configurator.doConfigure(config); LOG.warn("logback設定ファイル再設定が完了しました。{}", config.getAbsolutePath()); break; } else { LOG.warn("logback設定ファイルが読み込めません。{}", config.getAbsolutePath()); } } else { LOG.warn("logback設定ファイルがディレクトリです。{}", config.getAbsolutePath()); } } else { LOG.info("logback設定ファイルが見つかりません。{}", config.getAbsolutePath()); } } }
/** * 服务容器启动初始化加加载日志文件 * @param servletContextEvent */ public void contextInitialized(ServletContextEvent servletContextEvent) { //系统启动加载日志配置文件 InputStream is = this.getClass().getResourceAsStream("/logback.xml"); try { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure(is); } catch (Exception e) { e.printStackTrace(); logger.error("加载logback.xml 日志配置文件加载异常...",e); System.exit(0); } logger.debug(">>> Web :: 容器初始化完成 Success!"); }
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); } } }
/** * Loads the Logback configuration from a resource file. * Only here to avoid polluting other examples with logs. Could be * replaced by a simple logback.xml file in the resource folder. */ private static void loadLoggerConfiguration() { LoggerContext context = (LoggerContext) LoggerFactory .getILoggerFactory(); context.reset(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); try { if (LOGBACK_CONF_FILE != null) { configurator.doConfigure(LOGBACK_CONF_FILE); } } catch (JoranException e) { Logger.getLogger(MainTrader.class.getName()).log(Level.SEVERE, "Unable to load Logback configuration", e); } }
private static void configureLogbackFromLocalFile() { boolean localLogFileExists = Files.exists(Paths.get("./logback.xml")); if (!localLogFileExists) { System.out.println("logback.xml not found in local path - defaulting to packaged one"); return; } // assume SLF4J is bound to logback in the current environment 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("./logback.xml"); } catch (JoranException je) { // StatusPrinter will handle this } StatusPrinter.printInCaseOfErrorsOrWarnings(context); }
/** * Configures logging from a logback resource. * * @param logbackResource the logback resource, not null * @return true if logging was configured successfully, false otherwise */ public static boolean configureLogger(String logbackResource) { try { ArgumentChecker.notNull(logbackResource, "logbackResource"); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); URL logbackResourceUrl = LogUtils.class.getClassLoader().getResource(logbackResource); if (logbackResourceUrl == null) { throw new IllegalArgumentException("Logback file not found: " + logbackResource); } configurator.doConfigure(logbackResourceUrl); return true; } catch (Exception ex) { ex.printStackTrace(); return false; } }
public LogBackConfigLoader(String externalConfigFileLocation) throws IOException, JoranException{ LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); File externalConfigFile = new File(externalConfigFileLocation); if (!externalConfigFile.exists()) { throw new IOException("Logback External Config File Parameter does not reference a file that exists: " + externalConfigFileLocation); } else { if (!externalConfigFile.isFile()) { throw new IOException("Logback External Config File Parameter exists, but does not reference a file:" + externalConfigFileLocation); } else { if (!externalConfigFile.canRead()) { throw new IOException("Logback External Config File exists and is a file, but cannot be read: " + externalConfigFileLocation); } else { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure(externalConfigFileLocation); logger.info("Configured Logback with config file from: " + externalConfigFileLocation); } } } }
public static void configureLogging() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); context.reset(); configurator.setContext(context); System.out.println("Attempting to load logback configuration file: " + LOG_CONFIG_FILE_NAME + " from classpath or " + System.getProperty("user.home") + "/.waltz/"); Resource logbackConfigFile = IOUtilities.getFileResource(LOG_CONFIG_FILE_NAME); if (logbackConfigFile.exists()) { System.out.println("Found logback configuration file at: " + logbackConfigFile.getFile().getAbsolutePath()); configurator.doConfigure(logbackConfigFile.getFile()); } else { System.out.println("Logback configuration file not found.."); } } catch (IOException | JoranException e) { // StatusPrinter will handle this } StatusPrinter.printInCaseOfErrorsOrWarnings(context); }
private void initializeLogging() { String graviteeHome = System.getProperty("gravitee.home"); String logbackConfiguration = graviteeHome + File.separator + "config" + File.separator + "logback.xml"; File logbackConfigurationfile = new File(logbackConfiguration); // If logback configuration available, load it, else, load default logback configuration if (logbackConfigurationfile.exists()) { System.setProperty("logback.configurationFile", logbackConfigurationfile.getAbsolutePath()); StaticLoggerBinder loggerBinder = StaticLoggerBinder.getSingleton(); LoggerContext loggerContext = (LoggerContext) loggerBinder.getLoggerFactory(); loggerContext.reset(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(loggerContext); try { configurator.doConfigure(logbackConfigurationfile); } catch( JoranException e ) { LoggerFactory.getLogger(Container.class).error("An error occurs while initializing logging system", e); } // Internal status data is printed in case of warnings or errors. StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); } }
public void reloadByURL(URL url) throws JoranException { StatusListenerAsList statusListenerAsList = new StatusListenerAsList(); addStatusListener(statusListenerAsList); addInfo("Resetting context: " + loggerContext.getName()); loggerContext.reset(); // after a reset the statusListenerAsList gets removed as a listener addStatusListener(statusListenerAsList); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(loggerContext); configurator.doConfigure(url); addInfo("Context: " + loggerContext.getName() + " reloaded."); } finally { removeStatusListener(statusListenerAsList); if (debug) { StatusPrinter.print(statusListenerAsList.getStatusList()); } } }
private void performXMLConfiguration(LoggerContext lc) { JoranConfigurator jc = new JoranConfigurator(); jc.setContext(context); StatusUtil statusUtil = new StatusUtil(context); List<SaxEvent> eventList = jc.recallSafeConfiguration(); URL mainURL = ConfigurationWatchListUtil.getMainWatchURL(context); lc.reset(); long threshold = System.currentTimeMillis(); try { jc.doConfigure(mainConfigurationURL); if (statusUtil.hasXMLParsingErrors(threshold)) { fallbackConfiguration(lc, eventList, mainURL); } } catch (JoranException e) { fallbackConfiguration(lc, eventList, mainURL); } }
private void fallbackConfiguration(LoggerContext lc, List<SaxEvent> eventList, URL mainURL) { JoranConfigurator joranConfigurator = new JoranConfigurator(); joranConfigurator.setContext(context); if (eventList != null) { addWarn("Falling back to previously registered safe configuration."); try { lc.reset(); joranConfigurator.informContextOfURLUsedForConfiguration(context, mainURL); joranConfigurator.doConfigure(eventList); addInfo("Re-registering previous fallback configuration once more as a fallback configuration point"); joranConfigurator.registerSafeConfiguration(); } catch (JoranException e) { addError("Unexpected exception thrown by a configuration considered safe.", e); } } else { addWarn("No previous configuration to fall back on."); } }
public void configureByResource(URL url) throws JoranException { if (url == null) { throw new IllegalArgumentException("URL argument cannot be null"); } final String urlString = url.toString(); if (urlString.endsWith("groovy")) { if (EnvUtil.isGroovyAvailable()) { // avoid directly referring to GafferConfigurator so as to avoid // loading groovy.lang.GroovyObject . See also http://jira.qos.ch/browse/LBCLASSIC-214 GafferUtil.runGafferConfiguratorOn(loggerContext, this, url); } else { StatusManager sm = loggerContext.getStatusManager(); sm.add(new ErrorStatus("Groovy classes are not available on the class path. ABORTING INITIALIZATION.", loggerContext)); } } else if (urlString.endsWith("xml")) { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(loggerContext); configurator.doConfigure(url); } else { throw new LogbackException("Unexpected filename extension of file [" + url.toString() + "]. Should be either .groovy or .xml"); } }
public void start(BundleContext context) { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); // the context was probably already configured by default configuration // rules lc.reset(); configurator.doConfigure("src/test/input/osgi/simple.xml"); } catch (JoranException je) { je.printStackTrace(); } StatusPrinter.printInCaseOfErrorsOrWarnings(lc); Logger logger = LoggerFactory.getLogger(this.getClass()); logger.info("Activator.start()"); m_context = context; }
@Test public void lbcore211() throws JoranException { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure("/home/ceki/lbcore211.xml"); Logger l = lc.getLogger("file.logger"); StatusPrinter.print(lc); for (int i = 0; i < 10; i++) { l.info("hello " + i); } lc.stop(); }
public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(MyAppWithConfigFile.class); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); lc.reset(); configurator.setContext(lc); configurator.doConfigure(args[0]); } catch (JoranException je) { StatusPrinter.print(lc.getStatusManager()); } logger.info("Entering application."); Bar bar = new Bar(); bar.doIt(); logger.info("Exiting application."); }
public static void main(String[] args) throws InterruptedException { Logger logger = LoggerFactory.getLogger(TrivialMain.class); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure(args[0]); } catch (JoranException je) { // StatusPrinter will handle this } StatusPrinter.printInCaseOfErrorsOrWarnings(lc); for (int i = 0; i < 6; i++) { if (i % 5 == 0) { logger.warn("a warning message " + i); } else if(i % 3 == 0) { logger.info("hello world number" + i); } else { logger.debug("hello world number" + i); } } logger.error("Finish off with fireworks", new Exception("Just testing")); }
public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(ExceptionEvaluatorExample.class); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure(args[0]); } catch (JoranException je) { // StatusPrinter will handle this } StatusPrinter.printInCaseOfErrorsOrWarnings(lc); for (int i = 0; i < 3; i++) { if (i == 1) { logger.debug("logging statement " + i, new TestException( "do not display this")); } else { logger.debug("logging statement " + i, new Exception("display")); } } }
public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(CallerEvaluatorExample.class); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure(args[0]); } catch (JoranException je) { // StatusPrinter will handle this } StatusPrinter.printInCaseOfErrorsOrWarnings(lc); for (int i = 0; i < 5; i++) { if (i == 3) { logger.debug("who calls thee?"); } else { logger.debug("I know me " + i); } } }
public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(SampleLogging.class); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); lc.reset(); configurator.setContext(lc); configurator.doConfigure(args[0]); } catch (JoranException je) { // StatusPrinter will handle this } StatusPrinter.printInCaseOfErrorsOrWarnings(lc); logger.debug("Everything's going well"); logger.error("maybe not quite..."); }
public static void main(String[] args) { // assume SLF4J is bound to logback in the current environment 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(args[0]); } catch (JoranException je) { // StatusPrinter will handle this } StatusPrinter.printInCaseOfErrorsOrWarnings(context); logger.info("Entering application."); Foo foo = new Foo(); foo.doIt(); logger.info("Exiting application."); }
public static void main(String[] args) throws InterruptedException { Logger logger = (Logger) LoggerFactory.getLogger(ConfigurationTester.class); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure(args[0]); } catch (JoranException je) { je.printStackTrace(); } // After we've called Joran, let's print information about the // internal status of logback StatusPrinter.print(lc); logger.debug("**Hello {}", new Bar()); MDC.put("testKey", "testValueFromMDC"); MDC.put("testKey2", "value2"); for (int i = 0; i < 10; i++) { logger.debug("logging statement " + i); Thread.sleep(100); } Bar bar = new Bar(); bar.createLoggingRequest(); }
public static void main(String[] args) throws JoranException { if (args.length != 1) { usage("Wrong number of arguments."); } String configFile = args[0]; LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); lc.reset(); configurator.setContext(lc); configurator.doConfigure(configFile); Logger logger = LoggerFactory.getLogger(SiftExample.class); logger.debug("Application started"); MDC.put("userid", "Alice"); logger.debug("Alice says hello"); //StatusPrinter.print(lc); }
static public void main(String[] args) throws Exception { if (args.length != 1) { usage("Wrong number of arguments."); } String configFile = args[0]; if (configFile.endsWith(".xml")) { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); lc.reset(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); configurator.doConfigure(configFile); } Thread.sleep(Long.MAX_VALUE); }
public static void main(String[] args) { Logger logger = LoggerFactory .getLogger(GoMDC.class); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure("mdcFilter.xml"); } catch (JoranException je) { StatusPrinter.print(lc); } logger.debug("I know me " + 0); MDC.put("key", "val"); logger.debug("I know me " + 1); StatusPrinter.print(lc); }
/** * Initialize logback from the given file. * * @param location * the location of the config file: either a "classpath:" * location (e.g. "classpath:logback.xml"), an absolute file URL * (e.g. "file:C:/logback.xml), or a plain absolute path in the * file system (e.g. "C:/logback.xml") * @throws java.io.FileNotFoundException * if the location specifies an invalid file path */ public static void initLogging(final String location) throws FileNotFoundException { String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(location); URL url = ResourceUtils.getURL(resolvedLocation); LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(loggerContext); // the context was probably already configured by default // configuration // rules loggerContext.reset(); configurator.doConfigure(url); } catch (JoranException je) { // StatusPrinter will handle this } StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); }
@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); } }
private static boolean readAndSetLogbackConfiguration(String filePath, String fileName) { boolean doesConfigFileExist = FileIo.doesFileExist(filePath, fileName); if (doesConfigFileExist) { File logggerConfigFile = new File(filePath + File.separator + fileName); LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); context.reset(); configurator.doConfigure(logggerConfigFile); StatusPrinter.printInCaseOfErrorsOrWarnings(context); return true; } catch (Exception e) { StatusPrinter.printInCaseOfErrorsOrWarnings(context); return false; } } else { return false; } }