My java app uses JNI to invoke a library written in C. This native library logs errors to stderr but I would like to redirect the error stream through my log4j logger somehow. Is this possible?
The C library is external - I don't have the source, so cannot change it.
Thanks
Note: I have not tried this answer; YMMV.
The POSIX method freopen
will change the underlying file associated with a stream. As the manpage states: "The primary use of the freopen() function is to change the file associated with a standard text stream (stderr, stdin, or stdout)".
So, you could create your own JNI library that simply redirects the stream into a file. However, there are several serious roadblocks to making this work:
System.out
et al
to something else when your program starts up. That last point is by far the biggest: stdio writes to an OS-level file descriptor. You would have to create some Java-level code to read that descriptor and write to a log. My first thought is that you'd have to use a named pipe, and then spin up a new Java thread to read that pipe. But that won't be portable to different operating systems, and will that you manage the pipe name in your program's configuration.
Assuming that this is a server program, and does not itself process the standard IO streams, I think your best solution will be to configure Log4J with a console logger, and simply redirect all console output to a file.
Or talk to the people who wrote the library, to get them to add configurable logging.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With