Pull to refresh

Перенаправление/дублирование системного вывода в Java

Reading time3 min
Views5.1K
Тут недавно в инете наткнулся на линк, где описывалось, как в Java перенаправить системный вывод в файл, имеется ввиду System.out и System.err. С помощью всего одного дополнительно класса + еще несколько строк кода, и мы можем получить неплохой логгер. Все настолько просто, что нет слов, однако не знал раньше… Смотрим!

Перенаправление в файлы (можно в один и тот же)

Main.java
public static void main(String[] args) throws FileNotFoundException {
    PrintStream out = new PrintStream(new FileOutputStream("out.log"));
    PrintStream err = new PrintStream(new FileOutputStream("err.log"));
    System.setOut(out);
    System.setErr(err);   
    System.out.println("Hello!");
    String [] array = {"1", "2", "3"};
    System.out.println(array[5]);  // тут специально вызываем исключение
    
  }


* This source code was highlighted with Source Code Highlighter.


out.log
Hello!

err.log
Exception in thread «main» java.lang.ArrayIndexOutOfBoundsException: 5
at systemout.Main.main(Main.java:38)



Перенаправление в файлы и в консоль IDE

Для перенаправления вывода и в консоль и в файл, нам понадобится класс, расширяющий PrintStream:

DualStream.java
public class DualStream extends PrintStream {

  PrintStream out;

  public DualStream(PrintStream out1, PrintStream out2) {
    super(out1);
    this.out = out2;
  }

  public void write(byte buf[], int off, int len) {
    try {
      super.write(buf, off, len);
      out.write(buf, off, len);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void flush() {
    super.flush();
    out.flush();
  }
}


* This source code was highlighted with Source Code Highlighter.


Тут мы расширили класс PrintStream, путем добавления еще одного поля типа PrintStream, а так же переопределили два метода.

Main.java
public static void main(String[] args) throws FileNotFoundException {

    PrintStream out = new PrintStream(new FileOutputStream("out.log"));
    PrintStream dual = new DualStream(System.out, out);
    System.setOut(dual);

    PrintStream err = new PrintStream(new FileOutputStream("err.log"));
    dual= new DualStream(System.err, err);
    System.setErr(dual);

    System.out.println("Hello!");
    String [] array = {"1", "2", "3"};
    System.out.println(array[5]);
    
  }


* This source code was highlighted with Source Code Highlighter.



out.log
Hello!

err.log
Exception in thread «main» java.lang.ArrayIndexOutOfBoundsException: 5
at systemout.Main.main(Main.java:38)


console
Hello!
Exception in thread «main» java.lang.ArrayIndexOutOfBoundsException: 5
at systemout.Main.main(Main.java:38)



Вот таким образом можно получить простой логгер, который подойдет для различных задач.

Tags:
Hubs:
Total votes 10: ↑7 and ↓3+4
Comments10

Articles