DDFileLogger.m 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712
  1. // Software License Agreement (BSD License)
  2. //
  3. // Copyright (c) 2010-2019, 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 "DDFileLogger.h"
  16. #import "DDFileLogger+Internal.h"
  17. #import <sys/xattr.h>
  18. #if !__has_feature(objc_arc)
  19. #error This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
  20. #endif
  21. // We probably shouldn't be using DDLog() statements within the DDLog implementation.
  22. // But we still want to leave our log statements for any future debugging,
  23. // and to allow other developers to trace the implementation (which is a great learning tool).
  24. //
  25. // So we use primitive logging macros around NSLog.
  26. // We maintain the NS prefix on the macros to be explicit about the fact that we're using NSLog.
  27. #ifndef DD_NSLOG_LEVEL
  28. #define DD_NSLOG_LEVEL 2
  29. #endif
  30. #define NSLogError(frmt, ...) do{ if(DD_NSLOG_LEVEL >= 1) NSLog((frmt), ##__VA_ARGS__); } while(0)
  31. #define NSLogWarn(frmt, ...) do{ if(DD_NSLOG_LEVEL >= 2) NSLog((frmt), ##__VA_ARGS__); } while(0)
  32. #define NSLogInfo(frmt, ...) do{ if(DD_NSLOG_LEVEL >= 3) NSLog((frmt), ##__VA_ARGS__); } while(0)
  33. #define NSLogDebug(frmt, ...) do{ if(DD_NSLOG_LEVEL >= 4) NSLog((frmt), ##__VA_ARGS__); } while(0)
  34. #define NSLogVerbose(frmt, ...) do{ if(DD_NSLOG_LEVEL >= 5) NSLog((frmt), ##__VA_ARGS__); } while(0)
  35. #if TARGET_OS_IPHONE
  36. BOOL doesAppRunInBackground(void);
  37. #endif
  38. unsigned long long const kDDDefaultLogMaxFileSize = 1024 * 1024; // 1 MB
  39. NSTimeInterval const kDDDefaultLogRollingFrequency = 60 * 60 * 24; // 24 Hours
  40. NSUInteger const kDDDefaultLogMaxNumLogFiles = 5; // 5 Files
  41. unsigned long long const kDDDefaultLogFilesDiskQuota = 20 * 1024 * 1024; // 20 MB
  42. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  43. #pragma mark -
  44. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  45. @interface DDLogFileManagerDefault () {
  46. NSUInteger _maximumNumberOfLogFiles;
  47. unsigned long long _logFilesDiskQuota;
  48. NSString *_logsDirectory;
  49. #if TARGET_OS_IPHONE
  50. NSFileProtectionType _defaultFileProtectionLevel;
  51. #endif
  52. }
  53. @end
  54. @implementation DDLogFileManagerDefault
  55. @synthesize maximumNumberOfLogFiles = _maximumNumberOfLogFiles;
  56. @synthesize logFilesDiskQuota = _logFilesDiskQuota;
  57. - (instancetype)init {
  58. return [self initWithLogsDirectory:nil];
  59. }
  60. - (instancetype)initWithLogsDirectory:(NSString * __nullable)aLogsDirectory {
  61. if ((self = [super init])) {
  62. _maximumNumberOfLogFiles = kDDDefaultLogMaxNumLogFiles;
  63. _logFilesDiskQuota = kDDDefaultLogFilesDiskQuota;
  64. if (aLogsDirectory.length > 0) {
  65. _logsDirectory = [aLogsDirectory copy];
  66. } else {
  67. _logsDirectory = [[self defaultLogsDirectory] copy];
  68. }
  69. NSKeyValueObservingOptions kvoOptions = NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew;
  70. [self addObserver:self forKeyPath:NSStringFromSelector(@selector(maximumNumberOfLogFiles)) options:kvoOptions context:nil];
  71. [self addObserver:self forKeyPath:NSStringFromSelector(@selector(logFilesDiskQuota)) options:kvoOptions context:nil];
  72. NSLogVerbose(@"DDFileLogManagerDefault: logsDirectory:\n%@", [self logsDirectory]);
  73. NSLogVerbose(@"DDFileLogManagerDefault: sortedLogFileNames:\n%@", [self sortedLogFileNames]);
  74. }
  75. return self;
  76. }
  77. + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)theKey {
  78. if ([theKey isEqualToString:@"maximumNumberOfLogFiles"] || [theKey isEqualToString:@"logFilesDiskQuota"]) {
  79. return NO;
  80. } else {
  81. return [super automaticallyNotifiesObserversForKey:theKey];
  82. }
  83. }
  84. #if TARGET_OS_IPHONE
  85. - (instancetype)initWithLogsDirectory:(NSString *)logsDirectory
  86. defaultFileProtectionLevel:(NSFileProtectionType)fileProtectionLevel {
  87. if ((self = [self initWithLogsDirectory:logsDirectory])) {
  88. if ([fileProtectionLevel isEqualToString:NSFileProtectionNone] ||
  89. [fileProtectionLevel isEqualToString:NSFileProtectionComplete] ||
  90. [fileProtectionLevel isEqualToString:NSFileProtectionCompleteUnlessOpen] ||
  91. [fileProtectionLevel isEqualToString:NSFileProtectionCompleteUntilFirstUserAuthentication]) {
  92. _defaultFileProtectionLevel = fileProtectionLevel;
  93. }
  94. }
  95. return self;
  96. }
  97. #endif
  98. - (void)dealloc {
  99. // try-catch because the observer might be removed or never added. In this case, removeObserver throws and exception
  100. @try {
  101. [self removeObserver:self forKeyPath:NSStringFromSelector(@selector(maximumNumberOfLogFiles))];
  102. [self removeObserver:self forKeyPath:NSStringFromSelector(@selector(logFilesDiskQuota))];
  103. } @catch (NSException *exception) {
  104. }
  105. }
  106. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  107. #pragma mark Configuration
  108. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  109. - (void)observeValueForKeyPath:(NSString *)keyPath
  110. ofObject:(__unused id)object
  111. change:(NSDictionary *)change
  112. context:(__unused void *)context {
  113. NSNumber *old = change[NSKeyValueChangeOldKey];
  114. NSNumber *new = change[NSKeyValueChangeNewKey];
  115. if ([old isEqual:new]) {
  116. return;
  117. }
  118. if ([keyPath isEqualToString:NSStringFromSelector(@selector(maximumNumberOfLogFiles))] ||
  119. [keyPath isEqualToString:NSStringFromSelector(@selector(logFilesDiskQuota))]) {
  120. NSLogInfo(@"DDFileLogManagerDefault: Responding to configuration change: %@", keyPath);
  121. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  122. @autoreleasepool {
  123. // See method header for queue reasoning.
  124. [self deleteOldLogFiles];
  125. }
  126. });
  127. }
  128. }
  129. #if TARGET_OS_IPHONE
  130. - (NSFileProtectionType)logFileProtection {
  131. if (_defaultFileProtectionLevel.length > 0) {
  132. return _defaultFileProtectionLevel;
  133. } else if (doesAppRunInBackground()) {
  134. return NSFileProtectionCompleteUntilFirstUserAuthentication;
  135. } else {
  136. return NSFileProtectionCompleteUnlessOpen;
  137. }
  138. }
  139. #endif
  140. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  141. #pragma mark File Deleting
  142. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  143. /**
  144. * Deletes archived log files that exceed the maximumNumberOfLogFiles or logFilesDiskQuota configuration values.
  145. * Method may take a while to execute since we're performing IO. It's not critical that this is synchronized with
  146. * log output, since the files we're deleting are all archived and not in use, therefore this method is called on a
  147. * background queue.
  148. **/
  149. - (void)deleteOldLogFiles {
  150. NSLogVerbose(@"DDLogFileManagerDefault: deleteOldLogFiles");
  151. NSArray *sortedLogFileInfos = [self sortedLogFileInfos];
  152. NSUInteger firstIndexToDelete = NSNotFound;
  153. const unsigned long long diskQuota = self.logFilesDiskQuota;
  154. const NSUInteger maxNumLogFiles = self.maximumNumberOfLogFiles;
  155. if (diskQuota) {
  156. unsigned long long used = 0;
  157. for (NSUInteger i = 0; i < sortedLogFileInfos.count; i++) {
  158. DDLogFileInfo *info = sortedLogFileInfos[i];
  159. used += info.fileSize;
  160. if (used > diskQuota) {
  161. firstIndexToDelete = i;
  162. break;
  163. }
  164. }
  165. }
  166. if (maxNumLogFiles) {
  167. if (firstIndexToDelete == NSNotFound) {
  168. firstIndexToDelete = maxNumLogFiles;
  169. } else {
  170. firstIndexToDelete = MIN(firstIndexToDelete, maxNumLogFiles);
  171. }
  172. }
  173. if (firstIndexToDelete == 0) {
  174. // Do we consider the first file?
  175. // We are only supposed to be deleting archived files.
  176. // In most cases, the first file is likely the log file that is currently being written to.
  177. // So in most cases, we do not want to consider this file for deletion.
  178. if (sortedLogFileInfos.count > 0) {
  179. DDLogFileInfo *logFileInfo = sortedLogFileInfos[0];
  180. if (!logFileInfo.isArchived) {
  181. // Don't delete active file.
  182. ++firstIndexToDelete;
  183. }
  184. }
  185. }
  186. if (firstIndexToDelete != NSNotFound) {
  187. // removing all log files starting with firstIndexToDelete
  188. for (NSUInteger i = firstIndexToDelete; i < sortedLogFileInfos.count; i++) {
  189. DDLogFileInfo *logFileInfo = sortedLogFileInfos[i];
  190. NSError *error = nil;
  191. BOOL success = [[NSFileManager defaultManager] removeItemAtPath:logFileInfo.filePath error:&error];
  192. if (success) {
  193. NSLogInfo(@"DDLogFileManagerDefault: Deleting file: %@", logFileInfo.fileName);
  194. } else {
  195. NSLogError(@"DDLogFileManagerDefault: Error deleting file %@", error);
  196. }
  197. }
  198. }
  199. }
  200. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  201. #pragma mark Log Files
  202. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  203. /**
  204. * Returns the path to the default logs directory.
  205. * If the logs directory doesn't exist, this method automatically creates it.
  206. **/
  207. - (NSString *)defaultLogsDirectory {
  208. #if TARGET_OS_IPHONE
  209. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  210. NSString *baseDir = paths.firstObject;
  211. NSString *logsDirectory = [baseDir stringByAppendingPathComponent:@"Logs"];
  212. #else
  213. NSString *appName = [[NSProcessInfo processInfo] processName];
  214. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
  215. NSString *basePath = ([paths count] > 0) ? paths[0] : NSTemporaryDirectory();
  216. NSString *logsDirectory = [[basePath stringByAppendingPathComponent:@"Logs"] stringByAppendingPathComponent:appName];
  217. #endif
  218. return logsDirectory;
  219. }
  220. - (NSString *)logsDirectory {
  221. // We could do this check once, during initialization, and not bother again.
  222. // But this way the code continues to work if the directory gets deleted while the code is running.
  223. NSAssert(_logsDirectory.length > 0, @"Directory must be set.");
  224. NSError *err = nil;
  225. BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:_logsDirectory
  226. withIntermediateDirectories:YES
  227. attributes:nil
  228. error:&err];
  229. if (success == NO) {
  230. NSLogError(@"DDFileLogManagerDefault: Error creating logsDirectory: %@", err);
  231. }
  232. return _logsDirectory;
  233. }
  234. - (BOOL)isLogFile:(NSString *)fileName {
  235. NSString *appName = [self applicationName];
  236. // We need to add a space to the name as otherwise we could match applications that have the name prefix.
  237. BOOL hasProperPrefix = [fileName hasPrefix:[appName stringByAppendingString:@" "]];
  238. BOOL hasProperSuffix = [fileName hasSuffix:@".log"];
  239. return (hasProperPrefix && hasProperSuffix);
  240. }
  241. // if you change formatter, then change sortedLogFileInfos method also accordingly
  242. - (NSDateFormatter *)logFileDateFormatter {
  243. NSMutableDictionary *dictionary = [[NSThread currentThread] threadDictionary];
  244. NSString *dateFormat = @"yyyy'-'MM'-'dd'--'HH'-'mm'-'ss'-'SSS'";
  245. NSString *key = [NSString stringWithFormat:@"logFileDateFormatter.%@", dateFormat];
  246. NSDateFormatter *dateFormatter = dictionary[key];
  247. if (dateFormatter == nil) {
  248. dateFormatter = [[NSDateFormatter alloc] init];
  249. [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
  250. [dateFormatter setDateFormat:dateFormat];
  251. [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  252. dictionary[key] = dateFormatter;
  253. }
  254. return dateFormatter;
  255. }
  256. - (NSArray *)unsortedLogFilePaths {
  257. NSString *logsDirectory = [self logsDirectory];
  258. NSArray *fileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:logsDirectory error:nil];
  259. NSMutableArray *unsortedLogFilePaths = [NSMutableArray arrayWithCapacity:[fileNames count]];
  260. for (NSString *fileName in fileNames) {
  261. // Filter out any files that aren't log files. (Just for extra safety)
  262. #if TARGET_IPHONE_SIMULATOR
  263. // In case of iPhone simulator there can be 'archived' extension. isLogFile:
  264. // method knows nothing about it. Thus removing it for this method.
  265. //
  266. // See full explanation in the header file.
  267. NSString *theFileName = [fileName stringByReplacingOccurrencesOfString:@".archived"
  268. withString:@""];
  269. if ([self isLogFile:theFileName])
  270. #else
  271. if ([self isLogFile:fileName])
  272. #endif
  273. {
  274. NSString *filePath = [logsDirectory stringByAppendingPathComponent:fileName];
  275. [unsortedLogFilePaths addObject:filePath];
  276. }
  277. }
  278. return unsortedLogFilePaths;
  279. }
  280. - (NSArray *)unsortedLogFileNames {
  281. NSArray *unsortedLogFilePaths = [self unsortedLogFilePaths];
  282. NSMutableArray *unsortedLogFileNames = [NSMutableArray arrayWithCapacity:[unsortedLogFilePaths count]];
  283. for (NSString *filePath in unsortedLogFilePaths) {
  284. [unsortedLogFileNames addObject:[filePath lastPathComponent]];
  285. }
  286. return unsortedLogFileNames;
  287. }
  288. - (NSArray *)unsortedLogFileInfos {
  289. NSArray *unsortedLogFilePaths = [self unsortedLogFilePaths];
  290. NSMutableArray *unsortedLogFileInfos = [NSMutableArray arrayWithCapacity:[unsortedLogFilePaths count]];
  291. for (NSString *filePath in unsortedLogFilePaths) {
  292. DDLogFileInfo *logFileInfo = [[DDLogFileInfo alloc] initWithFilePath:filePath];
  293. [unsortedLogFileInfos addObject:logFileInfo];
  294. }
  295. return unsortedLogFileInfos;
  296. }
  297. - (NSArray *)sortedLogFilePaths {
  298. NSArray *sortedLogFileInfos = [self sortedLogFileInfos];
  299. NSMutableArray *sortedLogFilePaths = [NSMutableArray arrayWithCapacity:[sortedLogFileInfos count]];
  300. for (DDLogFileInfo *logFileInfo in sortedLogFileInfos) {
  301. [sortedLogFilePaths addObject:[logFileInfo filePath]];
  302. }
  303. return sortedLogFilePaths;
  304. }
  305. - (NSArray *)sortedLogFileNames {
  306. NSArray *sortedLogFileInfos = [self sortedLogFileInfos];
  307. NSMutableArray *sortedLogFileNames = [NSMutableArray arrayWithCapacity:[sortedLogFileInfos count]];
  308. for (DDLogFileInfo *logFileInfo in sortedLogFileInfos) {
  309. [sortedLogFileNames addObject:[logFileInfo fileName]];
  310. }
  311. return sortedLogFileNames;
  312. }
  313. - (NSArray *)sortedLogFileInfos {
  314. return [[self unsortedLogFileInfos] sortedArrayUsingComparator:^NSComparisonResult(DDLogFileInfo *obj1,
  315. DDLogFileInfo *obj2) {
  316. NSDate *date1 = [NSDate new];
  317. NSDate *date2 = [NSDate new];
  318. NSArray<NSString *> *arrayComponent = [[obj1 fileName] componentsSeparatedByString:@" "];
  319. if (arrayComponent.count > 0) {
  320. NSString *stringDate = arrayComponent.lastObject;
  321. stringDate = [stringDate stringByReplacingOccurrencesOfString:@".log" withString:@""];
  322. stringDate = [stringDate stringByReplacingOccurrencesOfString:@".archived" withString:@""];
  323. date1 = [[self logFileDateFormatter] dateFromString:stringDate] ?: [obj1 creationDate];
  324. }
  325. arrayComponent = [[obj2 fileName] componentsSeparatedByString:@" "];
  326. if (arrayComponent.count > 0) {
  327. NSString *stringDate = arrayComponent.lastObject;
  328. stringDate = [stringDate stringByReplacingOccurrencesOfString:@".log" withString:@""];
  329. stringDate = [stringDate stringByReplacingOccurrencesOfString:@".archived" withString:@""];
  330. date2 = [[self logFileDateFormatter] dateFromString:stringDate] ?: [obj2 creationDate];
  331. }
  332. return [date2 compare:date1 ?: [NSDate new]];
  333. }];
  334. }
  335. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  336. #pragma mark Creation
  337. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  338. //if you change newLogFileName , then change isLogFile method also accordingly
  339. - (NSString *)newLogFileName {
  340. NSString *appName = [self applicationName];
  341. NSDateFormatter *dateFormatter = [self logFileDateFormatter];
  342. NSString *formattedDate = [dateFormatter stringFromDate:[NSDate date]];
  343. return [NSString stringWithFormat:@"%@ %@.log", appName, formattedDate];
  344. }
  345. - (NSString * __nullable)logFileHeader {
  346. return nil;
  347. }
  348. - (NSData *)logFileHeaderData {
  349. NSString *fileHeaderStr = [self logFileHeader];
  350. if (fileHeaderStr.length == 0) {
  351. return nil;
  352. }
  353. if (![fileHeaderStr hasSuffix:@"\n"]) {
  354. fileHeaderStr = [fileHeaderStr stringByAppendingString:@"\n"];
  355. }
  356. return [fileHeaderStr dataUsingEncoding:NSUTF8StringEncoding];
  357. }
  358. - (NSString *)createNewLogFile {
  359. static NSUInteger MAX_ALLOWED_ERROR = 5;
  360. NSString *fileName = [self newLogFileName];
  361. NSString *logsDirectory = [self logsDirectory];
  362. NSData *fileHeader = [self logFileHeaderData];
  363. if (fileHeader == nil) {
  364. fileHeader = [NSData new];
  365. }
  366. NSUInteger attempt = 1;
  367. NSUInteger criticalErrors = 0;
  368. do {
  369. if (criticalErrors >= MAX_ALLOWED_ERROR) {
  370. NSLogError(@"DDLogFileManagerDefault: Bailing file creation, encountered %ld errors.",
  371. (unsigned long)criticalErrors);
  372. return nil;
  373. }
  374. NSString *actualFileName = fileName;
  375. if (attempt > 1) {
  376. NSString *extension = [actualFileName pathExtension];
  377. actualFileName = [actualFileName stringByDeletingPathExtension];
  378. actualFileName = [actualFileName stringByAppendingFormat:@" %lu", (unsigned long)attempt];
  379. if (extension.length) {
  380. actualFileName = [actualFileName stringByAppendingPathExtension:extension];
  381. }
  382. }
  383. NSString *filePath = [logsDirectory stringByAppendingPathComponent:actualFileName];
  384. NSError *error = nil;
  385. BOOL success = [fileHeader writeToFile:filePath options:NSAtomicWrite error:&error];
  386. #if TARGET_OS_IPHONE
  387. if (success) {
  388. // When creating log file on iOS we're setting NSFileProtectionKey attribute to NSFileProtectionCompleteUnlessOpen.
  389. //
  390. // But in case if app is able to launch from background we need to have an ability to open log file any time we
  391. // want (even if device is locked). Thats why that attribute have to be changed to
  392. // NSFileProtectionCompleteUntilFirstUserAuthentication.
  393. NSDictionary *attributes = @{NSFileProtectionKey: [self logFileProtection]};
  394. success = [[NSFileManager defaultManager] setAttributes:attributes
  395. ofItemAtPath:filePath
  396. error:&error];
  397. }
  398. #endif
  399. if (success) {
  400. NSLogVerbose(@"PURLogFileManagerDefault: Created new log file: %@", actualFileName);
  401. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  402. // Since we just created a new log file, we may need to delete some old log files
  403. [self deleteOldLogFiles];
  404. });
  405. return filePath;
  406. } else if (error.code == NSFileWriteFileExistsError) {
  407. attempt++;
  408. continue;
  409. } else {
  410. NSLogError(@"PURLogFileManagerDefault: Critical error while creating log file: %@", error);
  411. criticalErrors++;
  412. continue;
  413. }
  414. return filePath;
  415. } while (YES);
  416. }
  417. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  418. #pragma mark Utility
  419. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  420. - (NSString *)applicationName {
  421. static NSString *_appName;
  422. static dispatch_once_t onceToken;
  423. dispatch_once(&onceToken, ^{
  424. _appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
  425. if (_appName.length == 0) {
  426. _appName = [[NSProcessInfo processInfo] processName];
  427. }
  428. if (_appName.length == 0) {
  429. _appName = @"";
  430. }
  431. });
  432. return _appName;
  433. }
  434. @end
  435. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  436. #pragma mark -
  437. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  438. @interface DDLogFileFormatterDefault () {
  439. NSDateFormatter *_dateFormatter;
  440. }
  441. @end
  442. @implementation DDLogFileFormatterDefault
  443. - (instancetype)init {
  444. return [self initWithDateFormatter:nil];
  445. }
  446. - (instancetype)initWithDateFormatter:(NSDateFormatter * __nullable)aDateFormatter {
  447. if ((self = [super init])) {
  448. if (aDateFormatter) {
  449. _dateFormatter = aDateFormatter;
  450. } else {
  451. _dateFormatter = [[NSDateFormatter alloc] init];
  452. [_dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4]; // 10.4+ style
  453. [_dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss:SSS"];
  454. }
  455. }
  456. return self;
  457. }
  458. - (NSString *)formatLogMessage:(DDLogMessage *)logMessage {
  459. NSString *dateAndTime = [_dateFormatter stringFromDate:(logMessage->_timestamp)];
  460. return [NSString stringWithFormat:@"%@ %@", dateAndTime, logMessage->_message];
  461. }
  462. @end
  463. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  464. #pragma mark -
  465. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  466. @interface DDFileLogger () {
  467. id <DDLogFileManager> _logFileManager;
  468. DDLogFileInfo *_currentLogFileInfo;
  469. NSFileHandle *_currentLogFileHandle;
  470. dispatch_source_t _currentLogFileVnode;
  471. NSTimeInterval _rollingFrequency;
  472. dispatch_source_t _rollingTimer;
  473. unsigned long long _maximumFileSize;
  474. dispatch_queue_t _completionQueue;
  475. }
  476. @end
  477. @implementation DDFileLogger
  478. - (instancetype)init {
  479. DDLogFileManagerDefault *defaultLogFileManager = [[DDLogFileManagerDefault alloc] init];
  480. return [self initWithLogFileManager:defaultLogFileManager completionQueue:nil];
  481. }
  482. - (instancetype)initWithLogFileManager:(id<DDLogFileManager>)logFileManager {
  483. return [self initWithLogFileManager:logFileManager completionQueue:nil];
  484. }
  485. - (instancetype)initWithLogFileManager:(id <DDLogFileManager>)aLogFileManager
  486. completionQueue:(dispatch_queue_t __nullable)dispatchQueue {
  487. if ((self = [super init])) {
  488. _completionQueue = dispatchQueue ?: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  489. _maximumFileSize = kDDDefaultLogMaxFileSize;
  490. _rollingFrequency = kDDDefaultLogRollingFrequency;
  491. _automaticallyAppendNewlineForCustomFormatters = YES;
  492. _logFileManager = aLogFileManager;
  493. _logFormatter = [DDLogFileFormatterDefault new];
  494. }
  495. return self;
  496. }
  497. - (void)lt_cleanup {
  498. NSAssert([self isOnInternalLoggerQueue], @"lt_ methods should be on logger queue.");
  499. [_currentLogFileHandle synchronizeFile];
  500. [_currentLogFileHandle closeFile];
  501. if (_currentLogFileVnode) {
  502. dispatch_source_cancel(_currentLogFileVnode);
  503. _currentLogFileVnode = NULL;
  504. }
  505. if (_rollingTimer) {
  506. dispatch_source_cancel(_rollingTimer);
  507. _rollingTimer = NULL;
  508. }
  509. }
  510. - (void)dealloc {
  511. if (self.isOnInternalLoggerQueue) {
  512. [self lt_cleanup];
  513. } else {
  514. dispatch_sync(self.loggerQueue, ^{
  515. [self lt_cleanup];
  516. });
  517. }
  518. }
  519. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  520. #pragma mark Properties
  521. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  522. - (unsigned long long)maximumFileSize {
  523. __block unsigned long long result;
  524. dispatch_block_t block = ^{
  525. result = self->_maximumFileSize;
  526. };
  527. // The design of this method is taken from the DDAbstractLogger implementation.
  528. // For extensive documentation please refer to the DDAbstractLogger implementation.
  529. // Note: The internal implementation MUST access the maximumFileSize variable directly,
  530. // This method is designed explicitly for external access.
  531. //
  532. // Using "self." syntax to go through this method will cause immediate deadlock.
  533. // This is the intended result. Fix it by accessing the ivar directly.
  534. // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster.
  535. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  536. NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax.");
  537. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  538. dispatch_sync(globalLoggingQueue, ^{
  539. dispatch_sync(self.loggerQueue, block);
  540. });
  541. return result;
  542. }
  543. - (void)setMaximumFileSize:(unsigned long long)newMaximumFileSize {
  544. dispatch_block_t block = ^{
  545. @autoreleasepool {
  546. self->_maximumFileSize = newMaximumFileSize;
  547. [self lt_maybeRollLogFileDueToSize];
  548. }
  549. };
  550. // The design of this method is taken from the DDAbstractLogger implementation.
  551. // For extensive documentation please refer to the DDAbstractLogger implementation.
  552. // Note: The internal implementation MUST access the maximumFileSize variable directly,
  553. // This method is designed explicitly for external access.
  554. //
  555. // Using "self." syntax to go through this method will cause immediate deadlock.
  556. // This is the intended result. Fix it by accessing the ivar directly.
  557. // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster.
  558. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  559. NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax.");
  560. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  561. dispatch_async(globalLoggingQueue, ^{
  562. dispatch_async(self.loggerQueue, block);
  563. });
  564. }
  565. - (NSTimeInterval)rollingFrequency {
  566. __block NSTimeInterval result;
  567. dispatch_block_t block = ^{
  568. result = self->_rollingFrequency;
  569. };
  570. // The design of this method is taken from the DDAbstractLogger implementation.
  571. // For extensive documentation please refer to the DDAbstractLogger implementation.
  572. // Note: The internal implementation should access the rollingFrequency variable directly,
  573. // This method is designed explicitly for external access.
  574. //
  575. // Using "self." syntax to go through this method will cause immediate deadlock.
  576. // This is the intended result. Fix it by accessing the ivar directly.
  577. // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster.
  578. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  579. NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax.");
  580. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  581. dispatch_sync(globalLoggingQueue, ^{
  582. dispatch_sync(self.loggerQueue, block);
  583. });
  584. return result;
  585. }
  586. - (void)setRollingFrequency:(NSTimeInterval)newRollingFrequency {
  587. dispatch_block_t block = ^{
  588. @autoreleasepool {
  589. self->_rollingFrequency = newRollingFrequency;
  590. [self lt_maybeRollLogFileDueToAge];
  591. }
  592. };
  593. // The design of this method is taken from the DDAbstractLogger implementation.
  594. // For extensive documentation please refer to the DDAbstractLogger implementation.
  595. // Note: The internal implementation should access the rollingFrequency variable directly,
  596. // This method is designed explicitly for external access.
  597. //
  598. // Using "self." syntax to go through this method will cause immediate deadlock.
  599. // This is the intended result. Fix it by accessing the ivar directly.
  600. // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster.
  601. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  602. NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax.");
  603. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  604. dispatch_async(globalLoggingQueue, ^{
  605. dispatch_async(self.loggerQueue, block);
  606. });
  607. }
  608. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  609. #pragma mark File Rolling
  610. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  611. - (void)lt_scheduleTimerToRollLogFileDueToAge {
  612. NSAssert([self isOnInternalLoggerQueue], @"lt_ methods should be on logger queue.");
  613. if (_rollingTimer) {
  614. dispatch_source_cancel(_rollingTimer);
  615. _rollingTimer = NULL;
  616. }
  617. if (_currentLogFileInfo == nil || _rollingFrequency <= 0.0) {
  618. return;
  619. }
  620. NSDate *logFileCreationDate = [_currentLogFileInfo creationDate];
  621. NSTimeInterval frequency = MIN(_rollingFrequency, DBL_MAX - [logFileCreationDate timeIntervalSinceReferenceDate]);
  622. NSDate *logFileRollingDate = [logFileCreationDate dateByAddingTimeInterval:frequency];
  623. NSLogVerbose(@"DDFileLogger: scheduleTimerToRollLogFileDueToAge");
  624. NSLogVerbose(@"DDFileLogger: logFileCreationDate : %@", logFileCreationDate);
  625. NSLogVerbose(@"DDFileLogger: actual rollingFrequency: %f", frequency);
  626. NSLogVerbose(@"DDFileLogger: logFileRollingDate : %@", logFileRollingDate);
  627. _rollingTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _loggerQueue);
  628. __weak __auto_type weakSelf = self;
  629. dispatch_source_set_event_handler(_rollingTimer, ^{ @autoreleasepool {
  630. [weakSelf lt_maybeRollLogFileDueToAge];
  631. } });
  632. #if !OS_OBJECT_USE_OBJC
  633. dispatch_source_t theRollingTimer = _rollingTimer;
  634. dispatch_source_set_cancel_handler(_rollingTimer, ^{
  635. dispatch_release(theRollingTimer);
  636. });
  637. #endif
  638. static NSTimeInterval const kDDMaxTimerDelay = LONG_LONG_MAX / NSEC_PER_SEC;
  639. int64_t delay = (int64_t)(MIN([logFileRollingDate timeIntervalSinceNow], kDDMaxTimerDelay) * (NSTimeInterval) NSEC_PER_SEC);
  640. dispatch_time_t fireTime = dispatch_time(DISPATCH_TIME_NOW, delay);
  641. dispatch_source_set_timer(_rollingTimer, fireTime, DISPATCH_TIME_FOREVER, 1ull * NSEC_PER_SEC);
  642. dispatch_resume(_rollingTimer);
  643. }
  644. - (void)rollLogFile {
  645. [self rollLogFileWithCompletionBlock:nil];
  646. }
  647. - (void)rollLogFileWithCompletionBlock:(void (^ __nullable)(void))completionBlock {
  648. // This method is public.
  649. // We need to execute the rolling on our logging thread/queue.
  650. dispatch_block_t block = ^{
  651. @autoreleasepool {
  652. [self lt_rollLogFileNow];
  653. if (completionBlock) {
  654. dispatch_async(self->_completionQueue, ^{
  655. completionBlock();
  656. });
  657. }
  658. }
  659. };
  660. // The design of this method is taken from the DDAbstractLogger implementation.
  661. // For extensive documentation please refer to the DDAbstractLogger implementation.
  662. if ([self isOnInternalLoggerQueue]) {
  663. block();
  664. } else {
  665. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  666. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  667. dispatch_async(globalLoggingQueue, ^{
  668. dispatch_async(self.loggerQueue, block);
  669. });
  670. }
  671. }
  672. - (void)lt_rollLogFileNow {
  673. NSAssert([self isOnInternalLoggerQueue], @"lt_ methods should be on logger queue.");
  674. NSLogVerbose(@"DDFileLogger: rollLogFileNow");
  675. if (_currentLogFileHandle == nil) {
  676. return;
  677. }
  678. [_currentLogFileHandle synchronizeFile];
  679. [_currentLogFileHandle closeFile];
  680. _currentLogFileHandle = nil;
  681. _currentLogFileInfo.isArchived = YES;
  682. NSString *archivedFilePath = [_currentLogFileInfo.filePath copy];
  683. _currentLogFileInfo = nil;
  684. if ([_logFileManager respondsToSelector:@selector(didRollAndArchiveLogFile:)]) {
  685. dispatch_async(_completionQueue, ^{
  686. [self->_logFileManager didRollAndArchiveLogFile:archivedFilePath];
  687. });
  688. }
  689. if (_currentLogFileVnode) {
  690. dispatch_source_cancel(_currentLogFileVnode);
  691. _currentLogFileVnode = nil;
  692. }
  693. if (_rollingTimer) {
  694. dispatch_source_cancel(_rollingTimer);
  695. _rollingTimer = nil;
  696. }
  697. }
  698. - (void)lt_maybeRollLogFileDueToAge {
  699. NSAssert([self isOnInternalLoggerQueue], @"lt_ methods should be on logger queue.");
  700. if (_rollingFrequency > 0.0 && _currentLogFileInfo.age >= _rollingFrequency) {
  701. NSLogVerbose(@"DDFileLogger: Rolling log file due to age...");
  702. [self lt_rollLogFileNow];
  703. } else {
  704. [self lt_scheduleTimerToRollLogFileDueToAge];
  705. }
  706. }
  707. - (void)lt_maybeRollLogFileDueToSize {
  708. NSAssert([self isOnInternalLoggerQueue], @"lt_ methods should be on logger queue.");
  709. // This method is called from logMessage.
  710. // Keep it FAST.
  711. // Note: Use direct access to maximumFileSize variable.
  712. // We specifically wrote our own getter/setter method to allow us to do this (for performance reasons).
  713. if (_maximumFileSize > 0) {
  714. unsigned long long fileSize = [_currentLogFileHandle offsetInFile];
  715. if (fileSize >= _maximumFileSize) {
  716. NSLogVerbose(@"DDFileLogger: Rolling log file due to size (%qu)...", fileSize);
  717. [self lt_rollLogFileNow];
  718. }
  719. }
  720. }
  721. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  722. #pragma mark File Logging
  723. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  724. - (BOOL)lt_shouldLogFileBeArchived:(DDLogFileInfo *)mostRecentLogFileInfo {
  725. NSAssert([self isOnInternalLoggerQueue], @"lt_ methods should be on logger queue.");
  726. if (mostRecentLogFileInfo.isArchived) {
  727. return NO;
  728. } else if ([self shouldArchiveRecentLogFileInfo:mostRecentLogFileInfo]) {
  729. return YES;
  730. } else if (_maximumFileSize > 0 && mostRecentLogFileInfo.fileSize >= _maximumFileSize) {
  731. return YES;
  732. } else if (_rollingFrequency > 0.0 && mostRecentLogFileInfo.age >= _rollingFrequency) {
  733. return YES;
  734. }
  735. #if TARGET_OS_IPHONE
  736. // When creating log file on iOS we're setting NSFileProtectionKey attribute to NSFileProtectionCompleteUnlessOpen.
  737. //
  738. // But in case if app is able to launch from background we need to have an ability to open log file any time we
  739. // want (even if device is locked). Thats why that attribute have to be changed to
  740. // NSFileProtectionCompleteUntilFirstUserAuthentication.
  741. //
  742. // If previous log was created when app wasn't running in background, but now it is - we archive it and create
  743. // a new one.
  744. //
  745. // If user has overwritten to NSFileProtectionNone there is no neeed to create a new one.
  746. if (doesAppRunInBackground()) {
  747. NSFileProtectionType key = mostRecentLogFileInfo.fileAttributes[NSFileProtectionKey];
  748. BOOL isUntilFirstAuth = [key isEqualToString:NSFileProtectionCompleteUntilFirstUserAuthentication];
  749. BOOL isNone = [key isEqualToString:NSFileProtectionNone];
  750. if (!isUntilFirstAuth && !isNone) {
  751. return YES;
  752. }
  753. }
  754. #endif
  755. return NO;
  756. }
  757. /**
  758. * Returns the log file that should be used.
  759. * If there is an existing log file that is suitable, within the
  760. * constraints of maximumFileSize and rollingFrequency, then it is returned.
  761. *
  762. * Otherwise a new file is created and returned.
  763. **/
  764. - (DDLogFileInfo *)currentLogFileInfo {
  765. // The design of this method is taken from the DDAbstractLogger implementation.
  766. // For extensive documentation please refer to the DDAbstractLogger implementation.
  767. // Do not access this method on any Lumberjack queue, will deadlock.
  768. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  769. NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax.");
  770. __block DDLogFileInfo *info = nil;
  771. dispatch_block_t block = ^{
  772. info = [self lt_currentLogFileInfo];
  773. };
  774. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  775. dispatch_sync(globalLoggingQueue, ^{
  776. dispatch_sync(self->_loggerQueue, block);
  777. });
  778. return info;
  779. }
  780. - (DDLogFileInfo *)lt_currentLogFileInfo {
  781. NSAssert([self isOnInternalLoggerQueue], @"lt_ methods should be on logger queue.");
  782. // Get the current log file info ivar (might be nil).
  783. DDLogFileInfo *newCurrentLogFile = _currentLogFileInfo;
  784. // Check if we're resuming and if so, get the first of the sorted log file infos.
  785. BOOL isResuming = newCurrentLogFile == nil;
  786. if (isResuming) {
  787. NSArray *sortedLogFileInfos = [_logFileManager sortedLogFileInfos];
  788. newCurrentLogFile = sortedLogFileInfos.firstObject;
  789. }
  790. // Check if the file we've found is still valid. Otherwise create a new one.
  791. if (newCurrentLogFile != nil && [self lt_shouldUseLogFile:newCurrentLogFile isResuming:isResuming]) {
  792. if (isResuming) {
  793. NSLogVerbose(@"DDFileLogger: Resuming logging with file %@", newCurrentLogFile.fileName);
  794. }
  795. _currentLogFileInfo = newCurrentLogFile;
  796. } else {
  797. NSString *currentLogFilePath = [_logFileManager createNewLogFile];
  798. _currentLogFileInfo = [[DDLogFileInfo alloc] initWithFilePath:currentLogFilePath];
  799. }
  800. return _currentLogFileInfo;
  801. }
  802. - (BOOL)lt_shouldUseLogFile:(nonnull DDLogFileInfo *)logFileInfo isResuming:(BOOL)isResuming {
  803. NSAssert([self isOnInternalLoggerQueue], @"lt_ methods should be on logger queue.");
  804. NSParameterAssert(logFileInfo);
  805. // Check if the log file is archived. We must not use archived log files.
  806. if (logFileInfo.isArchived) {
  807. return NO;
  808. }
  809. // If we're resuming, we need to check if the log file is allowed for reuse or needs to be archived.
  810. if (isResuming && (_doNotReuseLogFiles || [self lt_shouldLogFileBeArchived:logFileInfo])) {
  811. logFileInfo.isArchived = YES;
  812. NSString *archivedLogFilePath = [logFileInfo.fileName copy];
  813. if ([_logFileManager respondsToSelector:@selector(didArchiveLogFile:)]) {
  814. dispatch_async(_completionQueue, ^{
  815. [self->_logFileManager didArchiveLogFile:archivedLogFilePath];
  816. });
  817. }
  818. return NO;
  819. }
  820. // All checks have passed. It's valid.
  821. return YES;
  822. }
  823. - (void)lt_monitorCurrentLogFileForExternalChanges {
  824. NSAssert([self isOnInternalLoggerQueue], @"lt_ methods should be on logger queue.");
  825. NSAssert(_currentLogFileHandle, @"Can not monitor without handle.");
  826. dispatch_source_vnode_flags_t flags = DISPATCH_VNODE_DELETE | DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE;
  827. _currentLogFileVnode = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE,
  828. (uintptr_t)[_currentLogFileHandle fileDescriptor],
  829. flags,
  830. _loggerQueue);
  831. __weak __auto_type weakSelf = self;
  832. dispatch_source_set_event_handler(_currentLogFileVnode, ^{ @autoreleasepool {
  833. NSLogInfo(@"DDFileLogger: Current logfile was moved. Rolling it and creating a new one");
  834. [weakSelf lt_rollLogFileNow];
  835. } });
  836. #if !OS_OBJECT_USE_OBJC
  837. dispatch_source_t vnode = _currentLogFileVnode;
  838. dispatch_source_set_cancel_handler(_currentLogFileVnode, ^{
  839. dispatch_release(vnode);
  840. });
  841. #endif
  842. dispatch_resume(_currentLogFileVnode);
  843. }
  844. - (NSFileHandle *)lt_currentLogFileHandle {
  845. NSAssert([self isOnInternalLoggerQueue], @"lt_ methods should be on logger queue.");
  846. if (!_currentLogFileHandle) {
  847. NSString *logFilePath = [[self lt_currentLogFileInfo] filePath];
  848. _currentLogFileHandle = [NSFileHandle fileHandleForWritingAtPath:logFilePath];
  849. [_currentLogFileHandle seekToEndOfFile];
  850. if (_currentLogFileHandle) {
  851. [self lt_scheduleTimerToRollLogFileDueToAge];
  852. [self lt_monitorCurrentLogFileForExternalChanges];
  853. }
  854. }
  855. return _currentLogFileHandle;
  856. }
  857. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  858. #pragma mark DDLogger Protocol
  859. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  860. static int exception_count = 0;
  861. - (void)logMessage:(DDLogMessage *)logMessage {
  862. NSAssert([self isOnInternalLoggerQueue], @"logMessage should only be executed on internal queue.");
  863. NSString *message = logMessage->_message;
  864. BOOL isFormatted = NO;
  865. if (_logFormatter != nil) {
  866. message = [_logFormatter formatLogMessage:logMessage];
  867. isFormatted = message != logMessage->_message;
  868. }
  869. if (message.length == 0) {
  870. return;
  871. }
  872. BOOL shouldFormat = !isFormatted || _automaticallyAppendNewlineForCustomFormatters;
  873. if (shouldFormat && ![message hasSuffix:@"\n"]) {
  874. message = [message stringByAppendingString:@"\n"];
  875. }
  876. [self lt_logData:[message dataUsingEncoding:NSUTF8StringEncoding]];
  877. }
  878. - (void)willLogMessage {
  879. }
  880. - (void)didLogMessage {
  881. [self lt_maybeRollLogFileDueToSize];
  882. }
  883. - (BOOL)shouldArchiveRecentLogFileInfo:(__unused DDLogFileInfo *)recentLogFileInfo {
  884. return NO;
  885. }
  886. - (void)willRemoveLogger {
  887. [self lt_rollLogFileNow];
  888. }
  889. - (void)flush {
  890. // This method is public.
  891. // We need to execute the rolling on our logging thread/queue.
  892. dispatch_block_t block = ^{
  893. @autoreleasepool {
  894. [self lt_flush];
  895. }
  896. };
  897. // The design of this method is taken from the DDAbstractLogger implementation.
  898. // For extensive documentation please refer to the DDAbstractLogger implementation.
  899. if ([self isOnInternalLoggerQueue]) {
  900. block();
  901. } else {
  902. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  903. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  904. dispatch_sync(globalLoggingQueue, ^{
  905. dispatch_sync(self.loggerQueue, block);
  906. });
  907. }
  908. }
  909. - (void)lt_flush {
  910. NSAssert([self isOnInternalLoggerQueue], @"flush should only be executed on internal queue.");
  911. [_currentLogFileHandle synchronizeFile];
  912. }
  913. - (DDLoggerName)loggerName {
  914. return DDLoggerNameFile;
  915. }
  916. @end
  917. @implementation DDFileLogger (Internal)
  918. - (void)logData:(NSData *)data {
  919. // This method is public.
  920. // We need to execute the rolling on our logging thread/queue.
  921. dispatch_block_t block = ^{
  922. @autoreleasepool {
  923. [self lt_logData:data];
  924. }
  925. };
  926. // The design of this method is taken from the DDAbstractLogger implementation.
  927. // For extensive documentation please refer to the DDAbstractLogger implementation.
  928. if ([self isOnInternalLoggerQueue]) {
  929. block();
  930. } else {
  931. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  932. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  933. dispatch_sync(globalLoggingQueue, ^{
  934. dispatch_sync(self.loggerQueue, block);
  935. });
  936. }
  937. }
  938. - (void)lt_logData:(NSData *)data {
  939. NSAssert([self isOnInternalLoggerQueue], @"logMessage should only be executed on internal queue.");
  940. if (data.length == 0) {
  941. return;
  942. }
  943. @try {
  944. [self willLogMessage];
  945. NSFileHandle *handle = [self lt_currentLogFileHandle];
  946. [handle seekToEndOfFile];
  947. [handle writeData:data];
  948. [self didLogMessage];
  949. } @catch (NSException *exception) {
  950. exception_count++;
  951. if (exception_count <= 10) {
  952. NSLogError(@"DDFileLogger.logMessage: %@", exception);
  953. if (exception_count == 10) {
  954. NSLogError(@"DDFileLogger.logMessage: Too many exceptions -- will not log any more of them.");
  955. }
  956. }
  957. }
  958. }
  959. - (NSData *)lt_dataForMessage:(DDLogMessage *)logMessage {
  960. NSAssert([self isOnInternalLoggerQueue], @"logMessage should only be executed on internal queue.");
  961. NSString *message = logMessage->_message;
  962. BOOL isFormatted = NO;
  963. if (_logFormatter != nil) {
  964. message = [_logFormatter formatLogMessage:logMessage];
  965. isFormatted = message != logMessage->_message;
  966. }
  967. if (message.length == 0) {
  968. return [NSData new];
  969. }
  970. BOOL shouldFormat = !isFormatted || _automaticallyAppendNewlineForCustomFormatters;
  971. if (shouldFormat && ![message hasSuffix:@"\n"]) {
  972. message = [message stringByAppendingString:@"\n"];
  973. }
  974. return [message dataUsingEncoding:NSUTF8StringEncoding];
  975. }
  976. @end
  977. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  978. #pragma mark -
  979. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  980. #if TARGET_IPHONE_SIMULATOR
  981. static NSString * const kDDXAttrArchivedName = @"archived";
  982. #else
  983. static NSString * const kDDXAttrArchivedName = @"lumberjack.log.archived";
  984. #endif
  985. @interface DDLogFileInfo () {
  986. __strong NSString *_filePath;
  987. __strong NSString *_fileName;
  988. __strong NSDictionary *_fileAttributes;
  989. __strong NSDate *_creationDate;
  990. __strong NSDate *_modificationDate;
  991. unsigned long long _fileSize;
  992. }
  993. @end
  994. @implementation DDLogFileInfo
  995. @synthesize filePath;
  996. @dynamic fileName;
  997. @dynamic fileAttributes;
  998. @dynamic creationDate;
  999. @dynamic modificationDate;
  1000. @dynamic fileSize;
  1001. @dynamic age;
  1002. @dynamic isArchived;
  1003. #pragma mark Lifecycle
  1004. + (instancetype)logFileWithPath:(NSString *)aFilePath {
  1005. return [[self alloc] initWithFilePath:aFilePath];
  1006. }
  1007. - (instancetype)initWithFilePath:(NSString *)aFilePath {
  1008. if ((self = [super init])) {
  1009. filePath = [aFilePath copy];
  1010. }
  1011. return self;
  1012. }
  1013. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1014. #pragma mark Standard Info
  1015. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1016. - (NSDictionary *)fileAttributes {
  1017. if (_fileAttributes == nil && filePath != nil) {
  1018. NSError *error = nil;
  1019. _fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error];
  1020. if (error) {
  1021. NSLogError(@"DDLogFileInfo: Failed to read file attributes: %@", error);
  1022. }
  1023. }
  1024. return _fileAttributes ?: @{};
  1025. }
  1026. - (NSString *)fileName {
  1027. if (_fileName == nil) {
  1028. _fileName = [filePath lastPathComponent];
  1029. }
  1030. return _fileName;
  1031. }
  1032. - (NSDate *)modificationDate {
  1033. if (_modificationDate == nil) {
  1034. _modificationDate = self.fileAttributes[NSFileModificationDate];
  1035. }
  1036. return _modificationDate;
  1037. }
  1038. - (NSDate *)creationDate {
  1039. if (_creationDate == nil) {
  1040. _creationDate = self.fileAttributes[NSFileCreationDate];
  1041. }
  1042. return _creationDate;
  1043. }
  1044. - (unsigned long long)fileSize {
  1045. if (_fileSize == 0) {
  1046. _fileSize = [self.fileAttributes[NSFileSize] unsignedLongLongValue];
  1047. }
  1048. return _fileSize;
  1049. }
  1050. - (NSTimeInterval)age {
  1051. return -[[self creationDate] timeIntervalSinceNow];
  1052. }
  1053. - (NSString *)description {
  1054. return [@{ @"filePath": self.filePath ? : @"",
  1055. @"fileName": self.fileName ? : @"",
  1056. @"fileAttributes": self.fileAttributes ? : @"",
  1057. @"creationDate": self.creationDate ? : @"",
  1058. @"modificationDate": self.modificationDate ? : @"",
  1059. @"fileSize": @(self.fileSize),
  1060. @"age": @(self.age),
  1061. @"isArchived": @(self.isArchived) } description];
  1062. }
  1063. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1064. #pragma mark Archiving
  1065. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1066. - (BOOL)isArchived {
  1067. #if TARGET_IPHONE_SIMULATOR
  1068. // Extended attributes don't work properly on the simulator.
  1069. // So we have to use a less attractive alternative.
  1070. // See full explanation in the header file.
  1071. return [self hasExtensionAttributeWithName:kDDXAttrArchivedName];
  1072. #else
  1073. return [self hasExtendedAttributeWithName:kDDXAttrArchivedName];
  1074. #endif
  1075. }
  1076. - (void)setIsArchived:(BOOL)flag {
  1077. #if TARGET_IPHONE_SIMULATOR
  1078. // Extended attributes don't work properly on the simulator.
  1079. // So we have to use a less attractive alternative.
  1080. // See full explanation in the header file.
  1081. if (flag) {
  1082. [self addExtensionAttributeWithName:kDDXAttrArchivedName];
  1083. } else {
  1084. [self removeExtensionAttributeWithName:kDDXAttrArchivedName];
  1085. }
  1086. #else
  1087. if (flag) {
  1088. [self addExtendedAttributeWithName:kDDXAttrArchivedName];
  1089. } else {
  1090. [self removeExtendedAttributeWithName:kDDXAttrArchivedName];
  1091. }
  1092. #endif
  1093. }
  1094. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1095. #pragma mark Changes
  1096. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1097. - (void)reset {
  1098. _fileName = nil;
  1099. _fileAttributes = nil;
  1100. _creationDate = nil;
  1101. _modificationDate = nil;
  1102. }
  1103. - (void)renameFile:(NSString *)newFileName {
  1104. // This method is only used on the iPhone simulator, where normal extended attributes are broken.
  1105. // See full explanation in the header file.
  1106. if (![newFileName isEqualToString:[self fileName]]) {
  1107. NSString *fileDir = [filePath stringByDeletingLastPathComponent];
  1108. NSString *newFilePath = [fileDir stringByAppendingPathComponent:newFileName];
  1109. #ifdef DEBUG
  1110. BOOL directory = NO;
  1111. [[NSFileManager defaultManager] fileExistsAtPath:fileDir isDirectory:&directory];
  1112. NSAssert(directory, @"Containing directory must exist.");
  1113. #endif
  1114. NSError *error = nil;
  1115. BOOL success = [[NSFileManager defaultManager] removeItemAtPath:newFilePath error:&error];
  1116. if (!success && error.code != NSFileNoSuchFileError) {
  1117. NSLogError(@"DDLogFileInfo: Error deleting archive (%@): %@", self.fileName, error);
  1118. }
  1119. success = [[NSFileManager defaultManager] moveItemAtPath:filePath toPath:newFilePath error:&error];
  1120. // When a log file is deleted, moved or renamed on the simulator, we attempt to rename it as a
  1121. // result of "archiving" it, but since the file doesn't exist anymore, needless error logs are printed
  1122. // We therefore ignore this error, and assert that the directory we are copying into exists (which
  1123. // is the only other case where this error code can come up).
  1124. #if TARGET_IPHONE_SIMULATOR
  1125. if (!success && error.code != NSFileNoSuchFileError) {
  1126. #else
  1127. if (!success) {
  1128. #endif
  1129. NSLogError(@"DDLogFileInfo: Error renaming file (%@): %@", self.fileName, error);
  1130. }
  1131. filePath = newFilePath;
  1132. [self reset];
  1133. }
  1134. }
  1135. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1136. #pragma mark Attribute Management
  1137. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1138. #if TARGET_IPHONE_SIMULATOR
  1139. // Extended attributes don't work properly on the simulator.
  1140. // So we have to use a less attractive alternative.
  1141. // See full explanation in the header file.
  1142. - (BOOL)hasExtensionAttributeWithName:(NSString *)attrName {
  1143. // This method is only used on the iPhone simulator, where normal extended attributes are broken.
  1144. // See full explanation in the header file.
  1145. // Split the file name into components. File name may have various format, but generally
  1146. // structure is same:
  1147. //
  1148. // <name part>.<extension part> and <name part>.archived.<extension part>
  1149. // or
  1150. // <name part> and <name part>.archived
  1151. //
  1152. // So we want to search for the attrName in the components (ignoring the first array index).
  1153. NSArray *components = [[self fileName] componentsSeparatedByString:@"."];
  1154. // Watch out for file names without an extension
  1155. for (NSUInteger i = 1; i < components.count; i++) {
  1156. NSString *attr = components[i];
  1157. if ([attrName isEqualToString:attr]) {
  1158. return YES;
  1159. }
  1160. }
  1161. return NO;
  1162. }
  1163. - (void)addExtensionAttributeWithName:(NSString *)attrName {
  1164. // This method is only used on the iPhone simulator, where normal extended attributes are broken.
  1165. // See full explanation in the header file.
  1166. if ([attrName length] == 0) {
  1167. return;
  1168. }
  1169. // Example:
  1170. // attrName = "archived"
  1171. //
  1172. // "mylog.txt" -> "mylog.archived.txt"
  1173. // "mylog" -> "mylog.archived"
  1174. NSArray *components = [[self fileName] componentsSeparatedByString:@"."];
  1175. NSUInteger count = [components count];
  1176. NSUInteger estimatedNewLength = [[self fileName] length] + [attrName length] + 1;
  1177. NSMutableString *newFileName = [NSMutableString stringWithCapacity:estimatedNewLength];
  1178. if (count > 0) {
  1179. [newFileName appendString:components.firstObject];
  1180. }
  1181. NSString *lastExt = @"";
  1182. NSUInteger i;
  1183. for (i = 1; i < count; i++) {
  1184. NSString *attr = components[i];
  1185. if ([attr length] == 0) {
  1186. continue;
  1187. }
  1188. if ([attrName isEqualToString:attr]) {
  1189. // Extension attribute already exists in file name
  1190. return;
  1191. }
  1192. if ([lastExt length] > 0) {
  1193. [newFileName appendFormat:@".%@", lastExt];
  1194. }
  1195. lastExt = attr;
  1196. }
  1197. [newFileName appendFormat:@".%@", attrName];
  1198. if ([lastExt length] > 0) {
  1199. [newFileName appendFormat:@".%@", lastExt];
  1200. }
  1201. [self renameFile:newFileName];
  1202. }
  1203. - (void)removeExtensionAttributeWithName:(NSString *)attrName {
  1204. // This method is only used on the iPhone simulator, where normal extended attributes are broken.
  1205. // See full explanation in the header file.
  1206. if ([attrName length] == 0) {
  1207. return;
  1208. }
  1209. // Example:
  1210. // attrName = "archived"
  1211. //
  1212. // "mylog.archived.txt" -> "mylog.txt"
  1213. // "mylog.archived" -> "mylog"
  1214. NSArray *components = [[self fileName] componentsSeparatedByString:@"."];
  1215. NSUInteger count = [components count];
  1216. NSUInteger estimatedNewLength = [[self fileName] length];
  1217. NSMutableString *newFileName = [NSMutableString stringWithCapacity:estimatedNewLength];
  1218. if (count > 0) {
  1219. [newFileName appendString:components.firstObject];
  1220. }
  1221. BOOL found = NO;
  1222. NSUInteger i;
  1223. for (i = 1; i < count; i++) {
  1224. NSString *attr = components[i];
  1225. if ([attrName isEqualToString:attr]) {
  1226. found = YES;
  1227. } else {
  1228. [newFileName appendFormat:@".%@", attr];
  1229. }
  1230. }
  1231. if (found) {
  1232. [self renameFile:newFileName];
  1233. }
  1234. }
  1235. #else /* if TARGET_IPHONE_SIMULATOR */
  1236. - (BOOL)hasExtendedAttributeWithName:(NSString *)attrName {
  1237. const char *path = [filePath UTF8String];
  1238. const char *name = [attrName UTF8String];
  1239. ssize_t result = getxattr(path, name, NULL, 0, 0, 0);
  1240. return (result >= 0);
  1241. }
  1242. - (void)addExtendedAttributeWithName:(NSString *)attrName {
  1243. const char *path = [filePath UTF8String];
  1244. const char *name = [attrName UTF8String];
  1245. int result = setxattr(path, name, NULL, 0, 0, 0);
  1246. if (result < 0) {
  1247. NSLogError(@"DDLogFileInfo: setxattr(%@, %@): error = %s",
  1248. attrName,
  1249. filePath,
  1250. strerror(errno));
  1251. }
  1252. }
  1253. - (void)removeExtendedAttributeWithName:(NSString *)attrName {
  1254. const char *path = [filePath UTF8String];
  1255. const char *name = [attrName UTF8String];
  1256. int result = removexattr(path, name, 0);
  1257. if (result < 0 && errno != ENOATTR) {
  1258. NSLogError(@"DDLogFileInfo: removexattr(%@, %@): error = %s",
  1259. attrName,
  1260. self.fileName,
  1261. strerror(errno));
  1262. }
  1263. }
  1264. #endif /* if TARGET_IPHONE_SIMULATOR */
  1265. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1266. #pragma mark Comparisons
  1267. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1268. - (BOOL)isEqual:(id)object {
  1269. if ([object isKindOfClass:[self class]]) {
  1270. DDLogFileInfo *another = (DDLogFileInfo *)object;
  1271. return [filePath isEqualToString:[another filePath]];
  1272. }
  1273. return NO;
  1274. }
  1275. - (NSUInteger)hash {
  1276. return [filePath hash];
  1277. }
  1278. - (NSComparisonResult)reverseCompareByCreationDate:(DDLogFileInfo *)another {
  1279. __auto_type us = [self creationDate];
  1280. __auto_type them = [another creationDate];
  1281. return [them compare:us];
  1282. }
  1283. - (NSComparisonResult)reverseCompareByModificationDate:(DDLogFileInfo *)another {
  1284. __auto_type us = [self modificationDate];
  1285. __auto_type them = [another modificationDate];
  1286. return [them compare:us];
  1287. }
  1288. @end
  1289. #if TARGET_OS_IPHONE
  1290. /**
  1291. * When creating log file on iOS we're setting NSFileProtectionKey attribute to NSFileProtectionCompleteUnlessOpen.
  1292. *
  1293. * But in case if app is able to launch from background we need to have an ability to open log file any time we
  1294. * want (even if device is locked). Thats why that attribute have to be changed to
  1295. * NSFileProtectionCompleteUntilFirstUserAuthentication.
  1296. */
  1297. BOOL doesAppRunInBackground() {
  1298. BOOL answer = NO;
  1299. NSArray *backgroundModes = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIBackgroundModes"];
  1300. for (NSString *mode in backgroundModes) {
  1301. if (mode.length > 0) {
  1302. answer = YES;
  1303. break;
  1304. }
  1305. }
  1306. return answer;
  1307. }
  1308. #endif