Add process id to log file name in log4cxx

In log4net, I can easily set the process id for the easy log file name from the configuration

<appender name="LogFileAppender" 
type="log4net.Appender.RollingFileAppender,log4net">

<file type="log4net.Util.PatternString" value="Log[%processid]" />
  • Can I do the same for log4cxx from the configuration file?
  • If so, how?
+2
source share
1 answer

According to the log4cxx documentation, to do this now you need to declare at least one MappedDiagnostic context.

An unverified fragment of this fragment is shown below.

   #include <sys/types.h>
   #include <log4cxx/mdc.h>
   #include <iostream>
   #include <sstream>


   int main (int argc, char **argv)
   {
   //at the start of your program
   pid_t pid = getpid(); 
   pid_t tid = gettid();
   std::string pidstring;
   std::string tidstring;
   std::stringstream buffer;   
   buffer << pid << std::endl;
   pidstring = buffer.str();
   buffer.str(std::string());
   buffer << tid << std::endl;
   tidstring = buffer.str();
   buffer.str(std::string());
   MDC::put( "pid", pidstring);
   MDC::put( "tid", tidstring);
   // do actual stuff here

  return 0;   
  }

After further checking the source of log4cxx, I realized that the file does not accept ConversionPattern, but FileNamePattern. I believe that you can use FileNamePattern when using TimeBaseRollingPolicy or FixedWindowRollingPolicy.

processid appender XML.

<rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
              <param name="FileNamePattern" value="MyApplication-%d{yyyy-MM-dd}- %X{pid}.log"/>
              <param name="activeFileName" value="MyApplication.log"/>
</rollingPolicy>
<param name="file" value="appxDailyLog.log"/>

, appender XML.

 <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%X{pid} %X{tid} %d{yyyy-MM-dd HH:mm:ss,SSS}"/>
 </layout>

, , log4net.

log4cxx, , ++, , .

<param name="file" value="${logfilename}"/>, $logfilename - ,

std::string filename ="MyApp-";
filename.append(pidstring);
logger = Logger::getLogger("Nameoflogger");
setenv("logfile.name", "MyApp.log", 1);

- ++, , .

log4cxx, , .

log4cxx -

Apache log4cxx

log4cxx

MD4 log4cxx

+2

All Articles