muduo_base库源码分析(十二)

muduo库中的实现日志滚动有两种条件,一种是日志文件大小达到预设值,另一种是时间(每天零点新建一个日志文件,不论前一个文件是否写满)。滚动日志类的文件是LogFile.cc、LogFile.h
我觉得这一节中的智能指针的用法很漂亮。
在这里插入图片描述
LogFile类中的重要部分:

boost::scoped_ptr<MutexLock> mutex_;//智能指针对象mutex_,与动态分配的MutexLock类对象关联
class File;//LogFile类中嵌套的File类的声明
boost::scoped_ptr<File> file_;//智能指针对象file_,与动态分配的File类对象关联

LogFile类中的嵌套类File的重要部分:
在File类的构造函数的初始化列表中调用fopen函数完成日志文件的创建(即对fp_初始化)。

FILE* fp_;//文件指针

LogFile类对象调用LogFile类的append函数时,里面会调用LogFile类的append_unlock函数,而append_unlock函数中又会通过LogFile类中的智能指针对象file_去调用File类的append函数。

还有就是LogFile类中滚动日志函数rollFile的实现:
在这里插入图片描述

源码

LogFile.h

#ifndef MUDUO_BASE_LOGFILE_H
#define MUDUO_BASE_LOGFILE_H

#include <muduo/base/Mutex.h>
#include <muduo/base/Types.h>

#include <boost/noncopyable.hpp>
#include <boost/scoped_ptr.hpp>

namespace muduo
{

class LogFile : boost::noncopyable
{
 public:
  LogFile(const string& basename,
          size_t rollSize,
          bool threadSafe = true,
          int flushInterval = 3);
  ~LogFile();

  void append(const char* logline, int len);
  void flush();

 private:
  void append_unlocked(const char* logline, int len);

  static string getLogFileName(const string& basename, time_t* now);
  void rollFile();//滚动日志

  const string basename_;		//日志文件basename
  const size_t rollSize_;		//日志文件达到rolSize_换一个新文件
  const int flushInterval_;		//日志写入间隔时间

  int count_;

  boost::scoped_ptr<MutexLock> mutex_;//智能指针对象mutex_,与动态分配的MutexLock类对象关联
  time_t startOfPeriod_;	//开始记录日志时间(调整至零点的时间)
  time_t lastRoll_;	        //上一次滚动日志文件时间
  time_t lastFlush_;		//上一次日志写入文件时间
  class File;//LogFile类中嵌套的File类的声明
  boost::scoped_ptr<File> file_;//智能指针对象file_,与动态分配的File类对象关联

  const static int kCheckTimeRoll_ = 1024;
  const static int kRollPerSeconds_ = 60*60*24;
};

}
#endif  // MUDUO_BASE_LOGFILE_H

LogFile.cc

#include <muduo/base/LogFile.h>
#include <muduo/base/Logging.h> // strerror_tl
#include <muduo/base/ProcessInfo.h>

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

using namespace muduo;

// not thread safe
class LogFile::File : boost::noncopyable//LogFile类中的嵌套类File的实现
{
 public:
  explicit File(const string& filename)
    : fp_(::fopen(filename.data(), "ae")),//在当前目录下创建文件
      writtenBytes_(0)
  {
    assert(fp_);
    ::setbuffer(fp_, buffer_, sizeof buffer_);
    //void setbuffer(FILE * stream,char * buf,size_t size);参数stream为指定的文件流,参数buf指向自定的缓冲区起始地址,参数size为缓冲区大小。
    //在打开文件流后,读取内容之前,调用setbuffer()来设置文件流的缓冲区。

  }

  ~File()
  {
    ::fclose(fp_);
  }

//把logline这一行信息添加到文件当中
  void append(const char* logline, const size_t len)
  {
    size_t n = write(logline, len);
    size_t remain = len - n;
	// remain>0表示没写完,需要继续写直到写完
    while (remain > 0)
    {
      size_t x = write(logline + n, remain);
      if (x == 0)
      {
        int err = ferror(fp_);
        if (err)
        {
          fprintf(stderr, "LogFile::File::append() failed %s\n", strerror_tl(err));
        }
        break;
      }
      n += x;
      remain = len - n; // remain -= x
    }

    writtenBytes_ += len;
  }

  void flush()
  {
    ::fflush(fp_);
  }

  size_t writtenBytes() const { return writtenBytes_; }

 private:

  size_t write(const char* logline, size_t len)
  {
#undef fwrite_unlocked
//使用fwrite_unlocked方式写入效率会高一些
    return ::fwrite_unlocked(logline, 1, len, fp_);
  }

  FILE* fp_;//文件指针
  char buffer_[64*1024];//文件指针的缓冲区,如果超过64k,会自动调用fflush(fp_)
  size_t writtenBytes_;//已经写入文件的字节数
};//File类

LogFile::LogFile(const string& basename,
                 size_t rollSize,
                 bool threadSafe,
                 int flushInterval)
  : basename_(basename),//日志文件的basename
    rollSize_(rollSize),//日志文件写到rollSize_时就换一个新的文件
    flushInterval_(flushInterval),//日志fflush的间隔时间,默认是3秒钟
    count_(0),//计数器初始化为0
    mutex_(threadSafe ? new MutexLock : NULL),//如果是线程安全的则构造一个互斥锁
    startOfPeriod_(0),//开始记录日志的时间(将会调整至0点时间)
    lastRoll_(0),//上一次滚动日志的时间
    lastFlush_(0)//上一次日志fflush写入文件的时间
{
  assert(basename.find('/') == string::npos);//断言basename中肯定不存在'/'
  rollFile();//滚动日志产生一个文件(第一次)
}

LogFile::~LogFile()
{
}

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);//这里调用的是LogFile类的嵌套类File中的append函数

  if (file_->writtenBytes() > rollSize_)//如果已经写入的字节数大于rollSize_
  {
    rollFile();//滚动日志
  }
  else//字节数没超不代表不进行滚动,还要检查时间决定是否该进行滚动
  {
    if (count_ > kCheckTimeRoll_)//查看计数值count是否超过kCheckTimeRoll_
    {
      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();
      }
    }
    else
    {
      ++count_;
    }
  }
}


//滚动日志
void LogFile::rollFile()
{
  time_t now = 0;
  string filename = getLogFileName(basename_, &now);
  // 注意,这里先除kRollPerSeconds_ 后乘kRollPerSeconds_表示
  // 对齐至kRollPerSeconds_整数倍,也就是时间调整到当天零点。
  time_t start = now / kRollPerSeconds_ * kRollPerSeconds_;

  if (now > lastRoll_)
  {
    lastRoll_ = now;
    lastFlush_ = now;
    startOfPeriod_ = start;
    //重新new一个LogFile类中的嵌套类File的对象,此时会在File类的构造函数中对文件指针fp_初始化,即产生一个新的日志文件)
    file_.reset(new File(filename));//这里调用的是智能指针的reset函数,将智能指针对象file_与新动态分配的File类对象关联,相当漂亮的用法!
    //智能指针对象调用reset时,会自动delete旧的动态分配的File类对象
  }
}

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

  char timebuf[32];
  char pidbuf[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();
  snprintf(pidbuf, sizeof pidbuf, ".%d", ProcessInfo::pid());
  filename += pidbuf;
  filename += ".log";

  return filename;
}


测试

1.输出一系列的日志并进行日志滚动
LogFile_test.cc

#include <muduo/base/LogFile.h>
#include <muduo/base/Logging.h>
//滚动日志测试
boost::scoped_ptr<muduo::LogFile> g_logFile;

void outputFunc(const char* msg, int len)
{
  g_logFile->append(msg, len);
}

void flushFunc()
{
  g_logFile->flush();
}

int main(int argc, char* argv[])
{
  char name[256];
  strncpy(name, argv[0], 256);
  g_logFile.reset(new muduo::LogFile(::basename(name), 200*1000));//每200000个字节进行日志滚动
  muduo::Logger::setOutput(outputFunc);
  muduo::Logger::setFlush(flushFunc);

  muduo::string line = "1234567890 abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ ";

  for (int i = 0; i < 10000; ++i)
  {
    LOG_INFO << line << i;
    usleep(1000);
  }
  return 0;
}

在这里插入图片描述

2.测试日志的性能
Logging_test.cc

#include <muduo/base/Logging.h>
#include <muduo/base/LogFile.h>
#include <muduo/base/ThreadPool.h>

#include <stdio.h>

int g_total;
FILE* g_file;
boost::scoped_ptr<muduo::LogFile> g_logFile;//智能指针对象,与动态内存分配的LogFile类对象关联

void myOutput(const char* msg, int len)
{
  g_total += len;
  if (g_file)
  {
    fwrite(msg, 1, len, g_file);
  }
  else if (g_logFile)
  {
    g_logFile->append(msg, len);
  }
}

void bench(const char* type)
{
  muduo::Logger::setOutput(myOutput);
  muduo::Timestamp start(muduo::Timestamp::now());
  g_total = 0;

  int n = 1000*1000;
  for (int i = 0; i < n; ++i)
  {
    LOG_INFO <<"abc "<< i;
  }
  muduo::Timestamp end(muduo::Timestamp::now());
  double seconds = timeDifference(end, start);
  printf("%12s: %f seconds, %d bytes, %10.2f msg/s, %.2f MiB/s\n",
         type, seconds, g_total, n / seconds, g_total / seconds / (1024 * 1024));
}

void logInThread()
{
  LOG_INFO << "logInThread";
  usleep(1000);//否则一秒内就能全部运行完,由于文件命名时只精确到秒,所以会导致日志滚动前后fopen函数操作的都是同一个文件,并没有创建新的日志
}

int main()
{
  getppid(); // for ltrace and strace

  muduo::ThreadPool pool("pool");
  pool.start(5);
  pool.run(logInThread);
  pool.run(logInThread);
  pool.run(logInThread);
  pool.run(logInThread);
  pool.run(logInThread);

  LOG_TRACE << "trace";
  LOG_DEBUG << "debug";
  LOG_INFO << "Hello";
  LOG_WARN << "World";
  LOG_ERROR << "Error";
  LOG_INFO << sizeof(muduo::Logger);
  LOG_INFO << sizeof(muduo::LogStream);
  LOG_INFO << sizeof(muduo::Fmt);
  LOG_INFO << sizeof(muduo::LogStream::Buffer);
//以上均输出到stdout
  sleep(1);
 

 
//普通日志测试
 char buffer[64*1024];
  g_file = fopen("/dev/null", "w");
  setbuffer(g_file, buffer, sizeof buffer);
  bench("/dev/null");
  fclose(g_file);

//滚动日志测试
  g_file = NULL;
  g_logFile.reset(new muduo::LogFile("test_log_threadSafe", 500*1000*1000, true));
  bench("线程安全的测试");

  g_logFile.reset(new muduo::LogFile("test_log_threadUnsafe", 500*1000*1000, false));
  bench("线程不安全的测试");
  g_logFile.reset();
  return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值