使用log4php将标头写入日志

时间:2016-06-04 06:37:56

标签: php log4php

我使用log4php将分号分隔的值记录到csv文件中。 我想在第一行写一个标题。如何做到这一点?

示例

消息ID,文件名,开始时间,结束时间,状态 MSGID1000; SAMPLE.TXT; 01:05:55; 07:08:44; OK MSGID1000; SAMPLE.TXT; 01:05:55; 07:08:44; NOK

我这样做

csvLogger = Logger::getRootLogger();
csvLogger->setLevel(LoggerLevel::toLevel(LoggerLevel::DEBUG));
csvLogger->removeAllAppenders();

$appender = new LoggerAppenderFile("csvLogAppender");
$appender->setFile("LogMessage.csv");
$appender->setAppend(false);   

csvLogger->addAppender($appender); 

1 个答案:

答案 0 :(得分:0)

我找到了扩展LoggerLayoutPattern并覆盖getHeader()方法的解决方案。

class csvLoggerLayoutPattern extends LoggerLayoutPattern {
    public function getHeader() {
        return "message id, file name, start time, end time, status\n";
    }
}

csvLogger = Logger::getRootLogger();
csvLogger->setLevel(LoggerLevel::toLevel(LoggerLevel::DEBUG));
csvLogger->removeAllAppenders();

$appender = new LoggerAppenderFile("csvLogAppender");
$appender->setFile("LogMessage.csv");
$appender->setAppend(false);

$appenderlayout = new csvLoggerLayoutPattern();
$appenderlayout->activateOptions();
$appender->setLayout($appenderlayout);

csvLogger->addAppender($appender);