javaloggingjschsystem.err

Does jsch session own error stream, when it is set, and no other thread can use it?


I am creating jsch session to run commands remotely and I am facing a strange behavior. In one of my threads I create session, set output stream to System.err and use the session.

ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setErrStream(System.err);

In another thread I have some stuff which uses Java util's logger (which by default writes logs to System.err). Once jsch session is created, I no longer see logger messages in console from my second thread. When I remove this line:

channel.setErrStream(System.err);

or set channel's error stream to null, logger messages from my second thread appear in console just fine.

If jsch session owns System.err stream when setting it, and that's why logger can't use, then what happens when error stream for session is set null? If this is not the case, then why logger messages do not appear after session starts using System.err?

If any one could explain this, that would be very useful.


Solution

  • You can find an online copy of the Jsch javadoc here. This page documents ChannelExec. The description of the single-argument version of setErrStream() says this (emphasis added):

    public void setErrStream(OutputStream out)

    Sets the error stream. The standard error output of the remote process will be sent to this stream. The stream will be closed on Channel.disconnect(com.jcraft.jsch.Session).

    In other words, passing System.err to this function will cause Jsch to close it when disconnecting the channel. Once System.err is closed, other parts of your program--such as the logger--won't be able to write to System.err.

    The documentation describes another version of setErrorStream() which takes two arguments:

    public void setErrStream(OutputStream out, boolean dontclose)

    Sets the error stream. The standard error output of the remote process will be sent to this stream.

    Parameters:

    dontclose - if true, we do not close the stream on Channel.disconnect(com.jcraft.jsch.Session).

    In other words, this version of the function lets you control whether the error stream should be closed or not when disconnecting the channel.