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;
20
21 import java.io.OutputStream;
22 import java.io.PrintStream;
23 import java.io.PrintWriter;
24
25 import org.apache.maven.api.annotations.Nullable;
26 import org.apache.maven.api.cli.Logger;
27
28 /**
29 * Proto {@link Logger}. Uses provided {@link PrintStream}s or {@link System} ones as fallback.
30 * Supports only two levels: ERROR and WARNING, that is emitted to STDERR and STDOUT.
31 */
32 public class ProtoLogger implements Logger {
33
34 private final PrintWriter out;
35 private final PrintWriter err;
36
37 public ProtoLogger() {
38 this(null, null);
39 }
40
41 public ProtoLogger(@Nullable OutputStream out, @Nullable OutputStream err) {
42 this.out = new PrintWriter(toPsOrDef(out, System.out), true);
43 this.err = new PrintWriter(toPsOrDef(err, System.err), true);
44 }
45
46 private PrintStream toPsOrDef(OutputStream outputStream, PrintStream def) {
47 if (outputStream == null) {
48 return def;
49 }
50 if (outputStream instanceof PrintStream ps) {
51 return ps;
52 }
53 return new PrintStream(outputStream);
54 }
55
56 //
57 // These are the only methods we need in our primordial logger
58 //
59
60 @Override
61 public void log(Level level, String message, Throwable error) {
62 PrintWriter pw = level == Level.ERROR ? err : level == Level.WARN ? out : null;
63 if (pw != null) {
64 pw.println(level.name() + " " + message);
65 if (error != null) {
66 error.printStackTrace(pw);
67 }
68 }
69 }
70 }