View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.cling.invoker.logging;
20  
21  import java.io.OutputStream;
22  import java.io.PrintStream;
23  import java.io.PrintWriter;
24  import java.util.Objects;
25  
26  import org.apache.maven.api.annotations.Nullable;
27  import org.apache.maven.api.cli.Logger;
28  
29  import static java.util.Objects.requireNonNull;
30  
31  /**
32   * System {@link Logger}. Uses provided {@link PrintStream}s or {@link System#err} ones as fallback.
33   * This logger is used in case of "early failures" (when no logging may be set up yet).
34   */
35  public class SystemLogger implements Logger {
36      private final PrintWriter out;
37      private final Level threshold;
38  
39      public SystemLogger(@Nullable OutputStream out) {
40          this(out, null);
41      }
42  
43      public SystemLogger(@Nullable OutputStream out, @Nullable Level threshold) {
44          this.out = new PrintWriter(toPsOrDef(out, System.err), true);
45          this.threshold = Objects.requireNonNullElse(threshold, Level.INFO);
46      }
47  
48      private PrintStream toPsOrDef(OutputStream outputStream, PrintStream def) {
49          if (outputStream == null) {
50              return def;
51          }
52          if (outputStream instanceof PrintStream ps) {
53              return ps;
54          }
55          return new PrintStream(outputStream, true);
56      }
57  
58      @Override
59      public void log(Level level, String message, Throwable error) {
60          requireNonNull(level, "level");
61          requireNonNull(message, "message");
62          if (level.ordinal() >= threshold.ordinal()) {
63              out.println("[" + level.name() + "] " + message);
64              if (error != null) {
65                  error.printStackTrace(out);
66              }
67          }
68      }
69  }