Skip to content

添加日志文件滚动功能 #42

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 44 additions & 4 deletions WebServer/base/LogFile.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,25 @@ LogFile::LogFile(const string& basename, int flushEveryN)
mutex_(new MutexLock)
{
//assert(basename.find('/') >= 0);
file_.reset(new AppendFile(basename));
rollFile();
}

LogFile::~LogFile()
{ }

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

curSize_ += len;
if(curSize_ >= KMaxFileSize)
{
file_->flush();
rollFile();
}
}

void LogFile::flush()
Expand All @@ -34,6 +43,14 @@ void LogFile::flush()
file_->flush();
}

void LogFile::rollFile()
{
string filename=getFilename();
file_.reset(new AppendFile(filename));
curSize_=0;
count_=0;
}

void LogFile::append_unlocked(const char* logline, int len)
{
file_->append(logline, len);
Expand All @@ -43,4 +60,27 @@ void LogFile::append_unlocked(const char* logline, int len)
count_ = 0;
file_->flush();
}
}
}

std::string LogFile::getFilename()
{
std::string filename;
filename.reserve(64);
filename = basename_;

char timebuf[16];
time_t now=time(NULL);
struct tm *tm=localtime(&now);
strftime(timebuf,sizeof timebuf,".%y%m%d_%H%M%S.",tm);

char hostbuf[64]; // getconf HOST_NAME_MAX
gethostname(hostbuf,sizeof hostbuf);

filename+=timebuf;
filename+=hostbuf;
filename+=".";
filename+=to_string(getpid());
filename+=".log";

return filename;
}
9 changes: 7 additions & 2 deletions WebServer/base/LogFile.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,20 @@ class LogFile : noncopyable

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

private:
void append_unlocked(const char* logline, int len);
// basename.年月日_时分秒.主机名.进程号.log
std::string getFilename();

static const int KMaxFileSize=1024*1024*1024; // 日志到达1G时切换

const std::string basename_;
const int flushEveryN_;

int count_;
int curSize_;
std::unique_ptr<MutexLock> mutex_;
std::unique_ptr<AppendFile> file_;
};
};