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     */
020    package org.sonar.process;
021    
022    import ch.qos.logback.classic.Logger;
023    import ch.qos.logback.classic.LoggerContext;
024    import ch.qos.logback.classic.joran.JoranConfigurator;
025    import ch.qos.logback.classic.spi.ILoggingEvent;
026    import ch.qos.logback.core.Appender;
027    import ch.qos.logback.core.joran.spi.JoranException;
028    import ch.qos.logback.core.util.StatusPrinter;
029    import org.slf4j.LoggerFactory;
030    
031    public class ProcessLogging {
032    
033      public void configure(Props props, String logbackXmlResource) {
034        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
035        try {
036          JoranConfigurator configurator = new JoranConfigurator();
037          configurator.setContext(context);
038          context.reset();
039          context.putProperty(ProcessConstants.PATH_LOGS, props.nonNullValue(ProcessConstants.PATH_LOGS));
040          doConfigure(configurator, logbackXmlResource);
041        } catch (JoranException ignored) {
042          // StatusPrinter will handle this
043        }
044        StatusPrinter.printInCaseOfErrorsOrWarnings(context);
045      }
046    
047      public void addConsoleAppender() {
048        Logger consoleLogger = (Logger) LoggerFactory.getLogger("console");
049        Appender<ILoggingEvent> consoleAppender = consoleLogger.getAppender("CONSOLE");
050    
051        Logger gobblerLogger = (Logger) LoggerFactory.getLogger("gobbler");
052        gobblerLogger.addAppender(consoleAppender);
053      }
054    
055      /**
056       * Extracted only for unit testing
057       */
058      void doConfigure(JoranConfigurator configurator, String logbackXmlResource) throws JoranException {
059        configurator.doConfigure(getClass().getResource(logbackXmlResource));
060      }
061    }