View Javadoc

1   /*
2    * This file is a part of CAST project.
3    * (c) Copyright 2007, AGH University of Science & Technology
4    * https://caribou.iisg.agh.edu.pl/trac/cast
5    *
6    * Licensed under the Eclipse Public License, Version 1.0 (the "License").
7    * You may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    * http://www.eclipse.org/legal/epl-v10.html
10   */
11  /*
12   * File: LoggingUtil.java
13   * Created: 2009-09-02
14   * Author: tmilos
15   * $Id$
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   * Utility methods for logger management.
29   *
30   * @author AGH CAST Team
31   */
32  public final class LoggingUtil {
33  
34  	/**
35  	 * Re-binds {@link System#out} to given logger.
36  	 *
37  	 * @param logger
38  	 *            the logger to bind standard output to
39  	 * @return the original standard output writer
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  	 * Re-binds {@link System#err} to given logger.
52  	 *
53  	 * @param logger
54  	 *            the logger to bind standard error to
55  	 * @return the original standard error writer
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  	 * Re-binds {@link System#out} and {@link System#err} to given file.
68  	 *
69  	 * @param file
70  	 *            file to use for standard output and error streams
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  }