1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package pl.edu.agh.cast.util.logging;
19
20 import java.io.File;
21 import java.io.FileOutputStream;
22 import java.io.IOException;
23 import java.io.PrintStream;
24
25 import org.apache.log4j.Logger;
26
27
28
29
30
31
32 public final class LoggingUtil {
33
34
35
36
37
38
39
40
41 public static PrintStream rebindStdOut(Logger logger) {
42 PrintStream stdout = System.out;
43
44 LoggingOutputStream los = new LoggingOutputStream(logger, StdOutLevel.STDOUT);
45 System.setOut(new PrintStream(los, true));
46
47 return stdout;
48 }
49
50
51
52
53
54
55
56
57 public static PrintStream rebindStdErr(Logger logger) {
58 PrintStream stderr = System.err;
59
60 LoggingOutputStream los = new LoggingOutputStream(logger, StdErrLevel.STDERR);
61 System.setErr(new PrintStream(los, true));
62
63 return stderr;
64 }
65
66
67
68
69
70
71
72 @SuppressWarnings("nls")
73 public static void rebindStdOutErr(File file) {
74 if (file == null) {
75 return;
76 }
77
78 PrintStream stdout = System.out;
79 PrintStream stderr = System.err;
80
81 PrintStream fos = null;
82 try {
83 fos = new PrintStream(new FileOutputStream(file));
84 System.setOut(fos);
85 System.setErr(fos);
86 System.out.println("-- STDOUT--");
87 System.err.println("-- STDERR--");
88 } catch (IOException e) {
89 System.setOut(stdout);
90 System.setErr(stderr);
91 if (fos != null) {
92 fos.close();
93 }
94 System.err.println("Failed to redirect stdout and stderr to " + file.toString());
95 e.printStackTrace();
96 }
97 }
98 }