将进程ID添加到log4cxx中的日志文件名

时间:2012-01-31 15:45:09

标签: logging log4cxx

在log4net中,我可以轻松地将进程ID设置为从配置中轻松记录文件名

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

<file type="log4net.Util.PatternString" value="Log[%processid]" />
  • 我可以从配置文件中为log4cxx做同样的事吗?
  • 如果是,怎么样?

1 个答案:

答案 0 :(得分:2)

根据log4cxx文档,目前要做到这一点 你需要声明至少一个MappedDiagnostic上下文。

这样做的未经测试的部分片段如下所示

   #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;   
  }

在进一步检查log4cxx源代码后,我意识到该文件不采用ConversionPattern,而是采用FileNamePattern。我相信当你使用TimeBasedRollingPolicy或FixedWindowRollingPolicy时,你只能使用FileNamePattern。

现在您可以将processid添加到日志中 通过在XML配置文件的appender标记中添加以下参数。

<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"/>

或者您可以通过在XML配置文件中的appender标记内指定以下布局标记将其包含在模式布局中。

 <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邮件列表线程提到了动态日志重命名,但所有这些线程都涉及到C ++代码中的大量更改,并且它们没有按照您的要求执行操作。

他们使用的方法涉及<param name="file" value="${logfilename}"/>,其中$ logfilename是由

设置的环境变量
std::string filename ="MyApp-";
filename.append(pidstring);
logger = Logger::getLogger("Nameoflogger");
setenv("logfile.name", "MyApp.log", 1);
每次要更改日志名称时,都会在C ++代码中调用类似上面的代码片段。

其他方法会涉及到log4cxx的补丁,因为它目前没有需要的功能

<强>参考

log4cxx Conversion Pattern Wiki

Short introduction to Apache log4cxx

log4cxx Tutorial

MDC log4cxx Class Reference

相关问题