1. 程式人生 > >log4qt 輸出到控制檯和檔案

log4qt 輸出到控制檯和檔案

  1. 輸出到控制檯
    // 建立一個 TTCCLayout(輸出時間、執行緒、Logger 以及訊息內容)
       Log4Qt::Logger *logger = Log4Qt::Logger::rootLogger();
       Log4Qt::TTCCLayout *layout = new Log4Qt::TTCCLayout();
       layout->setName("My Layout");
       layout->activateOptions();

       // 建立一個 ConsoleAppender(將日誌內容輸出到控制檯上)
       Log4Qt::ConsoleAppender *appender = new Log4Qt::ConsoleAppender();
       appender->setName("My Appender");
       appender->setLayout(layout);
       appender->setEncoding(QTextCodec::codecForName("UTF-8"));  // 設定編碼
       appender->setTarget(Log4Qt::ConsoleAppender::STDOUT_TARGET);  // 輸出到 stdout
       appender->setImmediateFlush(true);  // 立即重新整理
       appender->setThreshold(Log4Qt::Level::INFO_INT);  // 設定閾值級別為 INFO
       appender->activateOptions();

       // 在 logger 上新增 appender
       logger->addAppender(appender);

       // 設定級別為 DEBUG
       logger->setLevel(Log4Qt::Level::DEBUG_INT);

  1. 輸出到檔案
    //log pattern
    Log4Qt::Logger *log = Log4Qt::Logger::rootLogger();
    Log4Qt::PatternLayout *lay = new Log4Qt::PatternLayout(Log4Qt::PatternLayout::TTCC_CONVERSION_PATTERN);
    lay->setConversionPattern("%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n");


    Log4Qt::FileAppender *fileappender = new Log4Qt::FileAppender(lay, QString(LOG_PATH) + "/TagDataMonitorLog_"+QDateTime::currentDateTime().toString("yyyyMMddhhmmss")+ ".log");
    fileappender->setAppendFile(true);
    fileappender->activateOptions();
    fileappender->setEncoding(QTextCodec::codecForName("UTF-8"));
    log->addAppender(fileappender);

    delete dirtmp;
    log->deleteLater();