0

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 ??

Prashant Gautam
  • 589
  • 8
  • 10

2 Answers2

4

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
V a a m Y o b
  • 492
  • 3
  • 7
  • you are telling is one way of doing this but this is not feasible in my case as I have to change in lots of classes and have to add try and catch .. – Prashant Gautam Aug 27 '15 at 15:28
  • updated answer with alternate approach – V a a m Y o b Aug 27 '15 at 15:32
  • yes Thanks it is working. we can do something in log4j.properties otherwise I have to change lots of script files as I am referrring to same log4j in my project ?? Something like below :-- it is not working right now log4j.rootLogger=, stdout, stderr # configure stdout log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = %-5 – Prashant Gautam Aug 27 '15 at 15:36
  • If the answer worked for the original question, can you kindly click to accept the answer? – V a a m Y o b Aug 27 '15 at 21:11
1

Maybe org.apache.logging.log4j.io.LoggerPrintWriter is something for you. You can create a instance of it and set it as System.out and System.err. This class will forward everything to a log4j logger with specific parameters and you can use log4j to put what every you like in a file.

Nitram
  • 6,486
  • 2
  • 21
  • 32