diff --git a/WebServer/base/LogFile.cpp b/WebServer/base/LogFile.cpp index 15e8027..ff32734 100755 --- a/WebServer/base/LogFile.cpp +++ b/WebServer/base/LogFile.cpp @@ -16,7 +16,7 @@ LogFile::LogFile(const string& basename, int flushEveryN) mutex_(new MutexLock) { //assert(basename.find('/') >= 0); - file_.reset(new AppendFile(basename)); + rollFile(); } LogFile::~LogFile() @@ -24,8 +24,17 @@ 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() @@ -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); @@ -43,4 +60,27 @@ void LogFile::append_unlocked(const char* logline, int len) count_ = 0; file_->flush(); } -} \ No newline at end of file +} + +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; +} diff --git a/WebServer/base/LogFile.h b/WebServer/base/LogFile.h index cfdd927..38fb7fc 100755 --- a/WebServer/base/LogFile.h +++ b/WebServer/base/LogFile.h @@ -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 mutex_; std::unique_ptr file_; -}; \ No newline at end of file +};