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();