DDFileLogger.m 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696
  1. // Software License Agreement (BSD License)
  2. //
  3. // Copyright (c) 2010-2018, 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. BOOL isResuming = _currentLogFileInfo == nil;
  783. if (isResuming) {
  784. NSArray *sortedLogFileInfos = [_logFileManager sortedLogFileInfos];
  785. _currentLogFileInfo = sortedLogFileInfos.firstObject;
  786. }
  787. if (_currentLogFileInfo) {
  788. BOOL isMostRecentLogArchived = _currentLogFileInfo.isArchived;
  789. BOOL forceArchive = _doNotReuseLogFiles && isMostRecentLogArchived == NO;
  790. if (forceArchive || [self lt_shouldLogFileBeArchived:_currentLogFileInfo]) {
  791. _currentLogFileInfo.isArchived = YES;
  792. NSString *archivedLogFilePath = [_currentLogFileInfo.fileName copy];
  793. _currentLogFileInfo = nil;
  794. if ([_logFileManager respondsToSelector:@selector(didArchiveLogFile:)]) {
  795. dispatch_async(_completionQueue, ^{
  796. [self->_logFileManager didArchiveLogFile:archivedLogFilePath];
  797. });
  798. }
  799. }
  800. }
  801. if (isResuming && _currentLogFileInfo) {
  802. NSLogVerbose(@"DDFileLogger: Resuming logging with file %@", _currentLogFileInfo.fileName);
  803. }
  804. if (!_currentLogFileInfo) {
  805. NSString *currentLogFilePath = [_logFileManager createNewLogFile];
  806. _currentLogFileInfo = [[DDLogFileInfo alloc] initWithFilePath:currentLogFilePath];
  807. }
  808. return _currentLogFileInfo;
  809. }
  810. - (void)lt_monitorCurrentLogFileForExternalChanges {
  811. NSAssert([self isOnInternalLoggerQueue], @"lt_ methods should be on logger queue.");
  812. NSAssert(_currentLogFileHandle, @"Can not monitor without handle.");
  813. dispatch_source_vnode_flags_t flags = DISPATCH_VNODE_DELETE | DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE;
  814. _currentLogFileVnode = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE,
  815. (uintptr_t)[_currentLogFileHandle fileDescriptor],
  816. flags,
  817. _loggerQueue);
  818. __weak __auto_type weakSelf = self;
  819. dispatch_source_set_event_handler(_currentLogFileVnode, ^{ @autoreleasepool {
  820. NSLogInfo(@"DDFileLogger: Current logfile was moved. Rolling it and creating a new one");
  821. [weakSelf lt_rollLogFileNow];
  822. } });
  823. #if !OS_OBJECT_USE_OBJC
  824. dispatch_source_t vnode = _currentLogFileVnode;
  825. dispatch_source_set_cancel_handler(_currentLogFileVnode, ^{
  826. dispatch_release(vnode);
  827. });
  828. #endif
  829. dispatch_resume(_currentLogFileVnode);
  830. }
  831. - (NSFileHandle *)lt_currentLogFileHandle {
  832. NSAssert([self isOnInternalLoggerQueue], @"lt_ methods should be on logger queue.");
  833. if (!_currentLogFileHandle) {
  834. NSString *logFilePath = [[self lt_currentLogFileInfo] filePath];
  835. _currentLogFileHandle = [NSFileHandle fileHandleForWritingAtPath:logFilePath];
  836. [_currentLogFileHandle seekToEndOfFile];
  837. if (_currentLogFileHandle) {
  838. [self lt_scheduleTimerToRollLogFileDueToAge];
  839. [self lt_monitorCurrentLogFileForExternalChanges];
  840. }
  841. }
  842. return _currentLogFileHandle;
  843. }
  844. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  845. #pragma mark DDLogger Protocol
  846. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  847. static int exception_count = 0;
  848. - (void)logMessage:(DDLogMessage *)logMessage {
  849. NSAssert([self isOnInternalLoggerQueue], @"logMessage should only be executed on internal queue.");
  850. NSString *message = logMessage->_message;
  851. BOOL isFormatted = NO;
  852. if (_logFormatter != nil) {
  853. message = [_logFormatter formatLogMessage:logMessage];
  854. isFormatted = message != logMessage->_message;
  855. }
  856. if (message.length == 0) {
  857. return;
  858. }
  859. BOOL shouldFormat = !isFormatted || _automaticallyAppendNewlineForCustomFormatters;
  860. if (shouldFormat && ![message hasSuffix:@"\n"]) {
  861. message = [message stringByAppendingString:@"\n"];
  862. }
  863. [self lt_logData:[message dataUsingEncoding:NSUTF8StringEncoding]];
  864. }
  865. - (void)willLogMessage {
  866. }
  867. - (void)didLogMessage {
  868. [self lt_maybeRollLogFileDueToSize];
  869. }
  870. - (BOOL)shouldArchiveRecentLogFileInfo:(__unused DDLogFileInfo *)recentLogFileInfo {
  871. return NO;
  872. }
  873. - (void)willRemoveLogger {
  874. [self lt_rollLogFileNow];
  875. }
  876. - (void)flush {
  877. // This method is public.
  878. // We need to execute the rolling on our logging thread/queue.
  879. dispatch_block_t block = ^{
  880. @autoreleasepool {
  881. [self lt_flush];
  882. }
  883. };
  884. // The design of this method is taken from the DDAbstractLogger implementation.
  885. // For extensive documentation please refer to the DDAbstractLogger implementation.
  886. if ([self isOnInternalLoggerQueue]) {
  887. block();
  888. } else {
  889. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  890. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  891. dispatch_sync(globalLoggingQueue, ^{
  892. dispatch_sync(self.loggerQueue, block);
  893. });
  894. }
  895. }
  896. - (void)lt_flush {
  897. NSAssert([self isOnInternalLoggerQueue], @"flush should only be executed on internal queue.");
  898. [_currentLogFileHandle synchronizeFile];
  899. }
  900. - (DDLoggerName)loggerName {
  901. return DDLoggerNameFile;
  902. }
  903. @end
  904. @implementation DDFileLogger (Internal)
  905. - (void)logData:(NSData *)data {
  906. // This method is public.
  907. // We need to execute the rolling on our logging thread/queue.
  908. dispatch_block_t block = ^{
  909. @autoreleasepool {
  910. [self lt_logData:data];
  911. }
  912. };
  913. // The design of this method is taken from the DDAbstractLogger implementation.
  914. // For extensive documentation please refer to the DDAbstractLogger implementation.
  915. if ([self isOnInternalLoggerQueue]) {
  916. block();
  917. } else {
  918. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  919. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  920. dispatch_sync(globalLoggingQueue, ^{
  921. dispatch_sync(self.loggerQueue, block);
  922. });
  923. }
  924. }
  925. - (void)lt_logData:(NSData *)data {
  926. NSAssert([self isOnInternalLoggerQueue], @"logMessage should only be executed on internal queue.");
  927. if (data.length == 0) {
  928. return;
  929. }
  930. @try {
  931. [self willLogMessage];
  932. NSFileHandle *handle = [self lt_currentLogFileHandle];
  933. [handle seekToEndOfFile];
  934. [handle writeData:data];
  935. [self didLogMessage];
  936. } @catch (NSException *exception) {
  937. exception_count++;
  938. if (exception_count <= 10) {
  939. NSLogError(@"DDFileLogger.logMessage: %@", exception);
  940. if (exception_count == 10) {
  941. NSLogError(@"DDFileLogger.logMessage: Too many exceptions -- will not log any more of them.");
  942. }
  943. }
  944. }
  945. }
  946. - (NSData *)lt_dataForMessage:(DDLogMessage *)logMessage {
  947. NSAssert([self isOnInternalLoggerQueue], @"logMessage should only be executed on internal queue.");
  948. NSString *message = logMessage->_message;
  949. BOOL isFormatted = NO;
  950. if (_logFormatter != nil) {
  951. message = [_logFormatter formatLogMessage:logMessage];
  952. isFormatted = message != logMessage->_message;
  953. }
  954. if (message.length == 0) {
  955. return [NSData new];
  956. }
  957. BOOL shouldFormat = !isFormatted || _automaticallyAppendNewlineForCustomFormatters;
  958. if (shouldFormat && ![message hasSuffix:@"\n"]) {
  959. message = [message stringByAppendingString:@"\n"];
  960. }
  961. return [message dataUsingEncoding:NSUTF8StringEncoding];
  962. }
  963. @end
  964. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  965. #pragma mark -
  966. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  967. #if TARGET_IPHONE_SIMULATOR
  968. static NSString * const kDDXAttrArchivedName = @"archived";
  969. #else
  970. static NSString * const kDDXAttrArchivedName = @"lumberjack.log.archived";
  971. #endif
  972. @interface DDLogFileInfo () {
  973. __strong NSString *_filePath;
  974. __strong NSString *_fileName;
  975. __strong NSDictionary *_fileAttributes;
  976. __strong NSDate *_creationDate;
  977. __strong NSDate *_modificationDate;
  978. unsigned long long _fileSize;
  979. }
  980. @end
  981. @implementation DDLogFileInfo
  982. @synthesize filePath;
  983. @dynamic fileName;
  984. @dynamic fileAttributes;
  985. @dynamic creationDate;
  986. @dynamic modificationDate;
  987. @dynamic fileSize;
  988. @dynamic age;
  989. @dynamic isArchived;
  990. #pragma mark Lifecycle
  991. + (instancetype)logFileWithPath:(NSString *)aFilePath {
  992. return [[self alloc] initWithFilePath:aFilePath];
  993. }
  994. - (instancetype)initWithFilePath:(NSString *)aFilePath {
  995. if ((self = [super init])) {
  996. filePath = [aFilePath copy];
  997. }
  998. return self;
  999. }
  1000. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1001. #pragma mark Standard Info
  1002. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1003. - (NSDictionary *)fileAttributes {
  1004. if (_fileAttributes == nil && filePath != nil) {
  1005. NSError *error = nil;
  1006. _fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error];
  1007. if (error) {
  1008. NSLogError(@"DDLogFileInfo: Failed to read file attributes: %@", error);
  1009. }
  1010. }
  1011. return _fileAttributes ?: @{};
  1012. }
  1013. - (NSString *)fileName {
  1014. if (_fileName == nil) {
  1015. _fileName = [filePath lastPathComponent];
  1016. }
  1017. return _fileName;
  1018. }
  1019. - (NSDate *)modificationDate {
  1020. if (_modificationDate == nil) {
  1021. _modificationDate = self.fileAttributes[NSFileModificationDate];
  1022. }
  1023. return _modificationDate;
  1024. }
  1025. - (NSDate *)creationDate {
  1026. if (_creationDate == nil) {
  1027. _creationDate = self.fileAttributes[NSFileCreationDate];
  1028. }
  1029. return _creationDate;
  1030. }
  1031. - (unsigned long long)fileSize {
  1032. if (_fileSize == 0) {
  1033. _fileSize = [self.fileAttributes[NSFileSize] unsignedLongLongValue];
  1034. }
  1035. return _fileSize;
  1036. }
  1037. - (NSTimeInterval)age {
  1038. return -[[self creationDate] timeIntervalSinceNow];
  1039. }
  1040. - (NSString *)description {
  1041. return [@{ @"filePath": self.filePath ? : @"",
  1042. @"fileName": self.fileName ? : @"",
  1043. @"fileAttributes": self.fileAttributes ? : @"",
  1044. @"creationDate": self.creationDate ? : @"",
  1045. @"modificationDate": self.modificationDate ? : @"",
  1046. @"fileSize": @(self.fileSize),
  1047. @"age": @(self.age),
  1048. @"isArchived": @(self.isArchived) } description];
  1049. }
  1050. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1051. #pragma mark Archiving
  1052. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1053. - (BOOL)isArchived {
  1054. #if TARGET_IPHONE_SIMULATOR
  1055. // Extended attributes don't work properly on the simulator.
  1056. // So we have to use a less attractive alternative.
  1057. // See full explanation in the header file.
  1058. return [self hasExtensionAttributeWithName:kDDXAttrArchivedName];
  1059. #else
  1060. return [self hasExtendedAttributeWithName:kDDXAttrArchivedName];
  1061. #endif
  1062. }
  1063. - (void)setIsArchived:(BOOL)flag {
  1064. #if TARGET_IPHONE_SIMULATOR
  1065. // Extended attributes don't work properly on the simulator.
  1066. // So we have to use a less attractive alternative.
  1067. // See full explanation in the header file.
  1068. if (flag) {
  1069. [self addExtensionAttributeWithName:kDDXAttrArchivedName];
  1070. } else {
  1071. [self removeExtensionAttributeWithName:kDDXAttrArchivedName];
  1072. }
  1073. #else
  1074. if (flag) {
  1075. [self addExtendedAttributeWithName:kDDXAttrArchivedName];
  1076. } else {
  1077. [self removeExtendedAttributeWithName:kDDXAttrArchivedName];
  1078. }
  1079. #endif
  1080. }
  1081. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1082. #pragma mark Changes
  1083. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1084. - (void)reset {
  1085. _fileName = nil;
  1086. _fileAttributes = nil;
  1087. _creationDate = nil;
  1088. _modificationDate = nil;
  1089. }
  1090. - (void)renameFile:(NSString *)newFileName {
  1091. // This method is only used on the iPhone simulator, where normal extended attributes are broken.
  1092. // See full explanation in the header file.
  1093. if (![newFileName isEqualToString:[self fileName]]) {
  1094. NSString *fileDir = [filePath stringByDeletingLastPathComponent];
  1095. NSString *newFilePath = [fileDir stringByAppendingPathComponent:newFileName];
  1096. #ifdef DEBUG
  1097. BOOL directory = NO;
  1098. [[NSFileManager defaultManager] fileExistsAtPath:fileDir isDirectory:&directory];
  1099. NSAssert(directory, @"Containing directory must exist.");
  1100. #endif
  1101. NSError *error = nil;
  1102. BOOL success = [[NSFileManager defaultManager] removeItemAtPath:newFilePath error:&error];
  1103. if (!success && error.code != NSFileNoSuchFileError) {
  1104. NSLogError(@"DDLogFileInfo: Error deleting archive (%@): %@", self.fileName, error);
  1105. }
  1106. success = [[NSFileManager defaultManager] moveItemAtPath:filePath toPath:newFilePath error:&error];
  1107. // When a log file is deleted, moved or renamed on the simulator, we attempt to rename it as a
  1108. // result of "archiving" it, but since the file doesn't exist anymore, needless error logs are printed
  1109. // We therefore ignore this error, and assert that the directory we are copying into exists (which
  1110. // is the only other case where this error code can come up).
  1111. #if TARGET_IPHONE_SIMULATOR
  1112. if (!success && error.code != NSFileNoSuchFileError) {
  1113. #else
  1114. if (!success) {
  1115. #endif
  1116. NSLogError(@"DDLogFileInfo: Error renaming file (%@): %@", self.fileName, error);
  1117. }
  1118. filePath = newFilePath;
  1119. [self reset];
  1120. }
  1121. }
  1122. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1123. #pragma mark Attribute Management
  1124. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1125. #if TARGET_IPHONE_SIMULATOR
  1126. // Extended attributes don't work properly on the simulator.
  1127. // So we have to use a less attractive alternative.
  1128. // See full explanation in the header file.
  1129. - (BOOL)hasExtensionAttributeWithName:(NSString *)attrName {
  1130. // This method is only used on the iPhone simulator, where normal extended attributes are broken.
  1131. // See full explanation in the header file.
  1132. // Split the file name into components. File name may have various format, but generally
  1133. // structure is same:
  1134. //
  1135. // <name part>.<extension part> and <name part>.archived.<extension part>
  1136. // or
  1137. // <name part> and <name part>.archived
  1138. //
  1139. // So we want to search for the attrName in the components (ignoring the first array index).
  1140. NSArray *components = [[self fileName] componentsSeparatedByString:@"."];
  1141. // Watch out for file names without an extension
  1142. for (NSUInteger i = 1; i < components.count; i++) {
  1143. NSString *attr = components[i];
  1144. if ([attrName isEqualToString:attr]) {
  1145. return YES;
  1146. }
  1147. }
  1148. return NO;
  1149. }
  1150. - (void)addExtensionAttributeWithName:(NSString *)attrName {
  1151. // This method is only used on the iPhone simulator, where normal extended attributes are broken.
  1152. // See full explanation in the header file.
  1153. if ([attrName length] == 0) {
  1154. return;
  1155. }
  1156. // Example:
  1157. // attrName = "archived"
  1158. //
  1159. // "mylog.txt" -> "mylog.archived.txt"
  1160. // "mylog" -> "mylog.archived"
  1161. NSArray *components = [[self fileName] componentsSeparatedByString:@"."];
  1162. NSUInteger count = [components count];
  1163. NSUInteger estimatedNewLength = [[self fileName] length] + [attrName length] + 1;
  1164. NSMutableString *newFileName = [NSMutableString stringWithCapacity:estimatedNewLength];
  1165. if (count > 0) {
  1166. [newFileName appendString:components.firstObject];
  1167. }
  1168. NSString *lastExt = @"";
  1169. NSUInteger i;
  1170. for (i = 1; i < count; i++) {
  1171. NSString *attr = components[i];
  1172. if ([attr length] == 0) {
  1173. continue;
  1174. }
  1175. if ([attrName isEqualToString:attr]) {
  1176. // Extension attribute already exists in file name
  1177. return;
  1178. }
  1179. if ([lastExt length] > 0) {
  1180. [newFileName appendFormat:@".%@", lastExt];
  1181. }
  1182. lastExt = attr;
  1183. }
  1184. [newFileName appendFormat:@".%@", attrName];
  1185. if ([lastExt length] > 0) {
  1186. [newFileName appendFormat:@".%@", lastExt];
  1187. }
  1188. [self renameFile:newFileName];
  1189. }
  1190. - (void)removeExtensionAttributeWithName:(NSString *)attrName {
  1191. // This method is only used on the iPhone simulator, where normal extended attributes are broken.
  1192. // See full explanation in the header file.
  1193. if ([attrName length] == 0) {
  1194. return;
  1195. }
  1196. // Example:
  1197. // attrName = "archived"
  1198. //
  1199. // "mylog.archived.txt" -> "mylog.txt"
  1200. // "mylog.archived" -> "mylog"
  1201. NSArray *components = [[self fileName] componentsSeparatedByString:@"."];
  1202. NSUInteger count = [components count];
  1203. NSUInteger estimatedNewLength = [[self fileName] length];
  1204. NSMutableString *newFileName = [NSMutableString stringWithCapacity:estimatedNewLength];
  1205. if (count > 0) {
  1206. [newFileName appendString:components.firstObject];
  1207. }
  1208. BOOL found = NO;
  1209. NSUInteger i;
  1210. for (i = 1; i < count; i++) {
  1211. NSString *attr = components[i];
  1212. if ([attrName isEqualToString:attr]) {
  1213. found = YES;
  1214. } else {
  1215. [newFileName appendFormat:@".%@", attr];
  1216. }
  1217. }
  1218. if (found) {
  1219. [self renameFile:newFileName];
  1220. }
  1221. }
  1222. #else /* if TARGET_IPHONE_SIMULATOR */
  1223. - (BOOL)hasExtendedAttributeWithName:(NSString *)attrName {
  1224. const char *path = [filePath UTF8String];
  1225. const char *name = [attrName UTF8String];
  1226. ssize_t result = getxattr(path, name, NULL, 0, 0, 0);
  1227. return (result >= 0);
  1228. }
  1229. - (void)addExtendedAttributeWithName:(NSString *)attrName {
  1230. const char *path = [filePath UTF8String];
  1231. const char *name = [attrName UTF8String];
  1232. int result = setxattr(path, name, NULL, 0, 0, 0);
  1233. if (result < 0) {
  1234. NSLogError(@"DDLogFileInfo: setxattr(%@, %@): error = %s",
  1235. attrName,
  1236. filePath,
  1237. strerror(errno));
  1238. }
  1239. }
  1240. - (void)removeExtendedAttributeWithName:(NSString *)attrName {
  1241. const char *path = [filePath UTF8String];
  1242. const char *name = [attrName UTF8String];
  1243. int result = removexattr(path, name, 0);
  1244. if (result < 0 && errno != ENOATTR) {
  1245. NSLogError(@"DDLogFileInfo: removexattr(%@, %@): error = %s",
  1246. attrName,
  1247. self.fileName,
  1248. strerror(errno));
  1249. }
  1250. }
  1251. #endif /* if TARGET_IPHONE_SIMULATOR */
  1252. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1253. #pragma mark Comparisons
  1254. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1255. - (BOOL)isEqual:(id)object {
  1256. if ([object isKindOfClass:[self class]]) {
  1257. DDLogFileInfo *another = (DDLogFileInfo *)object;
  1258. return [filePath isEqualToString:[another filePath]];
  1259. }
  1260. return NO;
  1261. }
  1262. - (NSUInteger)hash {
  1263. return [filePath hash];
  1264. }
  1265. - (NSComparisonResult)reverseCompareByCreationDate:(DDLogFileInfo *)another {
  1266. __auto_type us = [self creationDate];
  1267. __auto_type them = [another creationDate];
  1268. return [them compare:us];
  1269. }
  1270. - (NSComparisonResult)reverseCompareByModificationDate:(DDLogFileInfo *)another {
  1271. __auto_type us = [self modificationDate];
  1272. __auto_type them = [another modificationDate];
  1273. return [them compare:us];
  1274. }
  1275. @end
  1276. #if TARGET_OS_IPHONE
  1277. /**
  1278. * When creating log file on iOS we're setting NSFileProtectionKey attribute to NSFileProtectionCompleteUnlessOpen.
  1279. *
  1280. * But in case if app is able to launch from background we need to have an ability to open log file any time we
  1281. * want (even if device is locked). Thats why that attribute have to be changed to
  1282. * NSFileProtectionCompleteUntilFirstUserAuthentication.
  1283. */
  1284. BOOL doesAppRunInBackground() {
  1285. BOOL answer = NO;
  1286. NSArray *backgroundModes = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIBackgroundModes"];
  1287. for (NSString *mode in backgroundModes) {
  1288. if (mode.length > 0) {
  1289. answer = YES;
  1290. break;
  1291. }
  1292. }
  1293. return answer;
  1294. }
  1295. #endif