CompressingLogFileManager.m 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. //
  2. // CompressingLogFileManager.m
  3. // LogFileCompressor
  4. //
  5. // CocoaLumberjack Demos
  6. //
  7. #import "CompressingLogFileManager.h"
  8. #import <zlib.h>
  9. // We probably shouldn't be using DDLog() statements within the DDLog implementation.
  10. // But we still want to leave our log statements for any future debugging,
  11. // and to allow other developers to trace the implementation (which is a great learning tool).
  12. //
  13. // So we use primitive logging macros around NSLog.
  14. // We maintain the NS prefix on the macros to be explicit about the fact that we're using NSLog.
  15. #define LOG_LEVEL 4
  16. #define NSLogError(frmt, ...) do{ if(LOG_LEVEL >= 1) NSLog(frmt, ##__VA_ARGS__); } while(0)
  17. #define NSLogWarn(frmt, ...) do{ if(LOG_LEVEL >= 2) NSLog(frmt, ##__VA_ARGS__); } while(0)
  18. #define NSLogInfo(frmt, ...) do{ if(LOG_LEVEL >= 3) NSLog(frmt, ##__VA_ARGS__); } while(0)
  19. #define NSLogVerbose(frmt, ...) do{ if(LOG_LEVEL >= 4) NSLog(frmt, ##__VA_ARGS__); } while(0)
  20. @interface CompressingLogFileManager (/* Must be nameless for properties */)
  21. @property (readwrite) BOOL isCompressing;
  22. @end
  23. @interface DDLogFileInfo (Compressor)
  24. @property (nonatomic, readonly) BOOL isCompressed;
  25. - (NSString *)tempFilePathByAppendingPathExtension:(NSString *)newExt;
  26. - (NSString *)fileNameByAppendingPathExtension:(NSString *)newExt;
  27. @end
  28. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  29. #pragma mark -
  30. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  31. @implementation CompressingLogFileManager
  32. @synthesize isCompressing;
  33. - (id)init
  34. {
  35. return [self initWithLogsDirectory:nil];
  36. }
  37. - (id)initWithLogsDirectory:(NSString *)aLogsDirectory
  38. {
  39. if ((self = [super initWithLogsDirectory:aLogsDirectory]))
  40. {
  41. upToDate = NO;
  42. // Check for any files that need to be compressed.
  43. // But don't start right away.
  44. // Wait for the app startup process to finish.
  45. [self performSelector:@selector(compressNextLogFile) withObject:nil afterDelay:5.0];
  46. }
  47. return self;
  48. }
  49. - (void)dealloc
  50. {
  51. [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(compressNextLogFile) object:nil];
  52. }
  53. - (void)compressLogFile:(DDLogFileInfo *)logFile
  54. {
  55. self.isCompressing = YES;
  56. CompressingLogFileManager* __weak weakSelf = self;
  57. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
  58. [weakSelf backgroundThread_CompressLogFile:logFile];
  59. });
  60. }
  61. - (void)compressNextLogFile
  62. {
  63. if (self.isCompressing)
  64. {
  65. // We're already compressing a file.
  66. // Wait until it's done to move onto the next file.
  67. return;
  68. }
  69. NSLogVerbose(@"CompressingLogFileManager: compressNextLogFile");
  70. upToDate = NO;
  71. NSArray *sortedLogFileInfos = [self sortedLogFileInfos];
  72. NSUInteger count = [sortedLogFileInfos count];
  73. if (count == 0)
  74. {
  75. // Nothing to compress
  76. upToDate = YES;
  77. return;
  78. }
  79. NSUInteger i = count;
  80. while (i > 0)
  81. {
  82. DDLogFileInfo *logFileInfo = [sortedLogFileInfos objectAtIndex:(i - 1)];
  83. if (logFileInfo.isArchived && !logFileInfo.isCompressed)
  84. {
  85. [self compressLogFile:logFileInfo];
  86. break;
  87. }
  88. i--;
  89. }
  90. upToDate = YES;
  91. }
  92. - (void)compressionDidSucceed:(DDLogFileInfo *)logFile
  93. {
  94. NSLogVerbose(@"CompressingLogFileManager: compressionDidSucceed: %@", logFile.fileName);
  95. self.isCompressing = NO;
  96. [self compressNextLogFile];
  97. }
  98. - (void)compressionDidFail:(DDLogFileInfo *)logFile
  99. {
  100. NSLogWarn(@"CompressingLogFileManager: compressionDidFail: %@", logFile.fileName);
  101. self.isCompressing = NO;
  102. // We should try the compression again, but after a short delay.
  103. //
  104. // If the compression failed there is probably some filesystem issue,
  105. // so flooding it with compression attempts is only going to make things worse.
  106. NSTimeInterval delay = (60 * 15); // 15 minutes
  107. [self performSelector:@selector(compressNextLogFile) withObject:nil afterDelay:delay];
  108. }
  109. - (void)didArchiveLogFile:(NSString *)logFilePath wasRolled:(BOOL)wasRolled {
  110. NSLogVerbose(@"CompressingLogFileManager: didArchiveLogFile: %@ wasRolled: %@",
  111. [logFilePath lastPathComponent], (wasRolled ? @"YES" : @"NO"));
  112. // If all other log files have been compressed, then we can get started right away.
  113. // Otherwise we should just wait for the current compression process to finish.
  114. if (upToDate)
  115. {
  116. [self compressLogFile:[DDLogFileInfo logFileWithPath:logFilePath]];
  117. }
  118. }
  119. - (void)backgroundThread_CompressLogFile:(DDLogFileInfo *)logFile
  120. {
  121. @autoreleasepool {
  122. NSLogInfo(@"CompressingLogFileManager: Compressing log file: %@", logFile.fileName);
  123. // Steps:
  124. // 1. Create a new file with the same fileName, but added "gzip" extension
  125. // 2. Open the new file for writing (output file)
  126. // 3. Open the given file for reading (input file)
  127. // 4. Setup zlib for gzip compression
  128. // 5. Read a chunk of the given file
  129. // 6. Compress the chunk
  130. // 7. Write the compressed chunk to the output file
  131. // 8. Repeat steps 5 - 7 until the input file is exhausted
  132. // 9. Close input and output file
  133. // 10. Teardown zlib
  134. // STEP 1
  135. NSString *inputFilePath = logFile.filePath;
  136. NSString *tempOutputFilePath = [logFile tempFilePathByAppendingPathExtension:@"gz"];
  137. #if TARGET_OS_IPHONE
  138. // We use the same protection as the original file. This means that it has the same security characteristics.
  139. // Also, if the app can run in the background, this means that it gets
  140. // NSFileProtectionCompleteUntilFirstUserAuthentication so that we can do this compression even with the
  141. // device locked. c.f. DDFileLogger.doesAppRunInBackground.
  142. NSString* protection = logFile.fileAttributes[NSFileProtectionKey];
  143. NSDictionary* attributes = protection == nil ? nil : @{NSFileProtectionKey: protection};
  144. [[NSFileManager defaultManager] createFileAtPath:tempOutputFilePath contents:nil attributes:attributes];
  145. #endif
  146. // STEP 2 & 3
  147. NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:inputFilePath];
  148. NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:tempOutputFilePath append:NO];
  149. [inputStream open];
  150. [outputStream open];
  151. // STEP 4
  152. z_stream strm;
  153. // Zero out the structure before (to be safe) before we start using it
  154. bzero(&strm, sizeof(strm));
  155. strm.zalloc = Z_NULL;
  156. strm.zfree = Z_NULL;
  157. strm.opaque = Z_NULL;
  158. strm.total_out = 0;
  159. // Compresssion Levels:
  160. // Z_NO_COMPRESSION
  161. // Z_BEST_SPEED
  162. // Z_BEST_COMPRESSION
  163. // Z_DEFAULT_COMPRESSION
  164. deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (15+16), 8, Z_DEFAULT_STRATEGY);
  165. // Prepare our variables for steps 5-7
  166. //
  167. // inputDataLength : Total length of buffer that we will read file data into
  168. // outputDataLength : Total length of buffer that zlib will output compressed bytes into
  169. //
  170. // Note: The output buffer can be smaller than the input buffer because the
  171. // compressed/output data is smaller than the file/input data (obviously).
  172. //
  173. // inputDataSize : The number of bytes in the input buffer that have valid data to be compressed.
  174. //
  175. // Imagine compressing a tiny file that is actually smaller than our inputDataLength.
  176. // In this case only a portion of the input buffer would have valid file data.
  177. // The inputDataSize helps represent the portion of the buffer that is valid.
  178. //
  179. // Imagine compressing a huge file, but consider what happens when we get to the very end of the file.
  180. // The last read will likely only fill a portion of the input buffer.
  181. // The inputDataSize helps represent the portion of the buffer that is valid.
  182. NSUInteger inputDataLength = (1024 * 2); // 2 KB
  183. NSUInteger outputDataLength = (1024 * 1); // 1 KB
  184. NSMutableData *inputData = [NSMutableData dataWithLength:inputDataLength];
  185. NSMutableData *outputData = [NSMutableData dataWithLength:outputDataLength];
  186. NSUInteger inputDataSize = 0;
  187. BOOL done = YES;
  188. NSError* error = nil;
  189. do
  190. {
  191. @autoreleasepool {
  192. // STEP 5
  193. // Read data from the input stream into our input buffer.
  194. //
  195. // inputBuffer : pointer to where we want the input stream to copy bytes into
  196. // inputBufferLength : max number of bytes the input stream should read
  197. //
  198. // Recall that inputDataSize is the number of valid bytes that already exist in the
  199. // input buffer that still need to be compressed.
  200. // This value is usually zero, but may be larger if a previous iteration of the loop
  201. // was unable to compress all the bytes in the input buffer.
  202. //
  203. // For example, imagine that we ready 2K worth of data from the file in the last loop iteration,
  204. // but when we asked zlib to compress it all, zlib was only able to compress 1.5K of it.
  205. // We would still have 0.5K leftover that still needs to be compressed.
  206. // We want to make sure not to skip this important data.
  207. //
  208. // The [inputData mutableBytes] gives us a pointer to the beginning of the underlying buffer.
  209. // When we add inputDataSize we get to the proper offset within the buffer
  210. // at which our input stream can start copying bytes into without overwriting anything it shouldn't.
  211. const void *inputBuffer = [inputData mutableBytes] + inputDataSize;
  212. NSUInteger inputBufferLength = inputDataLength - inputDataSize;
  213. NSInteger readLength = [inputStream read:(uint8_t *)inputBuffer maxLength:inputBufferLength];
  214. if (readLength < 0) {
  215. error = [inputStream streamError];
  216. break;
  217. }
  218. NSLogVerbose(@"CompressingLogFileManager: Read %li bytes from file", (long)readLength);
  219. inputDataSize += readLength;
  220. // STEP 6
  221. // Ask zlib to compress our input buffer.
  222. // Tell it to put the compressed bytes into our output buffer.
  223. strm.next_in = (Bytef *)[inputData mutableBytes]; // Read from input buffer
  224. strm.avail_in = (uInt)inputDataSize; // as much as was read from file (plus leftovers).
  225. strm.next_out = (Bytef *)[outputData mutableBytes]; // Write data to output buffer
  226. strm.avail_out = (uInt)outputDataLength; // as much space as is available in the buffer.
  227. // When we tell zlib to compress our data,
  228. // it won't directly tell us how much data was processed.
  229. // Instead it keeps a running total of the number of bytes it has processed.
  230. // In other words, every iteration from the loop it increments its total values.
  231. // So to figure out how much data was processed in this iteration,
  232. // we fetch the totals before we ask it to compress data,
  233. // and then afterwards we subtract from the new totals.
  234. NSInteger prevTotalIn = strm.total_in;
  235. NSInteger prevTotalOut = strm.total_out;
  236. int flush = [inputStream hasBytesAvailable] ? Z_SYNC_FLUSH : Z_FINISH;
  237. deflate(&strm, flush);
  238. NSInteger inputProcessed = strm.total_in - prevTotalIn;
  239. NSInteger outputProcessed = strm.total_out - prevTotalOut;
  240. NSLogVerbose(@"CompressingLogFileManager: Total bytes uncompressed: %lu", (unsigned long)strm.total_in);
  241. NSLogVerbose(@"CompressingLogFileManager: Total bytes compressed: %lu", (unsigned long)strm.total_out);
  242. NSLogVerbose(@"CompressingLogFileManager: Compression ratio: %.1f%%",
  243. (1.0F - (float)(strm.total_out) / (float)(strm.total_in)) * 100);
  244. // STEP 7
  245. // Now write all compressed bytes to our output stream.
  246. //
  247. // It is theoretically possible that the write operation doesn't write everything we ask it to.
  248. // Although this is highly unlikely, we take precautions.
  249. // Also, we watch out for any errors (maybe the disk is full).
  250. NSUInteger totalWriteLength = 0;
  251. NSInteger writeLength = 0;
  252. do
  253. {
  254. const void *outputBuffer = [outputData mutableBytes] + totalWriteLength;
  255. NSUInteger outputBufferLength = outputProcessed - totalWriteLength;
  256. writeLength = [outputStream write:(const uint8_t *)outputBuffer maxLength:outputBufferLength];
  257. if (writeLength < 0)
  258. {
  259. error = [outputStream streamError];
  260. }
  261. else
  262. {
  263. totalWriteLength += writeLength;
  264. }
  265. } while((totalWriteLength < outputProcessed) && !error);
  266. // STEP 7.5
  267. //
  268. // We now have data in our input buffer that has already been compressed.
  269. // We want to remove all the processed data from the input buffer,
  270. // and we want to move any unprocessed data to the beginning of the buffer.
  271. //
  272. // If the amount processed is less than the valid buffer size, we have leftovers.
  273. NSUInteger inputRemaining = inputDataSize - inputProcessed;
  274. if (inputRemaining > 0)
  275. {
  276. void *inputDst = [inputData mutableBytes];
  277. void *inputSrc = [inputData mutableBytes] + inputProcessed;
  278. memmove(inputDst, inputSrc, inputRemaining);
  279. }
  280. inputDataSize = inputRemaining;
  281. // Are we done yet?
  282. done = ((flush == Z_FINISH) && (inputDataSize == 0));
  283. // STEP 8
  284. // Loop repeats until end of data (or unlikely error)
  285. } // end @autoreleasepool
  286. } while (!done && error == nil);
  287. // STEP 9
  288. [inputStream close];
  289. [outputStream close];
  290. // STEP 10
  291. deflateEnd(&strm);
  292. // We're done!
  293. // Report success or failure back to the logging thread/queue.
  294. if (error)
  295. {
  296. // Remove output file.
  297. // Our compression attempt failed.
  298. NSLogError(@"Compression of %@ failed: %@", inputFilePath, error);
  299. error = nil;
  300. BOOL ok = [[NSFileManager defaultManager] removeItemAtPath:tempOutputFilePath error:&error];
  301. if (!ok)
  302. NSLogError(@"Failed to clean up %@ after failed compression: %@", tempOutputFilePath, error);
  303. // Report failure to class via logging thread/queue
  304. dispatch_async([DDLog loggingQueue], ^{ @autoreleasepool {
  305. [self compressionDidFail:logFile];
  306. }});
  307. }
  308. else
  309. {
  310. // Remove original input file.
  311. // It will be replaced with the new compressed version.
  312. error = nil;
  313. BOOL ok = [[NSFileManager defaultManager] removeItemAtPath:inputFilePath error:&error];
  314. if (!ok)
  315. NSLogWarn(@"Warning: failed to remove original file %@ after compression: %@", inputFilePath, error);
  316. // Mark the compressed file as archived,
  317. // and then move it into its final destination.
  318. //
  319. // temp-log-ABC123.txt.gz -> log-ABC123.txt.gz
  320. //
  321. // The reason we were using the "temp-" prefix was so the file would not be
  322. // considered a log file while it was only partially complete.
  323. // Only files that begin with "log-" are considered log files.
  324. DDLogFileInfo *compressedLogFile = [DDLogFileInfo logFileWithPath:tempOutputFilePath];
  325. compressedLogFile.isArchived = YES;
  326. NSString *outputFileName = [logFile fileNameByAppendingPathExtension:@"gz"];
  327. [compressedLogFile renameFile:outputFileName];
  328. // Report success to class via logging thread/queue
  329. dispatch_async([DDLog loggingQueue], ^{ @autoreleasepool {
  330. [self compressionDidSucceed:compressedLogFile];
  331. }});
  332. }
  333. } // end @autoreleasepool
  334. }
  335. @end
  336. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  337. #pragma mark -
  338. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  339. @implementation DDLogFileInfo (Compressor)
  340. @dynamic isCompressed;
  341. - (BOOL)isCompressed
  342. {
  343. return [[[self fileName] pathExtension] isEqualToString:@"gz"];
  344. }
  345. - (NSString *)tempFilePathByAppendingPathExtension:(NSString *)newExt
  346. {
  347. // Example:
  348. //
  349. // Current File Name: "/full/path/to/log-ABC123.txt"
  350. //
  351. // newExt: "gzip"
  352. // result: "/full/path/to/temp-log-ABC123.txt.gzip"
  353. NSString *tempFileName = [NSString stringWithFormat:@"temp-%@", [self fileName]];
  354. NSString *newFileName = [tempFileName stringByAppendingPathExtension:newExt];
  355. NSString *fileDir = [[self filePath] stringByDeletingLastPathComponent];
  356. NSString *newFilePath = [fileDir stringByAppendingPathComponent:newFileName];
  357. return newFilePath;
  358. }
  359. - (NSString *)fileNameByAppendingPathExtension:(NSString *)newExt
  360. {
  361. // Example:
  362. //
  363. // Current File Name: "log-ABC123.txt"
  364. //
  365. // newExt: "gzip"
  366. // result: "log-ABC123.txt.gzip"
  367. NSString *fileNameExtension = [[self fileName] pathExtension];
  368. if ([fileNameExtension isEqualToString:newExt])
  369. {
  370. return [self fileName];
  371. }
  372. return [[self fileName] stringByAppendingPathExtension:newExt];
  373. }
  374. @end