1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.core;
15
16 import java.io.OutputStream;
17 import java.io.PrintStream;
18 import java.lang.reflect.Method;
19 import java.util.Arrays;
20
21 import ch.qos.logback.core.joran.spi.ConsoleTarget;
22 import ch.qos.logback.core.status.Status;
23 import ch.qos.logback.core.status.WarnStatus;
24 import ch.qos.logback.core.util.Loader;
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 public class ConsoleAppender<E> extends OutputStreamAppender<E> {
42
43 protected ConsoleTarget target = ConsoleTarget.SystemOut;
44 protected boolean withJansi = false;
45
46 private final static String AnsiConsole_CLASS_NAME = "org.fusesource.jansi.AnsiConsole";
47 private final static String wrapSystemOut_METHOD_NAME = "wrapSystemOut";
48 private final static String wrapSystemErr_METHOD_NAME = "wrapSystemErr";
49 private final static Class<?>[] ARGUMENT_TYPES = { PrintStream.class };
50
51
52
53
54
55 public void setTarget(String value) {
56 ConsoleTarget t = ConsoleTarget.findByName(value.trim());
57 if (t == null) {
58 targetWarn(value);
59 } else {
60 target = t;
61 }
62 }
63
64
65
66
67
68
69
70 public String getTarget() {
71 return target.getName();
72 }
73
74 private void targetWarn(String val) {
75 Status status = new WarnStatus("[" + val + "] should be one of " + Arrays.toString(ConsoleTarget.values()),
76 this);
77 status.add(new WarnStatus("Using previously set target, System.out by default.", this));
78 addStatus(status);
79 }
80
81 @Override
82 public void start() {
83 OutputStream targetStream = target.getStream();
84
85 if (withJansi) {
86 targetStream = wrapWithJansi(targetStream);
87 }
88 setOutputStream(targetStream);
89 super.start();
90 }
91
92 private OutputStream wrapWithJansi(OutputStream targetStream) {
93 try {
94 addInfo("Enabling JANSI AnsiPrintStream for the console.");
95 ClassLoader classLoader = Loader.getClassLoaderOfObject(context);
96 Class<?> classObj = classLoader.loadClass(AnsiConsole_CLASS_NAME);
97 String methodName = target == ConsoleTarget.SystemOut ? wrapSystemOut_METHOD_NAME
98 : wrapSystemErr_METHOD_NAME;
99 Method method = classObj.getMethod(methodName, ARGUMENT_TYPES);
100 return (OutputStream) method.invoke(null, new PrintStream(targetStream));
101 } catch (Exception e) {
102 addWarn("Failed to create AnsiPrintStream. Falling back on the default stream.", e);
103 }
104 return targetStream;
105 }
106
107
108
109
110 public boolean isWithJansi() {
111 return withJansi;
112 }
113
114
115
116
117
118
119
120 public void setWithJansi(boolean withJansi) {
121 this.withJansi = withJansi;
122 }
123
124 }