Send JNI C stderr / stdout via log4j

My java application uses JNI to call a library written in C. This native library logs errors in stderr, but I would like to somehow redirect the error stream through the log4j log. Is it possible?

The C library is external - I have no source, so I can not change it.

thanks

+6
java logging jni
source share
2 answers

Note. I have not tried this answer; YMMV.

The POSIX freopen method will modify the underlying file associated with the stream. As the manpage says: "The main use of the freopen () function is to modify the file associated with a standard text stream (stderr, stdin or stdout)."

So, you can create your own JNI library, which simply redirects the stream to a file. However , there are several serious barriers to doing this work:

  • You need to make sure that your Java program itself does not use standard threads, because they will be redirected too. A workaround for this change is System.out et al. something else when your program starts.
  • It is possible that a third-party library bypasses the standard text streams and writes directly to the main file descriptor. This is unlikely, but possible. I cannot remember, freopen () simply changes the file descriptor, the buffered stream used, or actually reopens the underlying fd.
  • You will still have a connection problem being changed to a β€œfile” by the registrar.

This last point is by far the biggest one: stdio writes to the OS-level file descriptor. You will need to create Java-level code to read this descriptor and write to the log. My first thought is that you have to use a named pipe and then deploy a new Java thread to read that pipe. But this will not be transferred to different operating systems and will control the channel name in your program configuration.

Assuming that this is a server program and does not process standard input / output streams, I think that the best solution would be to configure Log4J using the console logger and simply redirect all console outputs to a file.

Or talk to the people who wrote the library to add them to custom logging.

+3
source share

My C is a little rusty, but it's possible, since you can call PrinStream methods from C through JNI. But you will need to find a way to connect when the stream is recorded.

Update. This can help you connect to stdout output from C:

http://www.gnu.org/software/hello/manual/libc/Hook-Functions.html

-one
source share

All Articles