Chapter 14: Files and Asynchronous Logging
This chapter describes path helpers, thread-safe file objects, bounded asynchronous logging, and their lifetime relationships.
1. Three layers
| Class | Responsibility | Key contract |
|---|---|---|
FileTool | Create paths/files, binary copy, file size | copy() does not create parent directories and returns false on open/write failure |
File | Thread-safe text/binary operations and memory transactions | File operations begin with openFile(); the locking thread also unlocks a memory transaction |
LogFile | Bounded queue and dedicated consumer thread | Drops and counts records on overload rather than blocking producers |
2. Binary-safe copy
if(!stt::file::FileTool::copy(
"runtime/source.bin",
"runtime/backup/source.bin"))
{
// Missing parent directory, open failure, or write failure.
}copy() preserves NUL bytes, newlines, and arbitrary binary data. The destination parent directory is expected to exist before the call.
3. File and memory transactions
stt::file::File config;
if(!config.openFile("runtime/app.conf"))
return 1;
config.deleteAll();
config.appendLine("port=8080");
config.appendLine("workers=4");
config.closeFile();Ordinary methods combine locking, modification, and persistence in one operation. lockMemory() and the C-suffixed methods represent an explicit multi-step transaction, with one matching unlockMemory() on every exit path.
4. Asynchronous log lifetime
{
// Capacity follows MPSCQueue's power-of-two requirement.
stt::file::LogFile log(16384);
if(!log.openFile("logs/server.log", ISO8086B, " "))
return 1;
log.writeLog("server started");
std::cout << log.getDroppedLogCount() << '
';
// Stop all producers before leaving this scope. The destructor stops
// the consumer and drains records that already entered the queue.
}- An arbitrary sleep is not a reliable log-flush protocol.
- The
LogFilelifetime covers every thread that callswriteLog(). - Observe overload with
getDroppedLogCount(). deleteLogByTime(start,end)uses a[start,end)interval.- Log content excludes passwords, private keys, complete tokens/cookies, and sensitive bodies.