19#include <trantor/exports.h>
23#include <condition_variable>
30using StringPtr = std::shared_ptr<std::string>;
31using StringPtrQueue = std::queue<StringPtr>;
38class TRANTOR_EXPORT AsyncFileLogger : NonCopyable
47 void output(
const char *msg,
const uint64_t len);
92 switchOnLimitOnly_ = flag;
103 const std::string &extName =
".log",
104 const std::string &path =
"./")
106 fileBaseName_ = baseName;
107 extName[0] ==
'.' ? fileExtName_ = extName
108 : fileExtName_ = std::string(
".") + extName;
110 if (filePath_.length() == 0)
112 if (filePath_[filePath_.length() - 1] !=
'/')
113 filePath_ = filePath_ +
"/";
120 std::condition_variable cond_;
121 StringPtr logBufferPtr_;
122 StringPtr nextBufferPtr_;
123 StringPtrQueue writeBuffers_;
124 StringPtrQueue tmpBuffers_;
125 void writeLogToFile(
const StringPtr buf);
126 std::unique_ptr<std::thread> threadPtr_;
127 bool stopFlag_{
false};
128 void logThreadFunc();
129 std::string filePath_{
"./"};
130 std::string fileBaseName_{
"trantor"};
131 std::string fileExtName_{
".log"};
132 uint64_t sizeLimit_{20 * 1024 * 1024};
133 bool switchOnLimitOnly_{
false};
137 class LoggerFile : NonCopyable
140 LoggerFile(
const std::string &filePath,
141 const std::string &fileBaseName,
142 const std::string &fileExtName,
143 bool switchOnLimitOnly =
false,
144 size_t maxFiles = 0);
146 void writeLog(
const StringPtr buf);
148 void switchLog(
bool openNewOne);
149 uint64_t getLength();
150 explicit operator bool()
const
152 return fp_ !=
nullptr;
157 void initFilenameQueue();
158 void deleteOldFiles();
162 std::string fileFullName_;
163 std::string filePath_;
164 std::string fileBaseName_;
165 std::string fileExtName_;
166 static uint64_t fileSeq_;
167 bool switchOnLimitOnly_{
false};
172 std::deque<std::string> filenameQueue_;
174 std::unique_ptr<LoggerFile> loggerFilePtr_;
176 uint64_t lostCounter_{0};
This class implements utility functions for writing logs to files asynchronously.
Definition AsyncFileLogger.h:39
void startLogging()
Start writing log files.
void setFileSizeLimit(uint64_t limit)
Set the size limit of log files. When the log file size reaches the limit, the log file is switched.
Definition AsyncFileLogger.h:67
void setFileName(const std::string &baseName, const std::string &extName=".log", const std::string &path="./")
Set the log file name.
Definition AsyncFileLogger.h:102
void flush()
Flush data from memory buffer to the log file.
void setMaxFiles(size_t maxFiles)
Set the max number of log files. When the number exceeds the limit, the oldest log file will be delet...
Definition AsyncFileLogger.h:78
void output(const char *msg, const uint64_t len)
Write the message to the log file.
void setSwitchOnLimitOnly(bool flag=true)
Set whether to switch the log file when the AsyncFileLogger object is destroyed. If this flag is set ...
Definition AsyncFileLogger.h:90
This class represents a time point.
Definition Date.h:28
Definition EventLoop.h:34