001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2023 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.SeverityLevel;
032
033/**
034 * Simple plain logger for text output.
035 * This is maybe not very suitable for a text output into a file since it
036 * does not need all 'audit finished' and so on stuff, but it looks good on
037 * stdout anyway. If there is really a problem this is what XMLLogger is for.
038 * It gives structure.
039 *
040 * @see XMLLogger
041 */
042public class DefaultLogger extends AutomaticBean implements AuditListener {
043
044    /**
045     * A key pointing to the add exception
046     * message in the "messages.properties" file.
047     */
048    public static final String ADD_EXCEPTION_MESSAGE = "DefaultLogger.addException";
049    /**
050     * A key pointing to the started audit
051     * message in the "messages.properties" file.
052     */
053    public static final String AUDIT_STARTED_MESSAGE = "DefaultLogger.auditStarted";
054    /**
055     * A key pointing to the finished audit
056     * message in the "messages.properties" file.
057     */
058    public static final String AUDIT_FINISHED_MESSAGE = "DefaultLogger.auditFinished";
059
060    /** Where to write info messages. **/
061    private final PrintWriter infoWriter;
062    /** Close info stream after use. */
063    private final boolean closeInfo;
064
065    /** Where to write error messages. **/
066    private final PrintWriter errorWriter;
067    /** Close error stream after use. */
068    private final boolean closeError;
069
070    /** Formatter for the log message. */
071    private final AuditEventFormatter formatter;
072
073    /**
074     * Creates a new {@code DefaultLogger} instance.
075     *
076     * @param outputStream where to log audit events
077     * @param outputStreamOptions if {@code CLOSE} that should be closed in auditFinished()
078     */
079    public DefaultLogger(OutputStream outputStream, OutputStreamOptions outputStreamOptions) {
080        // no need to close oS twice
081        this(outputStream, outputStreamOptions, outputStream, OutputStreamOptions.NONE);
082    }
083
084    /**
085     * Creates a new {@code DefaultLogger} instance.
086     *
087     * @param infoStream the {@code OutputStream} for info messages.
088     * @param infoStreamOptions if {@code CLOSE} info should be closed in auditFinished()
089     * @param errorStream the {@code OutputStream} for error messages.
090     * @param errorStreamOptions if {@code CLOSE} error should be closed in auditFinished()
091     */
092    public DefaultLogger(OutputStream infoStream,
093                         OutputStreamOptions infoStreamOptions,
094                         OutputStream errorStream,
095                         OutputStreamOptions errorStreamOptions) {
096        this(infoStream, infoStreamOptions, errorStream, errorStreamOptions,
097                new AuditEventDefaultFormatter());
098    }
099
100    /**
101     * Creates a new {@code DefaultLogger} instance.
102     *
103     * @param infoStream the {@code OutputStream} for info messages
104     * @param infoStreamOptions if {@code CLOSE} info should be closed in auditFinished()
105     * @param errorStream the {@code OutputStream} for error messages
106     * @param errorStreamOptions if {@code CLOSE} error should be closed in auditFinished()
107     * @param messageFormatter formatter for the log message.
108     * @throws IllegalArgumentException if stream options are null
109     * @noinspection WeakerAccess
110     * @noinspectionreason WeakerAccess - we avoid 'protected' when possible
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 exceptionMessage = new LocalizedMessage(
163                    Definitions.CHECKSTYLE_BUNDLE, DefaultLogger.class,
164                    ADD_EXCEPTION_MESSAGE, event.getFileName());
165            errorWriter.println(exceptionMessage.getMessage());
166            throwable.printStackTrace(errorWriter);
167        }
168    }
169
170    @Override
171    public void auditStarted(AuditEvent event) {
172        final LocalizedMessage auditStartMessage = new LocalizedMessage(
173                Definitions.CHECKSTYLE_BUNDLE, DefaultLogger.class,
174                AUDIT_STARTED_MESSAGE);
175        infoWriter.println(auditStartMessage.getMessage());
176        infoWriter.flush();
177    }
178
179    @Override
180    public void auditFinished(AuditEvent event) {
181        final LocalizedMessage auditFinishMessage = new LocalizedMessage(
182                Definitions.CHECKSTYLE_BUNDLE, DefaultLogger.class,
183                AUDIT_FINISHED_MESSAGE);
184        infoWriter.println(auditFinishMessage.getMessage());
185        closeStreams();
186    }
187
188    @Override
189    public void fileStarted(AuditEvent event) {
190        // No need to implement this method in this class
191    }
192
193    @Override
194    public void fileFinished(AuditEvent event) {
195        infoWriter.flush();
196    }
197
198    /**
199     * Flushes the output streams and closes them if needed.
200     */
201    private void closeStreams() {
202        infoWriter.flush();
203        if (closeInfo) {
204            infoWriter.close();
205        }
206
207        errorWriter.flush();
208        if (closeError) {
209            errorWriter.close();
210        }
211    }
212}