Stderr and stdout recording to console

advertisements

This question already has an answer here:

  • System.out to a file in java 7 answers

I want to move stderr and stdout to the console and move them to some file .

Suppose In my java class I write siome logger statements .. Info,WARN .. and some exception( throw new Runtime Exception ) is coming which is going to the stderr

and I invoke that java class from script and move it to some file .

I want that file contains both logger and exception .

import org.apache.log4j.Logger;

public class HelloExample2{

    final static Logger logger = Logger.getLogger(HelloExample2.class);

    public static void main(String[] args) {

            HelloExample2 obj = new HelloExample2();
            try{
                    obj.divide();
            }catch(ArithmeticException ex){
                    System.out.println("yeah buddy .. puchi");
                    logger.error("Sorry, something wrong!");
                    ex.printStackTrace();
            }

    }

    private void divide(){

            int i = 10 /0;

    }

}

I want both ERROR log and exception get printed to some file

I am running my program like :-- ./script_invoke_java > somefile.log

this file contains both loggers and exception ( I am taking about exceptions system.out are coming in file ). I want to do this using log4J any suggestions ??


You want your call to look like this:

logger.error("Sorry,...", ex);

Take a look at the javadoc

If you don't want to edit the java file itself, you can use shell redirection:

./script_invoke_java &> output.log