001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2020 the original author or authors.
004//
005// This library is free software; you can redistribute it and/or
006// modify it under the terms of the GNU Lesser General Public
007// License as published by the Free Software Foundation; either
008// version 2.1 of the License, or (at your option) any later version.
009//
010// This library is distributed in the hope that it will be useful,
011// but WITHOUT ANY WARRANTY; without even the implied warranty of
012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013// Lesser General Public License for more details.
014//
015// You should have received a copy of the GNU Lesser General Public
016// License along with this library; if not, write to the Free Software
017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
018////////////////////////////////////////////////////////////////////////////////
019
020package com.puppycrawl.tools.checkstyle;
021
022import java.io.OutputStream;
023import java.io.OutputStreamWriter;
024import java.io.PrintWriter;
025import java.io.Writer;
026import java.nio.charset.StandardCharsets;
027
028import com.puppycrawl.tools.checkstyle.api.AuditEvent;
029import com.puppycrawl.tools.checkstyle.api.AuditListener;
030import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
031import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
032import com.puppycrawl.tools.checkstyle.api.SeverityLevel;
033
034/**
035 * Simple plain logger for text output.
036 * This is maybe not very suitable for a text output into a file since it
037 * does not need all 'audit finished' and so on stuff, but it looks good on
038 * stdout anyway. If there is really a problem this is what XMLLogger is for.
039 * It gives structure.
040 *
041 * @see XMLLogger
042 */
043public class DefaultLogger extends AutomaticBean implements AuditListener {
044
045    /**
046     * A key pointing to the add exception
047     * message in the "messages.properties" file.
048     */
049    public static final String ADD_EXCEPTION_MESSAGE = "DefaultLogger.addException";
050    /**
051     * A key pointing to the started audit
052     * message in the "messages.properties" file.
053     */
054    public static final String AUDIT_STARTED_MESSAGE = "DefaultLogger.auditStarted";
055    /**
056     * A key pointing to the finished audit
057     * message in the "messages.properties" file.
058     */
059    public static final String AUDIT_FINISHED_MESSAGE = "DefaultLogger.auditFinished";
060
061    /** Where to write info messages. **/
062    private final PrintWriter infoWriter;
063    /** Close info stream after use. */
064    private final boolean closeInfo;
065
066    /** Where to write error messages. **/
067    private final PrintWriter errorWriter;
068    /** Close error stream after use. */
069    private final boolean closeError;
070
071    /** Formatter for the log message. */
072    private final AuditEventFormatter formatter;
073
074    /**
075     * Creates a new {@code DefaultLogger} instance.
076     *
077     * @param outputStream where to log audit events
078     * @param outputStreamOptions if {@code CLOSE} that should be closed in auditFinished()
079     */
080    public DefaultLogger(OutputStream outputStream, OutputStreamOptions outputStreamOptions) {
081        // no need to close oS twice
082        this(outputStream, outputStreamOptions, outputStream, OutputStreamOptions.NONE);
083    }
084
085    /**
086     * Creates a new {@code DefaultLogger} instance.
087     *
088     * @param infoStream the {@code OutputStream} for info messages.
089     * @param infoStreamOptions if {@code CLOSE} info should be closed in auditFinished()
090     * @param errorStream the {@code OutputStream} for error messages.
091     * @param errorStreamOptions if {@code CLOSE} error should be closed in auditFinished()
092     */
093    public DefaultLogger(OutputStream infoStream,
094                         OutputStreamOptions infoStreamOptions,
095                         OutputStream errorStream,
096                         OutputStreamOptions errorStreamOptions) {
097        this(infoStream, infoStreamOptions, errorStream, errorStreamOptions,
098                new AuditEventDefaultFormatter());
099    }
100
101    /**
102     * Creates a new {@code DefaultLogger} instance.
103     *
104     * @param infoStream the {@code OutputStream} for info messages
105     * @param infoStreamOptions if {@code CLOSE} info should be closed in auditFinished()
106     * @param errorStream the {@code OutputStream} for error messages
107     * @param errorStreamOptions if {@code CLOSE} error should be closed in auditFinished()
108     * @param messageFormatter formatter for the log message.
109     * @throws IllegalArgumentException if stream options are null
110     * @noinspection WeakerAccess
111     */
112    public DefaultLogger(OutputStream infoStream,
113                         OutputStreamOptions infoStreamOptions,
114                         OutputStream errorStream,
115                         OutputStreamOptions errorStreamOptions,
116                         AuditEventFormatter messageFormatter) {
117        if (infoStreamOptions == null) {
118            throw new IllegalArgumentException("Parameter infoStreamOptions can not be null");
119        }
120        closeInfo = infoStreamOptions == OutputStreamOptions.CLOSE;
121        if (errorStreamOptions == null) {
122            throw new IllegalArgumentException("Parameter errorStreamOptions can not be null");
123        }
124        closeError = errorStreamOptions == OutputStreamOptions.CLOSE;
125        final Writer infoStreamWriter = new OutputStreamWriter(infoStream, StandardCharsets.UTF_8);
126        infoWriter = new PrintWriter(infoStreamWriter);
127
128        if (infoStream == errorStream) {
129            errorWriter = infoWriter;
130        }
131        else {
132            final Writer errorStreamWriter = new OutputStreamWriter(errorStream,
133                    StandardCharsets.UTF_8);
134            errorWriter = new PrintWriter(errorStreamWriter);
135        }
136        formatter = messageFormatter;
137    }
138
139    @Override
140    protected void finishLocalSetup() {
141        // No code by default
142    }
143
144    /**
145     * Print an Emacs compliant line on the error stream.
146     * If the column number is non zero, then also display it.
147     *
148     * @see AuditListener
149     **/
150    @Override
151    public void addError(AuditEvent event) {
152        final SeverityLevel severityLevel = event.getSeverityLevel();
153        if (severityLevel != SeverityLevel.IGNORE) {
154            final String errorMessage = formatter.format(event);
155            errorWriter.println(errorMessage);
156        }
157    }
158
159    @Override
160    public void addException(AuditEvent event, Throwable throwable) {
161        synchronized (errorWriter) {
162            final LocalizedMessage addExceptionMessage = new LocalizedMessage(1,
163                Definitions.CHECKSTYLE_BUNDLE, ADD_EXCEPTION_MESSAGE,
164                new String[] {event.getFileName()}, null,
165                LocalizedMessage.class, null);
166            errorWriter.println(addExceptionMessage.getMessage());
167            throwable.printStackTrace(errorWriter);
168        }
169    }
170
171    @Override
172    public void auditStarted(AuditEvent event) {
173        final LocalizedMessage auditStartMessage = new LocalizedMessage(1,
174            Definitions.CHECKSTYLE_BUNDLE, AUDIT_STARTED_MESSAGE, null, null,
175            LocalizedMessage.class, null);
176        infoWriter.println(auditStartMessage.getMessage());
177        infoWriter.flush();
178    }
179
180    @Override
181    public void auditFinished(AuditEvent event) {
182        final LocalizedMessage auditFinishMessage = new LocalizedMessage(1,
183            Definitions.CHECKSTYLE_BUNDLE, AUDIT_FINISHED_MESSAGE, null, null,
184            LocalizedMessage.class, null);
185        infoWriter.println(auditFinishMessage.getMessage());
186        closeStreams();
187    }
188
189    @Override
190    public void fileStarted(AuditEvent event) {
191        // No need to implement this method in this class
192    }
193
194    @Override
195    public void fileFinished(AuditEvent event) {
196        infoWriter.flush();
197    }
198
199    /**
200     * Flushes the output streams and closes them if needed.
201     */
202    private void closeStreams() {
203        infoWriter.flush();
204        if (closeInfo) {
205            infoWriter.close();
206        }
207
208        errorWriter.flush();
209        if (closeError) {
210            errorWriter.close();
211        }
212    }
213
214}