LogFile

不聞窗外事發表於2020-10-31

 LogFile類就是提供同步的檔案輸出,在上一篇Logging的文章中,提到了設定輸出函式和重新整理IO緩衝函式,使用LogFile很簡單, 主要方法就是將該類的append和flush設定為Logger類的輸出和重新整理IO緩衝函式。

// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
//
// Author: Shuo Chen (chenshuo at chenshuo dot com)

#include "muduo/base/LogFile.h"

#include "muduo/base/FileUtil.h"
#include "muduo/base/ProcessInfo.h"

#include <assert.h>
#include <stdio.h>
#include <time.h>

using namespace muduo;

LogFile::LogFile(const string& basename,
                 off_t rollSize,
                 bool threadSafe,
                 int flushInterval,
                 int checkEveryN)
  : basename_(basename), //檔名
    rollSize_(rollSize), //日誌檔案滾動的大小
    flushInterval_(flushInterval), //重新整理緩衝時間間隔
    checkEveryN_(checkEveryN),        //每寫入checkEveryN_條日誌後進行檢查
    count_(0),       //統計是否達到checkEveryN_條
    mutex_(threadSafe ? new MutexLock : NULL), //是否需要做到執行緒安全
    startOfPeriod_(0),           //開始時間,以天為單位
    lastRoll_(0),        //上次滾動時間
    lastFlush_(0)        //上次重新整理時間
{
  assert(basename.find('/') == string::npos);
  rollFile();
}

LogFile::~LogFile() = default;

void LogFile::append(const char* logline, int len)
{
  if (mutex_)
  {
    MutexLockGuard lock(*mutex_);
    append_unlocked(logline, len);
  }
  else
  {
    append_unlocked(logline, len);
  }
}

void LogFile::flush()
{
  if (mutex_)
  {
    MutexLockGuard lock(*mutex_);
    file_->flush();
  }
  else
  {
    file_->flush();
  }
}

void LogFile::append_unlocked(const char* logline, int len)
{
  file_->append(logline, len);

  if (file_->writtenBytes() > rollSize_)
  {
    rollFile();
  }
  else
  {
    ++count_;
    if (count_ >= checkEveryN_)
    {
      count_ = 0;
      time_t now = ::time(NULL);
      time_t thisPeriod_ = now / kRollPerSeconds_ * kRollPerSeconds_;
      if (thisPeriod_ != startOfPeriod_)
      {
        rollFile();
      }
      else if (now - lastFlush_ > flushInterval_)
      {
        lastFlush_ = now;
        file_->flush();
      }
    }
  }
}

bool LogFile::rollFile()
{
  time_t now = 0;
  string filename = getLogFileName(basename_, &now);
  time_t start = now / kRollPerSeconds_ * kRollPerSeconds_;

  if (now > lastRoll_)
  {
    lastRoll_ = now;
    lastFlush_ = now;
    startOfPeriod_ = start;
    file_.reset(new FileUtil::AppendFile(filename));
    return true;
  }
  return false;
}

string LogFile::getLogFileName(const string& basename, time_t* now)
{
  string filename;
  filename.reserve(basename.size() + 64);
  filename = basename;

  char timebuf[32];
  struct tm tm;
  *now = time(NULL);
  gmtime_r(now, &tm); // FIXME: localtime_r ?
  strftime(timebuf, sizeof timebuf, ".%Y%m%d-%H%M%S.", &tm);
  filename += timebuf;

  filename += ProcessInfo::hostname();

  char pidbuf[32];
  snprintf(pidbuf, sizeof pidbuf, ".%d", ProcessInfo::pid());
  filename += pidbuf;

  filename += ".log";

  return filename;
}

在LogFile的建構函式中,會呼叫一次rollFile,開啟檔案,並且將startOfPeriod_、lastRoll_、lastFlush修改為當前的時間。該類最主要的介面是append_unlocked,在該介面中,會進行日誌滾動和重新整理緩衝。其他的功能主要是間接通過AppendFile這個類實現的。之後專門說一下該類。

LogFile使用方法很簡單,在LogFile_test.cc檔案中有,主要是三步:

  g_logFile.reset(new muduo::LogFile(::basename(name), 200*1000));

  muduo::Logger::setOutput(outputFunc); ---->g_logFile->append(msg, len);

  muduo::Logger::setFlush(flushFunc); ----> g_logFile->flush();