clog4cplus

log4cplus: use clogger API to write a single log from multiple processes


I'm using log4cplus 1.2.0 C-API for two of my C applications, running on Linux.

I want to log both processes actions on one logger. I'm using AsyncAppender, but for some reason, the prints I get are not sorted by time. When I sort the file, it all looks good, but I was looking for a solution that doesn't require any file modifications. Any ideas?

Procees 1 & 2:

#include <log4cplus/clogger.h>

int main()
{
    log4cplus_file_configure("log4cplus_test.properties");
    char msg = "Hello from Process 1"; // On process2 it will be "Hello from Process 2"

    while (1)
    {
        log4cplus_logger_log(NULL, L4CPWARN_LOG_LEVEL, msg);
        sleep(1);
    }
}

Properties file (identical to both processes):

log4cplus.rootLogger=DEBUG, R

log4cplus.appender.R=log4cplus::AsyncAppender
log4cplus.appender.R.Appender=log4cplus::FileAppender
log4cplus.appender.R.MaxFileSize=500KB
log4cplus.appender.R.MaxBackupIndex=5
log4cplus.appender.R.Appender.File=log4cplus_test.log
log4cplus.appender.R.Appender.layout=log4cplus::PatternLayout
log4cplus.appender.R.Appender.layout.ConversionPattern=%d{%m/%d/%y %H:%M:%S,%Q} %-5p %m%n

Log output:

02/13/18 08:18:49,474.596 WARN Hello from Process 1
02/13/18 08:18:50,474.937 WARN Hello from Process 1
02/13/18 08:18:51,475.395 WARN Hello from Process 1
02/13/18 08:18:52,475.857 WARN Hello from Process 1
02/13/18 08:18:53,476.392 WARN Hello from Process 1
02/13/18 08:18:54,476.885 WARN Hello from Process 1
02/13/18 08:18:55,477.332 WARN Hello from Process 1
02/13/18 08:18:56,477.785 WARN Hello from Process 1
02/13/18 08:18:57,478.267 WARN Hello from Process 1
02/13/18 08:18:58,478.744 WARN Hello from Process 1
8:05,858.108 WARN Hello from Process 2
02/13/18 08:18:06,858.571 WARN Hello from Process 2
02/13/18 08:18:07,859.072 WARN Hello from Process 2
02/13/18 08:18:08,859.560 WARN Hello from Process 2
02/13/18 08:18:09,859.992 WARN Hello from Process 2
02/13/18 08:18:10,860.431 WARN Hello from Process 2
02/13/18 08:18:11,860.877 WARN Hello from Process 2
02/13/18 08:18:12,861.364 WARN Hello from Process 2
02/13/18 08:18:13,861.984 WARN Hello from Process 2
02/13/18 08:18:14,862.504 WARN Hello from Process 2

UPDATE:

When I use log4cplus.appender.R.Appender=log4cplus::RollingFileAppender instead of log4cplus.appender.R.Appender=log4cplus::FileAppender it works perfectly fine.


Solution

  • The time stamp is the time when log4cplus' event object is created. The writes between two application might not be processed at the exactly same order as is the order of their time stamps. Thus you can see unsorted timestamps in the common logging file.

    You should probably add log4cplus.appender.R.UseLockFile=true to your configuration. Log4cplus will then use file locking to synchronize writing to log file between processes.