log4cxx asyncappender flush all logs before exiting

758 Views Asked by At

I am using Asynappender and DOMConfigurator to load the xml file. I am losing half of the logs. My application exits but only few logs appears in log file.

I have found that calling close() method of AsyncAppender class processes pending events before exiting. Does this means that it flushes all the logs to log file? And if yes then, as I don't have that object as I am simply loading file using DOMConfigurator::configure(). How can I retrieve the Asynappender object to call close()? Is there any other way to flush the logs before exiting? Using some configuration in xml file?

Below is my code for reference:

#include <log4cxx/logger.h>
#include <log4cxx/xml/domconfigurator.h>
#include<iostream>

using namespace log4cxx;
using namespace log4cxx::xml;
using namespace log4cxx::helpers;

LoggerPtr loggerMyMain(Logger::getLogger( "main"));

int main(int args, char **argv)
{
    DOMConfigurator::configure("asynclog4cxxconfig.xml");

    LOG4CXX_TRACE(perf, "this is a performance message!!!");
    LOG4CXX_DEBUG(loggerMyMain, "this is a debug message.");
    LOG4CXX_WARN (loggerMyMain, "this is a warn message, not too bad.");
    LOG4CXX_ERROR(loggerMyMain, "this is a error message, something serious is happening.");
    LOG4CXX_FATAL(loggerMyMain, "this is a fatal message!!!");

    return 0;
}

Below is the XML file:

<?xml version="1.0" encoding="UTF-8" ?>
 <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  <appender name="appxNormalAppender" class="org.apache.log4j.RollingFileAppender">
    <param name="file" value="logfile" />
    <param name="MaxFileSize" value="1000KB" />
    <param name="MaxBackupIndex" value="3" />
    <param name="append" value="true" />
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%X{process} %d %-5p %C{2} (%F:%L) - %m%n" />
    </layout>
  </appender>

  <appender name="async_appxNormalAppender" class="org.apache.log4cxx.AsyncAppender">
     <appender-ref ref="appxNormalAppender"/>
  </appender>

   <root>
       <priority value="debug" />
       <appender-ref ref="async_appxNormalAppender"/>
  </root>
</log4j:configuration>
1

There are 1 best solutions below

0
aaa On

The problem got solved, posting it here if it helps someone. Added the below piece of code at the end.

LoggerPtr root_logger = Logger::getRootLogger();
AppenderPtr app_ptr = root_logger->getAppender("async_appxNormalAppender");
if(app_ptr != NULL)
   app_ptr->close();