001/*
002 * SonarQube, open source software quality management tool.
003 * Copyright (C) 2008-2014 SonarSource
004 * mailto:contact AT sonarsource DOT com
005 *
006 * SonarQube is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 3 of the License, or (at your option) any later version.
010 *
011 * SonarQube is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014 * Lesser General Public License for more details.
015 *
016 * You should have received a copy of the GNU Lesser General Public License
017 * along with this program; if not, write to the Free Software Foundation,
018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
019 */
020package org.sonar.process;
021
022import ch.qos.logback.classic.Logger;
023import ch.qos.logback.classic.LoggerContext;
024import ch.qos.logback.classic.joran.JoranConfigurator;
025import ch.qos.logback.classic.spi.ILoggingEvent;
026import ch.qos.logback.core.Appender;
027import ch.qos.logback.core.joran.spi.JoranException;
028import ch.qos.logback.core.util.StatusPrinter;
029import org.slf4j.LoggerFactory;
030
031public class ProcessLogging {
032
033  private static final String PATH_LOGS_PROPERTY = "sonar.path.logs";
034
035  public void configure(Props props, String logbackXmlResource) {
036    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
037    try {
038      JoranConfigurator configurator = new JoranConfigurator();
039      configurator.setContext(context);
040      context.reset();
041      context.putProperty(PATH_LOGS_PROPERTY, props.nonNullValue(PATH_LOGS_PROPERTY));
042      doConfigure(configurator, logbackXmlResource);
043    } catch (JoranException ignored) {
044      // StatusPrinter will handle this
045    }
046    StatusPrinter.printInCaseOfErrorsOrWarnings(context);
047  }
048
049  public void addConsoleAppender() {
050    Logger consoleLogger = (Logger) LoggerFactory.getLogger("console");
051    Appender<ILoggingEvent> consoleAppender = consoleLogger.getAppender("CONSOLE");
052
053    Logger gobblerLogger = (Logger) LoggerFactory.getLogger("gobbler");
054    gobblerLogger.addAppender(consoleAppender);
055  }
056
057  /**
058   * Extracted only for unit testing
059   */
060  void doConfigure(JoranConfigurator configurator, String logbackXmlResource) throws JoranException {
061    configurator.doConfigure(getClass().getResource(logbackXmlResource));
062  }
063}