DDFileLogger.m 50 KB

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