Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging messages from C++ to Java

Tags:

java

c++

logging

I have a library in C++ which is being used by a Java app through JNI. In the Java app I'm using logback to produce logs.

Now I need to log the C++ library messages as well and I have to do it in the same file used by Java so I can have everything in chronological order.

My current approach, not yet implemented, is to create a C++ class named Logger that will send the messages to Java through JNI and then Java will log these messages. The disadvantage is that I'm losing Logback functionalities like logging the name of the thread or the line of the code that produced the log.

Is there a better way?

like image 468
dablak Avatar asked Jun 19 '13 13:06

dablak


People also ask

How do you log messages in Java?

Java Logging FormattersSimpleFormatter: This formatter generates text messages with basic information. ConsoleHandler uses this formatter class to print log messages to console. XMLFormatter: This formatter generates XML message for the log, FileHandler uses XMLFormatter as a default formatter.

How do you create a logger in Java?

The process of creating a new Logger in Java is quite simple. You have to use Logger. getLogger() method. The getLogger() method identifies the name of the Logger and takes string as a parameter.

Does Java Util logging use Log4j?

The JDK Logging Adapter is a custom implementation of java. util. logging. LogManager that uses Log4j.

Which logging framework is best for Java?

One of the most popular solutions for the Java world is the Apache Log4j 2 framework.


2 Answers

An easy solution would be to use a common service for logging such as syslog. In your Java code, set the appropriate appender to write the logs to syslog. In your C++ code, simply call syslog natively. All logs will be combined in a chronological order by syslog.

like image 171
abu.marcose Avatar answered Oct 23 '22 21:10

abu.marcose


A possible solution I've used in the past:-

  1. Use logback with a database appender. The DB will ensure transactional commits in order, with a timestamp. In some databases you can make it a trigger and use the native timestamp which may be more efficient.

  2. C++ part will need to have a similar appender and/or modified to write to the same table. (log4cpp works, or if you have a proprietary one, it may need to be modified slightly)

  3. Select * from table order by timestamp asc output to a file will give you the logs in order.

In my last place we used sqlite for storing these logs as the overhead was tiny compared to oracle or a more heavy duty one and we could delete the file if needed later.

like image 25
Delta_Fore Avatar answered Oct 23 '22 20:10

Delta_Fore