public static void load(String location) throws IOException {

    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    File externalConfigFile = new File(location);
    if (!externalConfigFile.exists()) {
      throw new IOException(
          "Logback External Conf File Parameter does not reference a file that exists");
    } else {
      if (!externalConfigFile.isFile()) {
        throw new IOException(
            "Logback External Conf File Parameter exists, but does not reference a file");
      } else {
        if (!externalConfigFile.canRead()) {
          throw new IOException(
              "Logback External Conf File exists and is a file, but cannot be read.");
        } else {
          JoranConfigurator configurator = new JoranConfigurator();
          configurator.setContext(lc);
          lc.reset();
          try {
            configurator.doConfigure(location);
          } catch (JoranException e) {
            throw new RuntimeException(e);
          }
          StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
        }
      }
    }
  }
Esempio n. 2
0
  @Override
  public void contextInitialized(final ServletContextEvent servletContextEvent) {
    final ServletContext sc = servletContextEvent.getServletContext();
    final String logbackConfigLocation = sc.getInitParameter(LOGBACK_CONFIG_LOCATION);
    String filePath = null;
    try {
      final Path configFile = Paths.get(sc.getResource(logbackConfigLocation).toURI());
      filePath = configFile.toAbsolutePath().toString();

      final File rootFolder = new File(sc.getResource("/").getPath());
      final File logFolder = new File(rootFolder.getParentFile().getPath() + "/logs");
      if (!logFolder.exists()) {
        if (!logFolder.mkdirs()) {
          throw new IOException("Cannot create: " + logFolder.getAbsolutePath());
        }
      }
      System.setProperty("log.basepath", logFolder.getAbsolutePath());
      final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
      final JoranConfigurator configurator = new JoranConfigurator();
      configurator.setContext(context);
      context.reset();
      configurator.doConfigure(configFile.toFile());
    } catch (Exception e) {
      System.err.println("Failed to locate logback config file: " + filePath);
      return;
    }
    System.out.println("[INFO] Init logback by the config file:" + filePath);
  }
Esempio n. 3
0
  public synchronized void init() {

    if (isInit == true) throw new RuntimeException("LogbackFactory had init~~~");

    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    try {
      File externalConfigFile = new File(fileName);
      if (!externalConfigFile.exists()) {

        throw new IOException("logback server file : " + fileName + " not existed!!!");
      }
      if (!externalConfigFile.isFile()) {
        throw new IOException("logback server file : " + fileName + " not file!!!");
      }
      if (!externalConfigFile.canRead()) {
        throw new IOException("logback server file : " + fileName + " can't read!!!");
      }

      JoranConfigurator configurator = new JoranConfigurator();
      configurator.setContext(lc);
      lc.reset();
      configurator.doConfigure(fileName);
      StatusPrinter.printInCaseOfErrorsOrWarnings(lc);

    } catch (final Exception e) {
      e.printStackTrace();
    }

    isInit = true;
  }
  // A few things that need to get set up before regular init().
  @Override
  protected void internalInit() {
    log.debug("Starting CWM Application Internal Init");
    log.debug("Application Class is " + getClass().getName());

    loadAppProperties();

    // If using Logback as the logger, and we have a logConfig property,
    // then read that configuration.
    File logConfig = configuration.getOptionalFile("cwm.logConfig");
    if (logConfig != null && LoggerFactory.getILoggerFactory() instanceof LoggerContext) {
      log.info("Log Configuration: {}", logConfig);
      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(logConfig);
      } catch (JoranException je) {
        je.printStackTrace();
      }
      StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
    }

    loadServices();

    getComponentInstantiationListeners()
        .add(new GuiceComponentInjector(this, getInjectionModuleArray()));

    super.internalInit();
  }
 /**
  * Initialize logback from the given URL.
  *
  * @param url the url pointing to the location of the config file.
  * @throws JoranException if the url points to a non existing location or an error occurs during
  *     the parsing operation.
  */
 public static void initLogging(URL url) throws JoranException {
   LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
   JoranConfigurator configurator = new JoranConfigurator();
   configurator.setContext(loggerContext);
   loggerContext.reset();
   configurator.doConfigure(url);
 }
Esempio n. 6
0
  public static void enableLogging(boolean enable) {

    // get the context
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

    try {

      // create a new configurator
      JoranConfigurator configurator = new JoranConfigurator();

      // set context and reset it
      configurator.setContext(loggerContext);
      loggerContext.reset();

      // if logging should be enabled
      if (enable) {

        // add the correct properties and load the XML file
        loggerContext.putProperty("araraLogName", AraraConstants.LOGNAME);
        configurator.doConfigure(
            AraraLogging.class.getResourceAsStream("/com/github/arara/conf/logback.xml"));
      }

    } catch (JoranException joranException) {
      // do nothing
    }
  }
Esempio n. 7
0
  public void testAspects() throws Exception {

    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(lc);

    // the context was probably already configured by default configuration
    // rules
    lc.reset();

    configurator.doConfigure(getClass().getResource("logback.xml"));

    ListAppender<LoggingEvent> listAppender =
        (ListAppender<LoggingEvent>)
            lc.getLogger(StopWatch.DEFAULT_LOGGER_NAME).getAppender("listAppender");

    ProfiledObject.simpleTestDefaultTagStatic(10);
    assertTrue(
        "Expected tag not found in " + listAppender.list.get(0).getMessage(),
        listAppender.list.get(0).getMessage().indexOf("tag[simpleTestDefaultTagStatic]") >= 0);

    new ProfiledObject().simpleTestUnprofiled(10);
    assertTrue(
        "Expected tag not found in " + listAppender.list.get(1).getMessage(),
        listAppender.list.get(1).getMessage().indexOf("tag[simpleTestUnprofiled]") >= 0);

    assertEquals("Expected two logging events", 2, listAppender.list.size());
  }
Esempio n. 8
0
  protected TestProtocolServer newTestProtocolServer(URI serverId) {
    LoggerContext loggerContext = new LoggerContext();
    loggerContext.putProperty("host", serverId.toString());

    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(loggerContext);
    try {
      configurator.doConfigure(getClass().getResource("/test-logback.xml"));
    } catch (JoranException e) {
      throw new IllegalStateException("Failed to configure logging", e);
    }

    Logging logging = new LogbackService(null, loggerContext);

    ProtocolServerFactory protocolServerFactory =
        new MultiPaxosServerFactory(new ClusterConfiguration("default"), logging);

    ServerIdElectionCredentialsProvider electionCredentialsProvider =
        new ServerIdElectionCredentialsProvider();
    electionCredentialsProvider.listeningAt(serverId);
    TestProtocolServer protocolServer =
        new TestProtocolServer(
            timeoutStrategy,
            protocolServerFactory,
            serverId,
            new InMemoryAcceptorInstanceStore(),
            electionCredentialsProvider);
    protocolServer.addStateTransitionListener(new StateTransitionLogger(logging));
    return protocolServer;
  }
Esempio n. 9
0
 private void initLogging(String location) throws JoranException {
   URL url = getResourceURL(location);
   LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
   loggerContext.reset();
   JoranConfigurator configurator = new JoranConfigurator();
   configurator.setContext(loggerContext);
   configurator.doConfigure(url);
 }
Esempio n. 10
0
  private static void initLogback() throws JoranException {
    String rocketmqHome =
        System.getProperty(MixAll.ROCKETMQ_HOME_PROPERTY, System.getenv(MixAll.ROCKETMQ_HOME_ENV));

    // 初始化Logback
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(lc);
    lc.reset();
    configurator.doConfigure(rocketmqHome + "/conf/logback_tools.xml");
  }
Esempio n. 11
0
  /** Initializes the logger. */
  private static void initLogger() {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

    try {
      JoranConfigurator configurator = new JoranConfigurator();
      configurator.setContext(context);
      context.reset();
      configurator.doConfigure(InspectIT.class.getResourceAsStream("/config/logback.xml"));
    } catch (JoranException je) { // NOPMD NOCHK StatusPrinter will handle this NOCHK
    }
    StatusPrinter.printInCaseOfErrorsOrWarnings(context);
  }
 @Test
 public void consolePatternCanBeOverridden() throws JoranException {
   JoranConfigurator configurator = new JoranConfigurator();
   LoggerContext context = new LoggerContext();
   configurator.setContext(context);
   configurator.doConfigure(new File("src/test/resources/custom-console-log-pattern.xml"));
   Appender<ILoggingEvent> appender = context.getLogger("ROOT").getAppender("CONSOLE");
   assertThat(appender).isInstanceOf(ConsoleAppender.class);
   Encoder<?> encoder = ((ConsoleAppender<?>) appender).getEncoder();
   assertThat(encoder).isInstanceOf(PatternLayoutEncoder.class);
   assertThat(((PatternLayoutEncoder) encoder).getPattern()).isEqualTo("foo");
 }
Esempio n. 13
0
  @Test
  public void LBCLASSIC_50() throws JoranException {

    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(lc);
    lc.reset();
    configurator.doConfigure(ClassicTestConstants.JORAN_INPUT_PREFIX + "/syslog_LBCLASSIC_50.xml");

    org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());
    logger.info("hello");
  }
  @Before
  public void before() throws Exception {
    lc = new LoggerContext();
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(lc);

    URL xmlConfigFile = getClass().getResource("/logback-gelf-with-dynamic-originhost.xml");

    configurator.doConfigure(xmlConfigFile);

    GelfTestSender.getMessages().clear();

    MDC.remove("mdcField1");
  }
  @Override
  protected void configure(String logFile) {
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    lc.reset();
    lc.putProperty("se.trillian.goodies.hostname", getHostName());
    lc.putProperty("se.trillian.goodies.hostname.full", getFullHostName());

    try {
      JoranConfigurator configurator = new JoranConfigurator();
      configurator.setContext(lc);
      configurator.doConfigure(logFile);
    } catch (JoranException je) {
      StatusPrinter.print(lc);
    }
  }
  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.");
  }
 /**
  * Initialize logback from the given file location, with no config file refreshing. Assumes an XML
  * file in case of a ".xml" file extension, and a properties file otherwise.
  *
  * @param location the location of the config file: either a "classpath:" location (e.g.
  *     "classpath:mylogback.properties"), an absolute file URL (e.g. "file:C:/logback.properties),
  *     or a plain absolute path in the file system (e.g. " C:/logback.properties")
  * @throws FileNotFoundException if the location specifies an invalid file path
  */
 public static void initLogging(String location) throws FileNotFoundException {
   String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(location);
   URL url = ResourceUtils.getURL(resolvedLocation);
   if (resolvedLocation.toLowerCase().endsWith(XML_FILE_EXTENSION)) {
     // DOMConfigurator.configure(url);
     configurator.setContext(lc);
     lc.reset();
     try {
       configurator.doConfigure(url);
     } catch (JoranException ex) {
       throw new FileNotFoundException(url.getPath());
     }
     lc.start();
   }
   // else {
   // PropertyConfigurator.configure(url);
   // }
 }
  @Override
  public void contextInitialized(ServletContextEvent sce) {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

    try {
      JoranConfigurator configurator = new JoranConfigurator();
      configurator.setContext(context);
      context.reset();
      ClassPathResource resource = new ClassPathResource("logback-default.xml");
      if (!resource.exists()) {
        String profile = EnvUtil.getProfile();
        resource = new ClassPathResource("META-INF/logback/logback-" + profile + ".xml");
      }

      configurator.doConfigure(resource.getInputStream());
      logger.info("加载logback配置文件:" + resource.getURL().getPath());
    } catch (Exception e) {
      throw new RuntimeException(e.getMessage(), e);
    }
    StatusPrinter.printInCaseOfErrorsOrWarnings(context);
  }
  public static void setLogConfig(String configFileName) throws Exception {
    ILoggerFactory fac = LoggerFactory.getILoggerFactory();
    LoggerContext ctx = (LoggerContext) fac;
    System.out.println("LogFileSelector.setLogConfig() ctx received: " + ctx);
    JoranConfigurator cfg = new JoranConfigurator();
    System.out.println("LogFileSelector.setLogConfig() JoranConfigurator created: " + cfg);
    cfg.setContext(ctx);
    System.out.println("LogFileSelector.setLogConfig() context was set.");
    ctx.reset();
    System.out.println("LogFileSelector.setLogConfig() context was reset.");

    ClassLoader cl = LogFileSelector.class.getClassLoader();
    InputStream in = cl.getResourceAsStream(configFileName);

    try {
      cfg.doConfigure(in);
      log.debug("----------------  log config changed to {}. ----------", configFileName);

    } catch (JoranException e) {
      throw new Exception("could not change log-config to " + configFileName, e);
    }
  }
Esempio n. 20
0
  public static void main(String[] args) {
    // assume SLF4J is bound to logback in the current environment
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

    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();
    try {
      configurator.doConfigure(args[0]);
    } catch (JoranException e) {
      // StatusPrinter will handle this
    }

    logger.info("Entering application");

    Foo foo = new Foo();
    foo.doIt();

    logger.info("Exiting application");
  }
 private void configure(String file) throws JoranException {
   JoranConfigurator jc = new JoranConfigurator();
   jc.setContext(loggerContext);
   loggerContext.putProperty("port", "" + port);
   jc.doConfigure(file);
 }
 void configure(String file) throws JoranException {
   JoranConfigurator jc = new JoranConfigurator();
   jc.setContext(lc);
   jc.doConfigure(file);
 }
 void configure(File file) throws JoranException {
   JoranConfigurator jc = new JoranConfigurator();
   jc.setContext(loggerContext);
   jc.doConfigure(file);
 }
 void configure(InputStream is) throws JoranException {
   JoranConfigurator jc = new JoranConfigurator();
   jc.setContext(loggerContext);
   jc.doConfigure(is);
 }
Esempio n. 25
0
  @SuppressWarnings("unchecked")
  public static void main(String... args) throws ParseException, JoranException, IOException {
    Parser parser = new BasicParser();
    CommandLine cl = null;
    try {
      cl = parser.parse(OPTS, args);
    } catch (ParseException e) {
      HelpFormatter help = new HelpFormatter();
      help.printHelp("dlog", OPTS, true);
      System.exit(-1);
    }

    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    loggerContext.reset();

    if (cl.hasOption("config")) {
      // Read Logback configuration
      JoranConfigurator configurator = new JoranConfigurator();
      configurator.setContext(loggerContext);

      configurator.doConfigure(cl.getOptionValue("file", "logback.xml"));

      StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext);
    } else {
      BasicConfigurator.configure(loggerContext);
    }

    Appender appender = null;
    if (cl.hasOption("output")) {
      String outputAppender = cl.getOptionValue("output", "console");
      appender = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME).getAppender(outputAppender);
    }

    ChronicleTools.warmup();
    Chronicle chronicle = new IndexedChronicle(cl.getOptionValue("path"), ChronicleConfig.DEFAULT);
    ExcerptTailer ex = chronicle.createTailer();

    Level level = Level.valueOf(cl.getOptionValue("level", "TRACE"));

    if (cl.hasOption("head")) {
      int lines = Integer.parseInt(cl.getOptionValue("head", "10"));
      for (int i = 0; i < lines; i++) {
        LoggingEvent evt = readLoggingEvent(ex, loggerContext);
        if (evt.getLevel().isGreaterOrEqual(level)) {
          writeEvent(evt, appender);
        }
      }
    } else if (cl.hasOption("tail")) {
      int lines = Integer.parseInt(cl.getOptionValue("tail", "10"));
      Queue<LoggingEvent> tail = new LinkedBlockingQueue<LoggingEvent>(lines);
      while (ex.nextIndex()) {
        LoggingEvent evt = readLoggingEvent(ex, loggerContext);
        if (!tail.offer(evt)) {
          tail.poll();
          tail.add(evt);
        }
      }
      LoggingEvent evt;
      while (null != (evt = tail.poll())) {
        if (evt.getLevel().isGreaterOrEqual(level)) {
          writeEvent(evt, appender);
        }
      }
    } else if (cl.hasOption("search")) {
      String regex = cl.getOptionValue("search");
      Pattern regexPatt = Pattern.compile(regex);
      while (ex.nextIndex()) {
        LoggingEvent evt = readLoggingEvent(ex, loggerContext);
        if (null != evt && evt.getLevel().isGreaterOrEqual(level)) {
          if (regexPatt.matcher(evt.getFormattedMessage()).matches()) {
            writeEvent(evt, appender);
          }
        }
      }
    }

    loggerContext.stop();
    chronicle.close();
  }
Esempio n. 26
0
 private void doConfigure() throws JoranException {
   LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
   JoranConfigurator configurator = new JoranConfigurator();
   configurator.setContext(context);
   configurator.doConfigure(new File("src/test/input/issue/logback-1159.xml"));
 }