java - 将 log4j 与 SWIG/JNI 集成?

标签 java c++ java-native-interface log4j swig

我正在开发一个具有 C++ 模块的 Java 程序。我希望将我的 C++ 标准输出/标准错误发送到 slf4j/log4j 记录器。

一些可能性:

  1. 让我的 C++ 模块在返回并发送到记录器的字符串中捕获 stdout/stderr。缺点是 C++ 模块可能很昂贵,而且这将是异步的。
  2. 让我的 Java 软件创建/管理一个 C++ 模块可以写入的临时文件。完成后,我的软件将读取并删除文件并将数据发送到 slf4j。
  3. 有什么方法可以通过我的 swig 接口(interface)从 log4j 获取 ostream 吗?
  4. 看起来我可以create a Director在 swig 中将字符串从 C++ 传递给 Java 以转发给记录器。

其他人是如何解决这个问题的?

最佳答案

要将 C++(通过 SWIG 生成的包装器调用)记录到 log4j,您需要解决三个问题:

  1. 我们如何捕获 C++ 输出(即 Hook iostream 对象)。
  2. 我们如何将此 Hook 插入到生成的包装器中。
  3. 我们如何使用捕获的内容实际调用 log4j。

在回答这个问题时,我编写了以下头文件来演示我的解决方案是如何工作的:

#include <iostream>

void test1() {
  std::cout << "OUT: " << "test1\n";
  std::cerr << "ERR: " << "test1\n";
}

struct HelloWorld {
  static void test2() {
    std::cout << "OUT: " << "test2\n";
    std::cerr << "ERR: " << "test2\n";
  }

  void test3() const {
    std::cout << "OUT: " << "test3\n";
    std::cerr << "ERR: " << "test3\n";
  }
};

最后,我希望看到 std::coutstd::cerr 都以正确的顺序进入 log4j。我有 answered that question before ,在这种情况下,为了保持简单和便携,我开始使用 rdbuf()std::coutstd::cerr 使用的内部缓冲区交换为我在 std::stringstream 中实际创建的缓冲区>,类似于:

std::stringstream out; // Capture into this

// Save state so we can restore it
auto old_buf = std::cout.rdbuf();
// Swap buffer on cout
std::cout.rdbuf(out.rdbuf());

// Do the real call to C++ here
// ...

// Reset things
std::cout.rdbuf(old_buf);

// Walk through what we captured in out

当然这不会捕获 libc 函数(printf() 等)或系统调用(write() 等)的输出,但它会获取所有你的标准 C++ 输出。

所以这是问题 #1 从我们的列表中划掉了。对于问题 #2 SWIG 有 %exception directive这非常符合我们想要做的事情,它让我们有机会在调用包装函数之前和之后执行 C++ 代码。在上面的例子中,我们需要做的就是使用特殊变量 $action 来让替换发生在注释“在这里对 C++ 进行真正的调用”的地方。

对于问题 #3,我们需要进行一些 Java 调用。我开始认为 JNI 不会太糟糕,也许有点冗长。基本上我们要做的就是复制以下 Java 代码 ( from the log4j docs ):

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class HelloWorld {
    private static final Logger logger = LogManager.getLogger("HelloWorld");
    public static void main(String[] args) {
        logger.info("Hello, World!");
    }
}

但在 JNI 而不是 Java 中并将正确的字符串传递到 getLogger 调用中。

因此,将所有这些组合到一个 SWIG 界面中,我们得到:

%module test

%{
#include "test.hh"
#include <sstream>
#include <cassert>
static const char *defaultLogname="$module"; // Use if we're not in a class
%}

// Exception handling for all wrapped calls
%exception {
  // Hook output into this:
  std::stringstream out;

  // Save old states
  auto old_outbuf = std::cout.rdbuf();
  auto old_errbuf = std::cerr.rdbuf();
  // Do actual buffer switch
  std::cout.rdbuf(out.rdbuf());
  std::cerr.rdbuf(out.rdbuf());
  try {
    $action
  }
  catch (...) {
    // TODO: use RAII instead of poor finally substitute?
    std::cout.rdbuf(old_outbuf);
    std::cerr.rdbuf(old_errbuf);
    throw;
  }
  // Restore state
  std::cout.rdbuf(old_outbuf);
  std::cerr.rdbuf(old_errbuf);

  // JNI calls to find mid and instance for Logger.error(String) for the right name
  static const std::string class_name = "$parentclassname";
  // prepare static call to org.apache.logging.log4j.LogManager.getLogger(String)
  // start with class lookup:
  jclass logmanagercls = JCALL1(FindClass, jenv, "org/apache/logging/log4j/LogManager");
  assert(logmanagercls);
  // find method ID for right overload of getLogger
  jmethodID getloggermid = JCALL3(GetStaticMethodID, jenv, logmanagercls, "getLogger", "(Ljava/lang/String;)Lorg/apache/logging/log4j/Logger;");
  assert(getloggermid);

  // Prep name strign to pass into getLogger
  jstring logname = JCALL1(NewStringUTF, jenv, (class_name.size() ? class_name.c_str(): defaultLogname));

  // Actually get the Logger instance for us to use
  jobject logger = JCALL3(CallStaticObjectMethod, jenv, logmanagercls, getloggermid, logname);
  assert(logger);
  // Lookup .error() method ID on logger, we need the jclass to start
  jclass loggercls = JCALL1(GetObjectClass, jenv, logger);
  assert(loggercls);
  // and the method ID of the right overload
  jmethodID errormid = JCALL3(GetMethodID, jenv, loggercls, "error", "(Ljava/lang/String;)V");
  assert(errormid);

  // Loop over all the lines we got from C++:
  std::string msg;
  while(std::getline(out, msg)) {
    // Pass string into Java logger
    jstring jmsg = JCALL1(NewStringUTF, jenv, msg.c_str());
    JCALL3(CallVoidMethod, jenv, logger, errormid, jmsg);
  }
}

// And of course actually wrap our test header    
%include "test.hh"

我添加了一些 Java 来证明这是可行的:

public class run {
  public static void main(String[] argv) {
    System.loadLibrary("test");
    test.test1();
    HelloWorld.test2();
    HelloWorld h1 = new HelloWorld();
    h1.test3();    
  }
}

使用当前目录中的 log4j 2.6 jar 编译并运行:

swig3.0 -c++ -java -Wall test.i
javac *.java
g++ -std=c++1y -Wall -Wextra -shared -o libtest.so test_wrap.cxx -I/usr/lib/jvm/default-java/include/ -I/usr/lib/jvm/default-java/include/linux -fPIC 
LD_LIBRARY_PATH=. java -classpath log4j-api-2.6.jar:log4j-core-2.6.jar:. run

当运行给出:

ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
22:31:08.383 [main] ERROR test - OUT: test1
22:31:08.384 [main] ERROR test - ERR: test1
22:31:08.386 [main] ERROR HelloWorld - OUT: test2
22:31:08.386 [main] ERROR HelloWorld - ERR: test2
22:31:08.386 [main] ERROR HelloWorld - OUT: test3
22:31:08.386 [main] ERROR HelloWorld - ERR: test3

讨论要点:

  • JNI 冗长吗?肯定是的,但这是否足以走另一条路?对我来说不是(尽管导演的想法是可行的,但由于complexities with producing interfaces,它并不像听起来那么简单)
  • 此处日志事件的时间戳将是“错误的”,因为捕获的所有日志信息都将在底层 C++ 函数调用返回后推出,而不是在其执行期间推出
  • cout/cerr 消息混合在一起并在同一级别记录。我这样做是因为前一点,如果他们没有像这样混合,那么如果不做更多的工作就不可能获得相对顺序
  • 如果您的 C++ 方法产生大量输出,缓冲区将变得相当大
  • 如果您有一个大型 C++ 项目,我希望您使用的日志记录框架比 iostreams 更好。如果是这种情况,您最好使用适配器实现其输出接口(interface),该适配器直接传递给 Java,并保留时间戳、日志级别等信息。 (反之亦然)
  • 即使坚持使用 iostream,Boost iostreams 库也可以更轻松地1编写一些在输出写入发生时 Hook 的东西,而不是当前的 Hook 技术(但引入了更大的依赖性,因此它是权衡)。您也可以在没有提升的情况下完成它,但是 basic_streambuf 类相当笨重。

1 如果您有兴趣,我可能可以在这个答案中说明提升版本。

关于java - 将 log4j 与 SWIG/JNI 集成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37597545/

相关文章:

c# - 是否有涵盖变量作用域的代码指标

java - 如何从 java 中的 URL 读取 XML 响应?

python - 在 python 中打开共享对象文件时出错(OSError : cannot open shared object file: No such file or directory)

c++ - 哪个 vector 和 map 使用更少的内存(大量数据和未知大小)

java - 如何在Android Studio中使用.so文件中的方法?

java - 如何将ArrayList转换为JList对象? java

c++ - 关于运算符+重载

java - 通过命令行与 JNI 调用

java - 如何使用 Javah 创建 C 头文件?

java - 我的 RMI 服务器中的对象为空