Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

can you redirect System.err to a file?

Status
Not open for further replies.

excession

Programmer
Sep 22, 2004
111
GB
Is it possible to redirect System.err to a file so that all errors are logged?

 
Take a look at setErr method at java.lang.System class.

Cheers,

Dian
 
Yes. All you have to do is set a string object equal to System.err.toString(), get a byte[] of the string and write it to a file.

Code:
FileOutputStream file = new FileOutputStream("log.txt");
for (int i = 0; i < bytes.length; i++)
     file.write(bytes[i]);
file.close();
 
ah ha, something like:
Code:
try {
            PrintStream out =
            new PrintStream(
            new BufferedOutputStream(
            new FileOutputStream("errorlog.txt")));
            
            System.setErr(out);
            System.err.println("testing 1 2 3");
            out.close();
        } catch (IOException e){
            e.printStackTrace();
        }


[smile]
 
if I redirect the System.err in my main class, does this automatically affect all objects it creates?
 
AFAIK, there's just an stderr for each virtual machine.

Cheers,

Dian
 
stdout and stderr are OS level file descriptors (in the C sense).

In Java System.err amd System.out are just stream objects basically that map to the OS's stdout and stderr.

So In Java, as in C, if you remap stdout and stderr to some other file descriptor then all calls to those handles will be redirected until the process (in Java, the JVM process) exits, or the streams are redirected/closed again.

--------------------------------------------------
Free Database Connection Pooling Software
 
What is the effect, if the user redirects the errorstream on the commandline (let's say, to a different file)?

I guess in most cases, it should be left to the user to redirect the errorstream.
He knows, where it is possible and appropriate to log to, and might wish to perform special handlings to the errorstream like tee-ing, filtering etc.

seeking a job as java-programmer in Berlin:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top