DDFileLoggerTests.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. __auto_type expectation = [self expectationWithDescription:@"Waiting for the log file to be rolled"];
  104. [logger rollLogFileWithCompletionBlock:^{
  105. [expectation fulfill];
  106. }];
  107. [self waitForExpectationsWithTimeout:3 handler:^(NSError * _Nullable error) {
  108. XCTAssertNil(error);
  109. }];
  110. DDLogError(@"Some log in the new file");
  111. __auto_type newLogFileInfo = [logger currentLogFileInfo];
  112. XCTAssertTrue([[NSFileManager defaultManager] fileExistsAtPath:oldLogFileInfo.filePath]);
  113. XCTAssertTrue([[NSFileManager defaultManager] fileExistsAtPath:newLogFileInfo.filePath]);
  114. __auto_type oldString = [NSString stringWithContentsOfFile:oldLogFileInfo.filePath
  115. encoding:NSUTF8StringEncoding
  116. error:nil];
  117. __auto_type newString = [NSString stringWithContentsOfFile:newLogFileInfo.filePath
  118. encoding:NSUTF8StringEncoding
  119. error:nil];
  120. XCTAssertFalse(oldString.length == 0);
  121. XCTAssertFalse(newString.length == 0);
  122. XCTAssertTrue([oldString containsString:@"Some log in the old file"]);
  123. XCTAssertTrue([newString containsString:@"Some log in the new file"]);
  124. }
  125. - (void)testExplicitLogFileRollingWhenNotReusingLogFiles {
  126. logger.doNotReuseLogFiles = YES;
  127. [DDLog addLogger:logger];
  128. DDLogError(@"Log 1 in the old file");
  129. DDLogError(@"Log 2 in the old file");
  130. __auto_type expectation = [self expectationWithDescription:@"Waiting for the log file to be rolled"];
  131. [logger rollLogFileWithCompletionBlock:^{
  132. [expectation fulfill];
  133. }];
  134. [self waitForExpectationsWithTimeout:3 handler:^(NSError * _Nullable error) {
  135. XCTAssertNil(error);
  136. }];
  137. DDLogError(@"Log 1 in the new file");
  138. DDLogError(@"Log 2 in the new file");
  139. XCTAssertEqual(logger.logFileManager.unsortedLogFileInfos.count, 2);
  140. }
  141. - (void)testAutomaticLogFileRollingWhenNotReusingLogFiles {
  142. // Use new logger so that it appears to be resuming.
  143. DDFileLogger *newLogger = [[DDFileLogger alloc] initWithLogFileManager:logFileManager];
  144. newLogger.doNotReuseLogFiles = YES;
  145. [DDLog addLogger:logger];
  146. DDLogError(@"Some log in the old file");
  147. __auto_type oldLogFileInfo = [logger currentLogFileInfo];
  148. usleep(1000); // prevent file name clash due to same time.
  149. __auto_type newLogFileInfo = [newLogger currentLogFileInfo];
  150. XCTAssertNotNil(oldLogFileInfo);
  151. XCTAssertNotNil(newLogFileInfo);
  152. XCTAssertNotEqualObjects(oldLogFileInfo.filePath, newLogFileInfo.filePath);
  153. XCTAssertEqualObjects(oldLogFileInfo.filePath, logFileManager.archivedLogFilePath);
  154. XCTAssertTrue(oldLogFileInfo.isArchived);
  155. XCTAssertFalse(newLogFileInfo.isArchived);
  156. }
  157. - (void)testCurrentLogFileInfoWhenNotReusingLogFilesOnlyCreatesNewLogFilesIfNecessary {
  158. logger.doNotReuseLogFiles = YES;
  159. __auto_type info1 = logger.currentLogFileInfo;
  160. __auto_type info2 = logger.currentLogFileInfo;
  161. XCTAssertEqualObjects(info1.filePath, info2.filePath);
  162. info2.isArchived = YES;
  163. usleep(1000); // make sure we have a different msec count. Otherwise the file names might be equal.
  164. __auto_type info3 = logger.currentLogFileInfo;
  165. __auto_type info4 = logger.currentLogFileInfo;
  166. XCTAssertEqualObjects(info3.filePath, info4.filePath);
  167. XCTAssertNotEqualObjects(info2.filePath, info3.filePath);
  168. XCTAssertEqual(logger.logFileManager.unsortedLogFileInfos.count, 2);
  169. }
  170. - (void)testExtendedAttributes {
  171. logger.doNotReuseLogFiles = YES;
  172. __auto_type info = logger.currentLogFileInfo;
  173. char buffer[1];
  174. ssize_t result = getxattr([info.filePath fileSystemRepresentation], "lumberjack.log.archived", buffer, 1, 0, 0);
  175. XCTAssertLessThan(result, 0);
  176. XCTAssertEqual(errno, ENOATTR);
  177. info.isArchived = YES;
  178. XCTAssertTrue(info.isArchived);
  179. result = getxattr([info.filePath fileSystemRepresentation], "lumberjack.log.archived", buffer, 1, 0, 0);
  180. XCTAssertEqual(result, 1);
  181. XCTAssertEqual(buffer[0], 0x01);
  182. info.isArchived = NO;
  183. XCTAssertFalse(info.isArchived);
  184. result = getxattr([info.filePath fileSystemRepresentation], "lumberjack.log.archived", buffer, 1, 0, 0);
  185. XCTAssertLessThan(result, 0);
  186. XCTAssertEqual(errno, ENOATTR);
  187. }
  188. - (void)testExtendedAttributesBackwardCompatibility {
  189. logger.doNotReuseLogFiles = YES;
  190. __auto_type info = logger.currentLogFileInfo;
  191. char buffer[1];
  192. #if TARGET_IPHONE_SIMULATOR
  193. [info renameFile:@"dummy.archived.log"];
  194. XCTAssertTrue(info.isArchived);
  195. ssize_t result = getxattr([info.filePath fileSystemRepresentation], "lumberjack.log.archived", buffer, 1, 0, 0);
  196. XCTAssertEqual(result, 1);
  197. XCTAssertEqual(buffer[0], 0x01);
  198. XCTAssertEqualObjects(info.fileName, @"dummy.log");
  199. [info renameFile:@"dummy.archived.log"];
  200. info.isArchived = YES;
  201. XCTAssertTrue(info.isArchived);
  202. XCTAssertEqualObjects(info.fileName, @"dummy.log");
  203. [info renameFile:@"dummy.archived.log"];
  204. info.isArchived = NO;
  205. XCTAssertFalse(info.isArchived);
  206. XCTAssertEqualObjects(info.fileName, @"dummy.log");
  207. #else
  208. int err = setxattr([info.filePath fileSystemRepresentation], "lumberjack.log.archived", "", 0, 0, 0);
  209. XCTAssertEqual(err, 0);
  210. XCTAssertTrue(info.isArchived);
  211. ssize_t result = getxattr([info.filePath fileSystemRepresentation], "lumberjack.log.archived", buffer, 1, 0, 0);
  212. XCTAssertEqual(result, 1);
  213. XCTAssertEqual(buffer[0], 0x01);
  214. #endif
  215. }
  216. - (void)testMaximumNumberOfLogFiles {
  217. logger.doNotReuseLogFiles = YES;
  218. logger.logFileManager.maximumNumberOfLogFiles = 4;
  219. logger.maximumFileSize = 10;
  220. [DDLog addLogger:logger];
  221. DDLogError(@"Log 1 in the file");
  222. DDLogError(@"Log 2 in the file");
  223. DDLogError(@"Log 3 in the file");
  224. DDLogError(@"Log 4 in the file");
  225. /// wait log queue finish.
  226. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  227. NSArray *oldFileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self->logger.logFileManager.logsDirectory error:nil];
  228. XCTAssertEqual(oldFileNames.count, 4);
  229. self->logger.logFileManager.maximumNumberOfLogFiles = 2;
  230. /// wait delete old files finish.
  231. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  232. NSArray *newFileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self->logger.logFileManager.logsDirectory error:nil];
  233. XCTAssertEqual(newFileNames.count, 2);
  234. });
  235. });
  236. }
  237. - (void)testWrapping {
  238. __auto_type wrapped = [logger wrapWithBuffer];
  239. XCTAssert([wrapped.class isSubclassOfClass:NSProxy.class]);
  240. __auto_type wrapped2 = [wrapped wrapWithBuffer];
  241. XCTAssertEqual(wrapped2, wrapped);
  242. __auto_type unwrapped = [wrapped unwrapFromBuffer];
  243. XCTAssert([unwrapped.class isSubclassOfClass:DDFileLogger.class]);
  244. __auto_type unwrapped2 = [unwrapped unwrapFromBuffer];
  245. XCTAssertEqual(unwrapped2, unwrapped);
  246. }
  247. - (void)testWriteToFileUnbuffered {
  248. logger = [logger unwrapFromBuffer];
  249. [DDLog addLogger:logger];
  250. DDLogError(@"%@", @"error");
  251. DDLogWarn(@"%@", @"warn");
  252. DDLogInfo(@"%@", @"info");
  253. DDLogDebug(@"%@", @"debug");
  254. DDLogVerbose(@"%@", @"verbose");
  255. [DDLog flushLog];
  256. NSString* filePath = logger.currentLogFileInfo.filePath;
  257. XCTAssertNotNil(filePath);
  258. NSError *error = nil;
  259. NSData *data = [NSData dataWithContentsOfFile:filePath options:NSDataReadingUncached error:&error];
  260. XCTAssertNil(error);
  261. NSString *contents = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  262. XCTAssertEqual([contents componentsSeparatedByString:@"\n"].count, 5 + 2);
  263. }
  264. - (void)testWriteToFileBuffered {
  265. logger = [logger wrapWithBuffer];
  266. [DDLog addLogger:logger];
  267. DDLogError(@"%@", @"error");
  268. DDLogWarn(@"%@", @"warn");
  269. DDLogInfo(@"%@", @"info");
  270. DDLogDebug(@"%@", @"debug");
  271. DDLogVerbose(@"%@", @"verbose");
  272. [DDLog flushLog];
  273. NSString* filePath = logger.currentLogFileInfo.filePath;
  274. XCTAssertNotNil(filePath);
  275. NSError *error = nil;
  276. NSData *data = [NSData dataWithContentsOfFile:filePath options:NSDataReadingUncached error:&error];
  277. XCTAssertNil(error);
  278. NSString *contents = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  279. XCTAssertEqual([contents componentsSeparatedByString:@"\n"].count, 5 + 2);
  280. }
  281. - (void)testOverwriteSymlink {
  282. NSString* customFileName = @"testIgnoreSymlink_file_name.log";
  283. logFileManager.customLogFileName = customFileName;
  284. NSString* logFileName = [logFileManager.logsDirectory stringByAppendingPathComponent:customFileName];
  285. NSString *tempFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSUUID UUID] UUIDString]];
  286. [NSFileManager.defaultManager createFileAtPath:tempFilePath contents:nil attributes:nil];
  287. [NSFileManager.defaultManager createDirectoryAtPath:logFileManager.logsDirectory
  288. withIntermediateDirectories:YES
  289. attributes:nil
  290. error:nil];
  291. [NSFileManager.defaultManager createSymbolicLinkAtPath:logFileName withDestinationPath:tempFilePath error:nil];
  292. __auto_type info = logger.currentLogFileInfo;
  293. XCTAssertEqualObjects(info.fileName, customFileName);
  294. XCTAssertFalse(info.isSymlink);
  295. }
  296. - (void)testSerializer {
  297. logFileManager.logMessageSerializer = [[DDMockedSerializer alloc] initWithSerializerBlock:^NSData *(NSString * string, DDLogMessage * msg) {
  298. NSString *resultingString = [NSString stringWithFormat:@"MessageLength: %lu; Message: %@", string.length, string];
  299. if (msg) {
  300. resultingString = [resultingString stringByAppendingString:@"; Message was non-nil"];
  301. }
  302. return [resultingString dataUsingEncoding:NSUTF8StringEncoding];
  303. }];
  304. logger.logFormatter = nil;
  305. __auto_type msg = [[DDLogMessage alloc] initWithFormat:@"SOME FORMAT"
  306. formatted:@"FORMATTED"
  307. level:DDLogLevelInfo
  308. flag:DDLogFlagInfo
  309. context:0
  310. file:@"FILE"
  311. function:@"FUNCTION"
  312. line:1
  313. tag:nil
  314. options:0
  315. timestamp:[NSDate date]];
  316. __block NSData *data = nil;
  317. dispatch_sync(DDLog.loggingQueue, ^{
  318. dispatch_sync(logger->_loggerQueue, ^{
  319. data = [logger lt_dataForMessage:msg];
  320. });
  321. });
  322. XCTAssertNotNil(data);
  323. __auto_type string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  324. XCTAssertNotNil(string);
  325. __auto_type formattedMsg = [msg.message stringByAppendingString:@"\n"];
  326. __auto_type expectedString = [NSString stringWithFormat:@"MessageLength: %ld; Message: %@; Message was non-nil", formattedMsg.length, formattedMsg];
  327. XCTAssertEqualObjects(string, expectedString);
  328. }
  329. @end