DDFileLoggerTests.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. // Software License Agreement (BSD License)
  2. //
  3. // Copyright (c) 2010-2025, Deusty, LLC
  4. // All rights reserved.
  5. //
  6. // Redistribution and use of this software in source and binary forms,
  7. // with or without modification, are permitted provided that the following conditions are met:
  8. //
  9. // * Redistributions of source code must retain the above copyright notice,
  10. // this list of conditions and the following disclaimer.
  11. //
  12. // * Neither the name of Deusty nor the names of its contributors may be used
  13. // to endorse or promote products derived from this software without specific
  14. // prior written permission of Deusty, LLC.
  15. @import XCTest;
  16. #import <CocoaLumberjack/DDFileLogger.h>
  17. #import <CocoaLumberjack/DDFileLogger+Buffering.h>
  18. #import <CocoaLumberjack/DDLogMacros.h>
  19. #import <sys/xattr.h>
  20. #import "DDSampleFileManager.h"
  21. static const DDLogLevel ddLogLevel = DDLogLevelAll;
  22. @interface DDFileLogger (Testing)
  23. - (nullable NSData *)lt_dataForMessage:(nonnull DDLogMessage *)logMessage;
  24. @end
  25. @interface DDMockedSerializer: NSObject <DDFileLogMessageSerializer>
  26. @property (nonatomic, nonnull, readonly) NSData * _Nonnull(^serializerBlock)(NSString * _Nonnull, DDLogMessage * _Nullable);
  27. - (instancetype)initWithSerializerBlock:(NSData * _Nonnull(^_Nonnull)(NSString * _Nonnull, DDLogMessage * _Nullable))serializerBlock;
  28. @end
  29. @implementation DDMockedSerializer
  30. @synthesize serializerBlock = _serializerBlock;
  31. - (instancetype)initWithSerializerBlock:(NSData * _Nonnull(^)(NSString * _Nonnull, DDLogMessage * _Nullable))serializerBlock {
  32. if (self = [super init]) {
  33. self->_serializerBlock = serializerBlock;
  34. }
  35. return self;
  36. }
  37. - (NSData *)dataForString:(NSString *)string originatingFromMessage:(DDLogMessage *)message {
  38. return self.serializerBlock(string, message);
  39. }
  40. @end
  41. @interface DDFileLoggerTests : XCTestCase {
  42. DDSampleFileManager *logFileManager;
  43. DDFileLogger *logger;
  44. NSString *logsDirectory;
  45. }
  46. @end
  47. @implementation DDFileLoggerTests
  48. - (void)setUp {
  49. [super setUp];
  50. logFileManager = [[DDSampleFileManager alloc] initWithLogFileHeader:@"header"];
  51. logger = [[DDFileLogger alloc] initWithLogFileManager:logFileManager];
  52. logsDirectory = logger.logFileManager.logsDirectory;
  53. }
  54. - (void)tearDown {
  55. [super tearDown];
  56. [DDLog removeAllLoggers];
  57. // We need to sync all involved queues to wait for the post-removal processing of the logger to finish before deleting the files.
  58. NSAssert(![self->logger isOnGlobalLoggingQueue], @"Trouble ahead!");
  59. dispatch_sync(DDLog.loggingQueue, ^{
  60. NSAssert(![self->logger isOnInternalLoggerQueue], @"Trouble ahead!");
  61. dispatch_sync(self->logger.loggerQueue, ^{
  62. /* noop */
  63. });
  64. });
  65. NSError *error = nil;
  66. __auto_type contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:logsDirectory error:&error];
  67. XCTAssertNil(error);
  68. for (NSString *path in contents) {
  69. error = nil;
  70. XCTAssertTrue([[NSFileManager defaultManager] removeItemAtPath:[logsDirectory stringByAppendingPathComponent:path] error:&error]);
  71. XCTAssertNil(error);
  72. }
  73. error = nil;
  74. XCTAssertTrue([[NSFileManager defaultManager] removeItemAtPath:logsDirectory error:&error]);
  75. XCTAssertNil(error);
  76. logFileManager = nil;
  77. logger = nil;
  78. logsDirectory = nil;
  79. }
  80. - (void)testExplicitLogFileRolling {
  81. [DDLog addLogger:logger];
  82. DDLogError(@"Some log in the old file");
  83. __auto_type oldLogFileInfo = [logger currentLogFileInfo];
  84. __auto_type expectation = [self expectationWithDescription:@"Waiting for the log file to be rolled"];
  85. [logger rollLogFileWithCompletionBlock:^{
  86. [expectation fulfill];
  87. }];
  88. [self waitForExpectationsWithTimeout:3 handler:^(NSError * _Nullable error) {
  89. XCTAssertNil(error);
  90. }];
  91. __auto_type newLogFileInfo = [logger currentLogFileInfo];
  92. XCTAssertNotNil(oldLogFileInfo);
  93. XCTAssertNotNil(newLogFileInfo);
  94. XCTAssertNotEqualObjects(oldLogFileInfo.filePath, newLogFileInfo.filePath);
  95. XCTAssertEqualObjects(oldLogFileInfo.filePath, logFileManager.archivedLogFilePath);
  96. XCTAssertTrue(oldLogFileInfo.isArchived);
  97. XCTAssertFalse(newLogFileInfo.isArchived);
  98. }
  99. - (void)testLoggingAfterLogFileRolling {
  100. [DDLog addLogger:logger];
  101. DDLogError(@"Some log in the old file");
  102. __auto_type oldLogFileInfo = [logger currentLogFileInfo];
  103. XCTAssertNotNil(oldLogFileInfo);
  104. __auto_type expectation = [self expectationWithDescription:@"Waiting for the log file to be rolled"];
  105. [logger rollLogFileWithCompletionBlock:^{
  106. [expectation fulfill];
  107. }];
  108. [self waitForExpectationsWithTimeout:3 handler:^(NSError * _Nullable error) {
  109. XCTAssertNil(error);
  110. }];
  111. DDLogError(@"Some log in the new file");
  112. __auto_type newLogFileInfo = [logger currentLogFileInfo];
  113. XCTAssertNotNil(newLogFileInfo);
  114. XCTAssertTrue([[NSFileManager defaultManager] fileExistsAtPath:oldLogFileInfo.filePath]);
  115. XCTAssertTrue([[NSFileManager defaultManager] fileExistsAtPath:newLogFileInfo.filePath]);
  116. __auto_type oldString = [NSString stringWithContentsOfFile:oldLogFileInfo.filePath
  117. encoding:NSUTF8StringEncoding
  118. error:nil];
  119. __auto_type newString = [NSString stringWithContentsOfFile:newLogFileInfo.filePath
  120. encoding:NSUTF8StringEncoding
  121. error:nil];
  122. XCTAssertFalse(oldString.length == 0);
  123. XCTAssertFalse(newString.length == 0);
  124. XCTAssertTrue([oldString containsString:@"Some log in the old file"]);
  125. XCTAssertTrue([newString containsString:@"Some log in the new file"]);
  126. }
  127. - (void)testExplicitLogFileRollingWhenNotReusingLogFiles {
  128. logger.doNotReuseLogFiles = YES;
  129. [DDLog addLogger:logger];
  130. DDLogError(@"Log 1 in the old file");
  131. DDLogError(@"Log 2 in the old file");
  132. __auto_type expectation = [self expectationWithDescription:@"Waiting for the log file to be rolled"];
  133. [logger rollLogFileWithCompletionBlock:^{
  134. [expectation fulfill];
  135. }];
  136. [self waitForExpectationsWithTimeout:3 handler:^(NSError * _Nullable error) {
  137. XCTAssertNil(error);
  138. }];
  139. DDLogError(@"Log 1 in the new file");
  140. DDLogError(@"Log 2 in the new file");
  141. XCTAssertEqual(logger.logFileManager.unsortedLogFileInfos.count, 2);
  142. }
  143. - (void)testAutomaticLogFileRollingWhenNotReusingLogFiles {
  144. // Use new logger so that it appears to be resuming.
  145. DDFileLogger *newLogger = [[DDFileLogger alloc] initWithLogFileManager:logFileManager];
  146. newLogger.doNotReuseLogFiles = YES;
  147. [DDLog addLogger:logger];
  148. DDLogError(@"Some log in the old file");
  149. __auto_type oldLogFileInfo = [logger currentLogFileInfo];
  150. usleep(1000); // prevent file name clash due to same time.
  151. __auto_type newLogFileInfo = [newLogger currentLogFileInfo];
  152. XCTAssertNotNil(oldLogFileInfo);
  153. XCTAssertNotNil(newLogFileInfo);
  154. XCTAssertNotEqualObjects(oldLogFileInfo.filePath, newLogFileInfo.filePath);
  155. XCTAssertEqualObjects(oldLogFileInfo.filePath, logFileManager.archivedLogFilePath);
  156. XCTAssertTrue(oldLogFileInfo.isArchived);
  157. XCTAssertFalse(newLogFileInfo.isArchived);
  158. }
  159. - (void)testCurrentLogFileInfoWhenNotReusingLogFilesOnlyCreatesNewLogFilesIfNecessary {
  160. logger.doNotReuseLogFiles = YES;
  161. __auto_type info1 = logger.currentLogFileInfo;
  162. __auto_type info2 = logger.currentLogFileInfo;
  163. XCTAssertEqualObjects(info1.filePath, info2.filePath);
  164. info2.isArchived = YES;
  165. usleep(1000); // make sure we have a different msec count. Otherwise the file names might be equal.
  166. __auto_type info3 = logger.currentLogFileInfo;
  167. __auto_type info4 = logger.currentLogFileInfo;
  168. XCTAssertEqualObjects(info3.filePath, info4.filePath);
  169. XCTAssertNotEqualObjects(info2.filePath, info3.filePath);
  170. XCTAssertEqual(logger.logFileManager.unsortedLogFileInfos.count, 2);
  171. }
  172. - (void)testExtendedAttributes {
  173. logger.doNotReuseLogFiles = YES;
  174. __auto_type info = logger.currentLogFileInfo;
  175. char buffer[1];
  176. ssize_t result = getxattr([info.filePath fileSystemRepresentation], "lumberjack.log.archived", buffer, 1, 0, 0);
  177. XCTAssertLessThan(result, 0);
  178. XCTAssertEqual(errno, ENOATTR);
  179. info.isArchived = YES;
  180. XCTAssertTrue(info.isArchived);
  181. result = getxattr([info.filePath fileSystemRepresentation], "lumberjack.log.archived", buffer, 1, 0, 0);
  182. XCTAssertEqual(result, 1);
  183. XCTAssertEqual(buffer[0], 0x01);
  184. info.isArchived = NO;
  185. XCTAssertFalse(info.isArchived);
  186. result = getxattr([info.filePath fileSystemRepresentation], "lumberjack.log.archived", buffer, 1, 0, 0);
  187. XCTAssertLessThan(result, 0);
  188. XCTAssertEqual(errno, ENOATTR);
  189. }
  190. - (void)testExtendedAttributesBackwardCompatibility {
  191. logger.doNotReuseLogFiles = YES;
  192. __auto_type info = logger.currentLogFileInfo;
  193. char buffer[1];
  194. #if TARGET_IPHONE_SIMULATOR
  195. [info renameFile:@"dummy.archived.log"];
  196. XCTAssertTrue(info.isArchived);
  197. ssize_t result = getxattr([info.filePath fileSystemRepresentation], "lumberjack.log.archived", buffer, 1, 0, 0);
  198. XCTAssertEqual(result, 1);
  199. XCTAssertEqual(buffer[0], 0x01);
  200. XCTAssertEqualObjects(info.fileName, @"dummy.log");
  201. [info renameFile:@"dummy.archived.log"];
  202. info.isArchived = YES;
  203. XCTAssertTrue(info.isArchived);
  204. XCTAssertEqualObjects(info.fileName, @"dummy.log");
  205. [info renameFile:@"dummy.archived.log"];
  206. info.isArchived = NO;
  207. XCTAssertFalse(info.isArchived);
  208. XCTAssertEqualObjects(info.fileName, @"dummy.log");
  209. #else
  210. int err = setxattr([info.filePath fileSystemRepresentation], "lumberjack.log.archived", "", 0, 0, 0);
  211. XCTAssertEqual(err, 0);
  212. XCTAssertTrue(info.isArchived);
  213. ssize_t result = getxattr([info.filePath fileSystemRepresentation], "lumberjack.log.archived", buffer, 1, 0, 0);
  214. XCTAssertEqual(result, 1);
  215. XCTAssertEqual(buffer[0], 0x01);
  216. #endif
  217. }
  218. - (void)testMaximumNumberOfLogFiles {
  219. logger.doNotReuseLogFiles = YES;
  220. logger.logFileManager.maximumNumberOfLogFiles = 4;
  221. logger.maximumFileSize = 10;
  222. [DDLog addLogger:logger];
  223. DDLogError(@"Log 1 in the file");
  224. DDLogError(@"Log 2 in the file");
  225. DDLogError(@"Log 3 in the file");
  226. DDLogError(@"Log 4 in the file");
  227. /// wait log queue finish.
  228. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  229. NSArray *oldFileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self->logger.logFileManager.logsDirectory error:nil];
  230. XCTAssertEqual(oldFileNames.count, 4);
  231. self->logger.logFileManager.maximumNumberOfLogFiles = 2;
  232. /// wait delete old files finish.
  233. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  234. NSArray *newFileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self->logger.logFileManager.logsDirectory error:nil];
  235. XCTAssertEqual(newFileNames.count, 2);
  236. });
  237. });
  238. }
  239. - (void)testWrapping {
  240. __auto_type wrapped = [logger wrapWithBuffer];
  241. XCTAssert([wrapped.class isSubclassOfClass:NSProxy.class]);
  242. __auto_type wrapped2 = [wrapped wrapWithBuffer];
  243. XCTAssertEqual(wrapped2, wrapped);
  244. __auto_type unwrapped = [wrapped unwrapFromBuffer];
  245. XCTAssert([unwrapped.class isSubclassOfClass:DDFileLogger.class]);
  246. __auto_type unwrapped2 = [unwrapped unwrapFromBuffer];
  247. XCTAssertEqual(unwrapped2, unwrapped);
  248. }
  249. - (void)testWriteToFileUnbuffered {
  250. logger = [logger unwrapFromBuffer];
  251. [DDLog addLogger:logger];
  252. DDLogError(@"%@", @"error");
  253. DDLogWarn(@"%@", @"warn");
  254. DDLogInfo(@"%@", @"info");
  255. DDLogDebug(@"%@", @"debug");
  256. DDLogVerbose(@"%@", @"verbose");
  257. [DDLog flushLog];
  258. NSString* filePath = logger.currentLogFileInfo.filePath;
  259. XCTAssertNotNil(filePath);
  260. NSError *error = nil;
  261. NSData *data = [NSData dataWithContentsOfFile:filePath options:NSDataReadingUncached error:&error];
  262. XCTAssertNil(error);
  263. NSString *contents = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  264. XCTAssertEqual([contents componentsSeparatedByString:@"\n"].count, 5 + 2);
  265. }
  266. - (void)testWriteToFileBuffered {
  267. logger = [logger wrapWithBuffer];
  268. [DDLog addLogger:logger];
  269. DDLogError(@"%@", @"error");
  270. DDLogWarn(@"%@", @"warn");
  271. DDLogInfo(@"%@", @"info");
  272. DDLogDebug(@"%@", @"debug");
  273. DDLogVerbose(@"%@", @"verbose");
  274. [DDLog flushLog];
  275. NSString* filePath = logger.currentLogFileInfo.filePath;
  276. XCTAssertNotNil(filePath);
  277. NSError *error = nil;
  278. NSData *data = [NSData dataWithContentsOfFile:filePath options:NSDataReadingUncached error:&error];
  279. XCTAssertNil(error);
  280. NSString *contents = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  281. XCTAssertEqual([contents componentsSeparatedByString:@"\n"].count, 5 + 2);
  282. }
  283. - (void)testOverwriteSymlink {
  284. NSString* customFileName = @"testIgnoreSymlink_file_name.log";
  285. logFileManager.customLogFileName = customFileName;
  286. NSString* logFileName = [logFileManager.logsDirectory stringByAppendingPathComponent:customFileName];
  287. NSString *tempFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSUUID UUID] UUIDString]];
  288. [NSFileManager.defaultManager createFileAtPath:tempFilePath contents:nil attributes:nil];
  289. [NSFileManager.defaultManager createDirectoryAtPath:logFileManager.logsDirectory
  290. withIntermediateDirectories:YES
  291. attributes:nil
  292. error:nil];
  293. [NSFileManager.defaultManager createSymbolicLinkAtPath:logFileName withDestinationPath:tempFilePath error:nil];
  294. __auto_type info = logger.currentLogFileInfo;
  295. XCTAssertEqualObjects(info.fileName, customFileName);
  296. XCTAssertFalse(info.isSymlink);
  297. }
  298. - (void)testSerializer {
  299. logFileManager.logMessageSerializer = [[DDMockedSerializer alloc] initWithSerializerBlock:^NSData *(NSString * string, DDLogMessage * msg) {
  300. NSString *resultingString = [NSString stringWithFormat:@"MessageLength: %lu; Message: %@", string.length, string];
  301. if (msg) {
  302. resultingString = [resultingString stringByAppendingString:@"; Message was non-nil"];
  303. }
  304. return [resultingString dataUsingEncoding:NSUTF8StringEncoding];
  305. }];
  306. logger.logFormatter = nil;
  307. __auto_type msg = [[DDLogMessage alloc] initWithFormat:@"SOME FORMAT"
  308. formatted:@"FORMATTED"
  309. level:DDLogLevelInfo
  310. flag:DDLogFlagInfo
  311. context:0
  312. file:@"FILE"
  313. function:@"FUNCTION"
  314. line:1
  315. tag:nil
  316. options:0
  317. timestamp:[NSDate date]];
  318. __block NSData *data = nil;
  319. dispatch_sync(DDLog.loggingQueue, ^{
  320. dispatch_sync(logger->_loggerQueue, ^{
  321. data = [logger lt_dataForMessage:msg];
  322. });
  323. });
  324. XCTAssertNotNil(data);
  325. __auto_type string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  326. XCTAssertNotNil(string);
  327. __auto_type formattedMsg = [msg.message stringByAppendingString:@"\n"];
  328. __auto_type expectedString = [NSString stringWithFormat:@"MessageLength: %ld; Message: %@; Message was non-nil", formattedMsg.length, formattedMsg];
  329. XCTAssertEqualObjects(string, expectedString);
  330. }
  331. @end