JNI printf到log4j [英] JNI printf to log4j

查看:173
本文介绍了JNI printf到log4j的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过JAVA的JNI调用了一些C代码.

I call some C code via JNI from JAVA.

在我的C语言中,我要使用log4j记录多个printf.

In my C, I do multiple printf that I want to log with log4j.

    printf("Could not find HID device\n");
    fflush(stdout);

它们在Eclipse控制台中正常显示,使用log4j我将标准输出重定向到记录器:

They show up fine in the Eclipse console, with log4j I redirect the stdout to my logger :

        System.setOut(new PrintStream(new OutputStreamLogger(log, Priority.DEBUG), true));

当我调用"System.out.println"时,它已写入我的日志文件.

When I call "System.out.println", it's written to my log file.

但是JNI printfs没有. 他们不是在标准输出中吗?
如何将它们放入我的日志文件中?

But the JNI printfs don't. Aren't they in the stdout ?
How can I put them in my logfile ?

推荐答案

您可以做的一件事是在JNI内核中使用 dup dup2 .这样,您可以将stdout与Log4J使用的文件相关联.

One thing you can do is to use dup and dup2 inside your JNI core. This way, you can associate your stdout with the file that is used by Log4J.

int newStdout(const char *filename, fpos_t *pos)
{
  fflush(stdout);
  fgetpos(stdout, pos);
  int fd = dup(fileno(stdout));
  freopen(filename, "w", stdout);
  return fd;
}

void revertStdout(int fd, fpos_t *pos)
{
  fflush(stdout);
  dup2(fd, fileno(stdout));
  close(fd);
  clearerr(stdout);
  fsetpos(stdout, pos);
}

然后,您可以在代码中像这样使用它:

Then, in your code you can use it like this:

fpos_t pos;
char filelocation[256] = "some_place";
int fd = newStdout(filelocation, &pos);
//
//... do some stuff here ...
//... things that put data into stdout ...
//
revertStdout(fd, &pos);

这并不是您要找的东西,但仍然可以为您提供解决方案.

This is not exactly what you are looking for, but still, might be a solution for you.

这篇关于JNI printf到log4j的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆