DDFileLogger.m 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485
  1. // Software License Agreement (BSD License)
  2. //
  3. // Copyright (c) 2010-2015, 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. NSString *_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:(NSString *)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. BOOL hasProperPrefix = [fileName hasPrefix:appName];
  222. BOOL hasProperSuffix = [fileName hasSuffix:@".log"];
  223. BOOL hasProperDate = NO;
  224. if (hasProperPrefix && hasProperSuffix) {
  225. NSUInteger lengthOfMiddle = fileName.length - appName.length - @".log".length;
  226. // Date string should have at least 16 characters - " 2013-12-03 17-14"
  227. if (lengthOfMiddle >= 17) {
  228. NSRange range = NSMakeRange(appName.length, lengthOfMiddle);
  229. NSString *middle = [fileName substringWithRange:range];
  230. NSArray *components = [middle componentsSeparatedByString:@" "];
  231. // When creating logfile if there is existing file with the same name, we append attemp number at the end.
  232. // Thats why here we can have three or four components. For details see createNewLogFile method.
  233. //
  234. // Components:
  235. // "", "2013-12-03", "17-14"
  236. // or
  237. // "", "2013-12-03", "17-14", "1"
  238. if (components.count == 3 || components.count == 4) {
  239. NSString *dateString = [NSString stringWithFormat:@"%@ %@", components[1], components[2]];
  240. NSDateFormatter *dateFormatter = [self logFileDateFormatter];
  241. NSDate *date = [dateFormatter dateFromString:dateString];
  242. if (date) {
  243. hasProperDate = YES;
  244. }
  245. }
  246. }
  247. }
  248. return (hasProperPrefix && hasProperDate && hasProperSuffix);
  249. }
  250. - (NSDateFormatter *)logFileDateFormatter {
  251. NSMutableDictionary *dictionary = [[NSThread currentThread]
  252. threadDictionary];
  253. NSString *dateFormat = @"yyyy'-'MM'-'dd' 'HH'-'mm'";
  254. NSString *key = [NSString stringWithFormat:@"logFileDateFormatter.%@", dateFormat];
  255. NSDateFormatter *dateFormatter = dictionary[key];
  256. if (dateFormatter == nil) {
  257. dateFormatter = [[NSDateFormatter alloc] init];
  258. [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
  259. [dateFormatter setDateFormat:dateFormat];
  260. [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  261. dictionary[key] = dateFormatter;
  262. }
  263. return dateFormatter;
  264. }
  265. - (NSArray *)unsortedLogFilePaths {
  266. NSString *logsDirectory = [self logsDirectory];
  267. NSArray *fileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:logsDirectory error:nil];
  268. NSMutableArray *unsortedLogFilePaths = [NSMutableArray arrayWithCapacity:[fileNames count]];
  269. for (NSString *fileName in fileNames) {
  270. // Filter out any files that aren't log files. (Just for extra safety)
  271. #if TARGET_IPHONE_SIMULATOR
  272. // In case of iPhone simulator there can be 'archived' extension. isLogFile:
  273. // method knows nothing about it. Thus removing it for this method.
  274. //
  275. // See full explanation in the header file.
  276. NSString *theFileName = [fileName stringByReplacingOccurrencesOfString:@".archived"
  277. withString:@""];
  278. if ([self isLogFile:theFileName])
  279. #else
  280. if ([self isLogFile:fileName])
  281. #endif
  282. {
  283. NSString *filePath = [logsDirectory stringByAppendingPathComponent:fileName];
  284. [unsortedLogFilePaths addObject:filePath];
  285. }
  286. }
  287. return unsortedLogFilePaths;
  288. }
  289. - (NSArray *)unsortedLogFileNames {
  290. NSArray *unsortedLogFilePaths = [self unsortedLogFilePaths];
  291. NSMutableArray *unsortedLogFileNames = [NSMutableArray arrayWithCapacity:[unsortedLogFilePaths count]];
  292. for (NSString *filePath in unsortedLogFilePaths) {
  293. [unsortedLogFileNames addObject:[filePath lastPathComponent]];
  294. }
  295. return unsortedLogFileNames;
  296. }
  297. - (NSArray *)unsortedLogFileInfos {
  298. NSArray *unsortedLogFilePaths = [self unsortedLogFilePaths];
  299. NSMutableArray *unsortedLogFileInfos = [NSMutableArray arrayWithCapacity:[unsortedLogFilePaths count]];
  300. for (NSString *filePath in unsortedLogFilePaths) {
  301. DDLogFileInfo *logFileInfo = [[DDLogFileInfo alloc] initWithFilePath:filePath];
  302. [unsortedLogFileInfos addObject:logFileInfo];
  303. }
  304. return unsortedLogFileInfos;
  305. }
  306. - (NSArray *)sortedLogFilePaths {
  307. NSArray *sortedLogFileInfos = [self sortedLogFileInfos];
  308. NSMutableArray *sortedLogFilePaths = [NSMutableArray arrayWithCapacity:[sortedLogFileInfos count]];
  309. for (DDLogFileInfo *logFileInfo in sortedLogFileInfos) {
  310. [sortedLogFilePaths addObject:[logFileInfo filePath]];
  311. }
  312. return sortedLogFilePaths;
  313. }
  314. - (NSArray *)sortedLogFileNames {
  315. NSArray *sortedLogFileInfos = [self sortedLogFileInfos];
  316. NSMutableArray *sortedLogFileNames = [NSMutableArray arrayWithCapacity:[sortedLogFileInfos count]];
  317. for (DDLogFileInfo *logFileInfo in sortedLogFileInfos) {
  318. [sortedLogFileNames addObject:[logFileInfo fileName]];
  319. }
  320. return sortedLogFileNames;
  321. }
  322. - (NSArray *)sortedLogFileInfos {
  323. return [[self unsortedLogFileInfos] sortedArrayUsingSelector:@selector(reverseCompareByCreationDate:)];
  324. }
  325. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  326. #pragma mark Creation
  327. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  328. - (NSString *)newLogFileName {
  329. NSString *appName = [self applicationName];
  330. NSDateFormatter *dateFormatter = [self logFileDateFormatter];
  331. NSString *formattedDate = [dateFormatter stringFromDate:[NSDate date]];
  332. return [NSString stringWithFormat:@"%@ %@.log", appName, formattedDate];
  333. }
  334. - (NSString *)createNewLogFile {
  335. NSString *fileName = [self newLogFileName];
  336. NSString *logsDirectory = [self logsDirectory];
  337. NSUInteger attempt = 1;
  338. do {
  339. NSString *actualFileName = fileName;
  340. if (attempt > 1) {
  341. NSString *extension = [actualFileName pathExtension];
  342. actualFileName = [actualFileName stringByDeletingPathExtension];
  343. actualFileName = [actualFileName stringByAppendingFormat:@" %lu", (unsigned long)attempt];
  344. if (extension.length) {
  345. actualFileName = [actualFileName stringByAppendingPathExtension:extension];
  346. }
  347. }
  348. NSString *filePath = [logsDirectory stringByAppendingPathComponent:actualFileName];
  349. if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
  350. NSLogVerbose(@"DDLogFileManagerDefault: Creating new log file: %@", actualFileName);
  351. NSDictionary *attributes = nil;
  352. #if TARGET_OS_IPHONE
  353. // When creating log file on iOS we're setting NSFileProtectionKey attribute to NSFileProtectionCompleteUnlessOpen.
  354. //
  355. // But in case if app is able to launch from background we need to have an ability to open log file any time we
  356. // want (even if device is locked). Thats why that attribute have to be changed to
  357. // NSFileProtectionCompleteUntilFirstUserAuthentication.
  358. NSString *key = _defaultFileProtectionLevel ? :
  359. (doesAppRunInBackground() ? NSFileProtectionCompleteUntilFirstUserAuthentication : NSFileProtectionCompleteUnlessOpen);
  360. attributes = @{
  361. NSFileProtectionKey: key
  362. };
  363. #endif
  364. [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:attributes];
  365. // Since we just created a new log file, we may need to delete some old log files
  366. [self deleteOldLogFiles];
  367. return filePath;
  368. } else {
  369. attempt++;
  370. }
  371. } while (YES);
  372. }
  373. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  374. #pragma mark Utility
  375. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  376. - (NSString *)applicationName {
  377. static NSString *_appName;
  378. static dispatch_once_t onceToken;
  379. dispatch_once(&onceToken, ^{
  380. _appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
  381. if (!_appName) {
  382. _appName = [[NSProcessInfo processInfo] processName];
  383. }
  384. if (!_appName) {
  385. _appName = @"";
  386. }
  387. });
  388. return _appName;
  389. }
  390. @end
  391. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  392. #pragma mark -
  393. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  394. @interface DDLogFileFormatterDefault () {
  395. NSDateFormatter *_dateFormatter;
  396. }
  397. @end
  398. @implementation DDLogFileFormatterDefault
  399. - (instancetype)init {
  400. return [self initWithDateFormatter:nil];
  401. }
  402. - (instancetype)initWithDateFormatter:(NSDateFormatter *)aDateFormatter {
  403. if ((self = [super init])) {
  404. if (aDateFormatter) {
  405. _dateFormatter = aDateFormatter;
  406. } else {
  407. _dateFormatter = [[NSDateFormatter alloc] init];
  408. [_dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4]; // 10.4+ style
  409. [_dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss:SSS"];
  410. }
  411. }
  412. return self;
  413. }
  414. - (NSString *)formatLogMessage:(DDLogMessage *)logMessage {
  415. NSString *dateAndTime = [_dateFormatter stringFromDate:(logMessage->_timestamp)];
  416. return [NSString stringWithFormat:@"%@ %@", dateAndTime, logMessage->_message];
  417. }
  418. @end
  419. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  420. #pragma mark -
  421. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  422. @interface DDFileLogger () {
  423. __strong id <DDLogFileManager> _logFileManager;
  424. DDLogFileInfo *_currentLogFileInfo;
  425. NSFileHandle *_currentLogFileHandle;
  426. dispatch_source_t _currentLogFileVnode;
  427. dispatch_source_t _rollingTimer;
  428. unsigned long long _maximumFileSize;
  429. NSTimeInterval _rollingFrequency;
  430. }
  431. - (void)rollLogFileNow;
  432. - (void)maybeRollLogFileDueToAge;
  433. - (void)maybeRollLogFileDueToSize;
  434. @end
  435. @implementation DDFileLogger
  436. - (instancetype)init {
  437. DDLogFileManagerDefault *defaultLogFileManager = [[DDLogFileManagerDefault alloc] init];
  438. return [self initWithLogFileManager:defaultLogFileManager];
  439. }
  440. - (instancetype)initWithLogFileManager:(id <DDLogFileManager>)aLogFileManager {
  441. if ((self = [super init])) {
  442. _maximumFileSize = kDDDefaultLogMaxFileSize;
  443. _rollingFrequency = kDDDefaultLogRollingFrequency;
  444. _automaticallyAppendNewlineForCustomFormatters = YES;
  445. logFileManager = aLogFileManager;
  446. self.logFormatter = [DDLogFileFormatterDefault new];
  447. }
  448. return self;
  449. }
  450. - (void)dealloc {
  451. [_currentLogFileHandle synchronizeFile];
  452. [_currentLogFileHandle closeFile];
  453. if (_currentLogFileVnode) {
  454. dispatch_source_cancel(_currentLogFileVnode);
  455. _currentLogFileVnode = NULL;
  456. }
  457. if (_rollingTimer) {
  458. dispatch_source_cancel(_rollingTimer);
  459. _rollingTimer = NULL;
  460. }
  461. }
  462. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  463. #pragma mark Properties
  464. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  465. @synthesize logFileManager;
  466. - (unsigned long long)maximumFileSize {
  467. __block unsigned long long result;
  468. dispatch_block_t block = ^{
  469. result = _maximumFileSize;
  470. };
  471. // The design of this method is taken from the DDAbstractLogger implementation.
  472. // For extensive documentation please refer to the DDAbstractLogger implementation.
  473. // Note: The internal implementation MUST access the maximumFileSize variable directly,
  474. // This method is designed explicitly for external access.
  475. //
  476. // Using "self." syntax to go through this method will cause immediate deadlock.
  477. // This is the intended result. Fix it by accessing the ivar directly.
  478. // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster.
  479. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  480. NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax.");
  481. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  482. dispatch_sync(globalLoggingQueue, ^{
  483. dispatch_sync(self.loggerQueue, block);
  484. });
  485. return result;
  486. }
  487. - (void)setMaximumFileSize:(unsigned long long)newMaximumFileSize {
  488. dispatch_block_t block = ^{
  489. @autoreleasepool {
  490. _maximumFileSize = newMaximumFileSize;
  491. [self maybeRollLogFileDueToSize];
  492. }
  493. };
  494. // The design of this method is taken from the DDAbstractLogger implementation.
  495. // For extensive documentation please refer to the DDAbstractLogger implementation.
  496. // Note: The internal implementation MUST access the maximumFileSize variable directly,
  497. // This method is designed explicitly for external access.
  498. //
  499. // Using "self." syntax to go through this method will cause immediate deadlock.
  500. // This is the intended result. Fix it by accessing the ivar directly.
  501. // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster.
  502. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  503. NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax.");
  504. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  505. dispatch_async(globalLoggingQueue, ^{
  506. dispatch_async(self.loggerQueue, block);
  507. });
  508. }
  509. - (NSTimeInterval)rollingFrequency {
  510. __block NSTimeInterval result;
  511. dispatch_block_t block = ^{
  512. result = _rollingFrequency;
  513. };
  514. // The design of this method is taken from the DDAbstractLogger implementation.
  515. // For extensive documentation please refer to the DDAbstractLogger implementation.
  516. // Note: The internal implementation should access the rollingFrequency variable directly,
  517. // This method is designed explicitly for external access.
  518. //
  519. // Using "self." syntax to go through this method will cause immediate deadlock.
  520. // This is the intended result. Fix it by accessing the ivar directly.
  521. // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster.
  522. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  523. NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax.");
  524. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  525. dispatch_sync(globalLoggingQueue, ^{
  526. dispatch_sync(self.loggerQueue, block);
  527. });
  528. return result;
  529. }
  530. - (void)setRollingFrequency:(NSTimeInterval)newRollingFrequency {
  531. dispatch_block_t block = ^{
  532. @autoreleasepool {
  533. _rollingFrequency = newRollingFrequency;
  534. [self maybeRollLogFileDueToAge];
  535. }
  536. };
  537. // The design of this method is taken from the DDAbstractLogger implementation.
  538. // For extensive documentation please refer to the DDAbstractLogger implementation.
  539. // Note: The internal implementation should access the rollingFrequency variable directly,
  540. // This method is designed explicitly for external access.
  541. //
  542. // Using "self." syntax to go through this method will cause immediate deadlock.
  543. // This is the intended result. Fix it by accessing the ivar directly.
  544. // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster.
  545. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  546. NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax.");
  547. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  548. dispatch_async(globalLoggingQueue, ^{
  549. dispatch_async(self.loggerQueue, block);
  550. });
  551. }
  552. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  553. #pragma mark File Rolling
  554. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  555. - (void)scheduleTimerToRollLogFileDueToAge {
  556. if (_rollingTimer) {
  557. dispatch_source_cancel(_rollingTimer);
  558. _rollingTimer = NULL;
  559. }
  560. if (_currentLogFileInfo == nil || _rollingFrequency <= 0.0) {
  561. return;
  562. }
  563. NSDate *logFileCreationDate = [_currentLogFileInfo creationDate];
  564. NSTimeInterval ti = [logFileCreationDate timeIntervalSinceReferenceDate];
  565. ti += _rollingFrequency;
  566. NSDate *logFileRollingDate = [NSDate dateWithTimeIntervalSinceReferenceDate:ti];
  567. NSLogVerbose(@"DDFileLogger: scheduleTimerToRollLogFileDueToAge");
  568. NSLogVerbose(@"DDFileLogger: logFileCreationDate: %@", logFileCreationDate);
  569. NSLogVerbose(@"DDFileLogger: logFileRollingDate : %@", logFileRollingDate);
  570. _rollingTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.loggerQueue);
  571. dispatch_source_set_event_handler(_rollingTimer, ^{ @autoreleasepool {
  572. [self maybeRollLogFileDueToAge];
  573. } });
  574. #if !OS_OBJECT_USE_OBJC
  575. dispatch_source_t theRollingTimer = _rollingTimer;
  576. dispatch_source_set_cancel_handler(_rollingTimer, ^{
  577. dispatch_release(theRollingTimer);
  578. });
  579. #endif
  580. uint64_t delay = (uint64_t)([logFileRollingDate timeIntervalSinceNow] * NSEC_PER_SEC);
  581. dispatch_time_t fireTime = dispatch_time(DISPATCH_TIME_NOW, delay);
  582. dispatch_source_set_timer(_rollingTimer, fireTime, DISPATCH_TIME_FOREVER, 1.0);
  583. dispatch_resume(_rollingTimer);
  584. }
  585. - (void)rollLogFile {
  586. [self rollLogFileWithCompletionBlock:nil];
  587. }
  588. - (void)rollLogFileWithCompletionBlock:(void (^)())completionBlock {
  589. // This method is public.
  590. // We need to execute the rolling on our logging thread/queue.
  591. dispatch_block_t block = ^{
  592. @autoreleasepool {
  593. [self rollLogFileNow];
  594. if (completionBlock) {
  595. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  596. completionBlock();
  597. });
  598. }
  599. }
  600. };
  601. // The design of this method is taken from the DDAbstractLogger implementation.
  602. // For extensive documentation please refer to the DDAbstractLogger implementation.
  603. if ([self isOnInternalLoggerQueue]) {
  604. block();
  605. } else {
  606. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  607. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  608. dispatch_async(globalLoggingQueue, ^{
  609. dispatch_async(self.loggerQueue, block);
  610. });
  611. }
  612. }
  613. - (void)rollLogFileNow {
  614. NSLogVerbose(@"DDFileLogger: rollLogFileNow");
  615. if (_currentLogFileHandle == nil) {
  616. return;
  617. }
  618. [_currentLogFileHandle synchronizeFile];
  619. [_currentLogFileHandle closeFile];
  620. _currentLogFileHandle = nil;
  621. _currentLogFileInfo.isArchived = YES;
  622. if ([logFileManager respondsToSelector:@selector(didRollAndArchiveLogFile:)]) {
  623. [logFileManager didRollAndArchiveLogFile:(_currentLogFileInfo.filePath)];
  624. }
  625. _currentLogFileInfo = nil;
  626. if (_currentLogFileVnode) {
  627. dispatch_source_cancel(_currentLogFileVnode);
  628. _currentLogFileVnode = NULL;
  629. }
  630. if (_rollingTimer) {
  631. dispatch_source_cancel(_rollingTimer);
  632. _rollingTimer = NULL;
  633. }
  634. }
  635. - (void)maybeRollLogFileDueToAge {
  636. if (_rollingFrequency > 0.0 && _currentLogFileInfo.age >= _rollingFrequency) {
  637. NSLogVerbose(@"DDFileLogger: Rolling log file due to age...");
  638. [self rollLogFileNow];
  639. } else {
  640. [self scheduleTimerToRollLogFileDueToAge];
  641. }
  642. }
  643. - (void)maybeRollLogFileDueToSize {
  644. // This method is called from logMessage.
  645. // Keep it FAST.
  646. // Note: Use direct access to maximumFileSize variable.
  647. // We specifically wrote our own getter/setter method to allow us to do this (for performance reasons).
  648. if (_maximumFileSize > 0) {
  649. unsigned long long fileSize = [_currentLogFileHandle offsetInFile];
  650. if (fileSize >= _maximumFileSize) {
  651. NSLogVerbose(@"DDFileLogger: Rolling log file due to size (%qu)...", fileSize);
  652. [self rollLogFileNow];
  653. }
  654. }
  655. }
  656. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  657. #pragma mark File Logging
  658. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  659. /**
  660. * Returns the log file that should be used.
  661. * If there is an existing log file that is suitable,
  662. * within the constraints of maximumFileSize and rollingFrequency, then it is returned.
  663. *
  664. * Otherwise a new file is created and returned.
  665. **/
  666. - (DDLogFileInfo *)currentLogFileInfo {
  667. if (_currentLogFileInfo == nil) {
  668. NSArray *sortedLogFileInfos = [logFileManager sortedLogFileInfos];
  669. if ([sortedLogFileInfos count] > 0) {
  670. DDLogFileInfo *mostRecentLogFileInfo = sortedLogFileInfos[0];
  671. BOOL shouldArchiveMostRecent = NO;
  672. if (mostRecentLogFileInfo.isArchived) {
  673. shouldArchiveMostRecent = NO;
  674. } else if (_maximumFileSize > 0 && mostRecentLogFileInfo.fileSize >= _maximumFileSize) {
  675. shouldArchiveMostRecent = YES;
  676. } else if (_rollingFrequency > 0.0 && mostRecentLogFileInfo.age >= _rollingFrequency) {
  677. shouldArchiveMostRecent = YES;
  678. }
  679. #if TARGET_OS_IPHONE
  680. // When creating log file on iOS we're setting NSFileProtectionKey attribute to NSFileProtectionCompleteUnlessOpen.
  681. //
  682. // But in case if app is able to launch from background we need to have an ability to open log file any time we
  683. // want (even if device is locked). Thats why that attribute have to be changed to
  684. // NSFileProtectionCompleteUntilFirstUserAuthentication.
  685. //
  686. // If previous log was created when app wasn't running in background, but now it is - we archive it and create
  687. // a new one.
  688. //
  689. // If user has owerwritten to NSFileProtectionNone there is no neeed to create a new one.
  690. if (!_doNotReuseLogFiles && doesAppRunInBackground()) {
  691. NSString *key = mostRecentLogFileInfo.fileAttributes[NSFileProtectionKey];
  692. if ([key length] > 0 && !([key isEqualToString:NSFileProtectionCompleteUntilFirstUserAuthentication] || [key isEqualToString:NSFileProtectionNone])) {
  693. shouldArchiveMostRecent = YES;
  694. }
  695. }
  696. #endif
  697. if (!_doNotReuseLogFiles && !mostRecentLogFileInfo.isArchived && !shouldArchiveMostRecent) {
  698. NSLogVerbose(@"DDFileLogger: Resuming logging with file %@", mostRecentLogFileInfo.fileName);
  699. _currentLogFileInfo = mostRecentLogFileInfo;
  700. } else {
  701. if (shouldArchiveMostRecent) {
  702. mostRecentLogFileInfo.isArchived = YES;
  703. if ([logFileManager respondsToSelector:@selector(didArchiveLogFile:)]) {
  704. [logFileManager didArchiveLogFile:(mostRecentLogFileInfo.filePath)];
  705. }
  706. }
  707. }
  708. }
  709. if (_currentLogFileInfo == nil) {
  710. NSString *currentLogFilePath = [logFileManager createNewLogFile];
  711. _currentLogFileInfo = [[DDLogFileInfo alloc] initWithFilePath:currentLogFilePath];
  712. }
  713. }
  714. return _currentLogFileInfo;
  715. }
  716. - (NSFileHandle *)currentLogFileHandle {
  717. if (_currentLogFileHandle == nil) {
  718. NSString *logFilePath = [[self currentLogFileInfo] filePath];
  719. _currentLogFileHandle = [NSFileHandle fileHandleForWritingAtPath:logFilePath];
  720. [_currentLogFileHandle seekToEndOfFile];
  721. if (_currentLogFileHandle) {
  722. [self scheduleTimerToRollLogFileDueToAge];
  723. // Here we are monitoring the log file. In case if it would be deleted ormoved
  724. // somewhere we want to roll it and use a new one.
  725. _currentLogFileVnode = dispatch_source_create(
  726. DISPATCH_SOURCE_TYPE_VNODE,
  727. [_currentLogFileHandle fileDescriptor],
  728. DISPATCH_VNODE_DELETE | DISPATCH_VNODE_RENAME,
  729. self.loggerQueue
  730. );
  731. dispatch_source_set_event_handler(_currentLogFileVnode, ^{ @autoreleasepool {
  732. NSLogInfo(@"DDFileLogger: Current logfile was moved. Rolling it and creating a new one");
  733. [self rollLogFileNow];
  734. } });
  735. #if !OS_OBJECT_USE_OBJC
  736. dispatch_source_t vnode = _currentLogFileVnode;
  737. dispatch_source_set_cancel_handler(_currentLogFileVnode, ^{
  738. dispatch_release(vnode);
  739. });
  740. #endif
  741. dispatch_resume(_currentLogFileVnode);
  742. }
  743. }
  744. return _currentLogFileHandle;
  745. }
  746. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  747. #pragma mark DDLogger Protocol
  748. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  749. static int exception_count = 0;
  750. - (void)logMessage:(DDLogMessage *)logMessage {
  751. NSString *message = logMessage->_message;
  752. BOOL isFormatted = NO;
  753. if (_logFormatter) {
  754. message = [_logFormatter formatLogMessage:logMessage];
  755. isFormatted = message != logMessage->_message;
  756. }
  757. if (message) {
  758. if ((!isFormatted || _automaticallyAppendNewlineForCustomFormatters) &&
  759. (![message hasSuffix:@"\n"])) {
  760. message = [message stringByAppendingString:@"\n"];
  761. }
  762. NSData *logData = [message dataUsingEncoding:NSUTF8StringEncoding];
  763. @try {
  764. [[self currentLogFileHandle] writeData:logData];
  765. [self maybeRollLogFileDueToSize];
  766. } @catch (NSException *exception) {
  767. exception_count++;
  768. if (exception_count <= 10) {
  769. NSLogError(@"DDFileLogger.logMessage: %@", exception);
  770. if (exception_count == 10) {
  771. NSLogError(@"DDFileLogger.logMessage: Too many exceptions -- will not log any more of them.");
  772. }
  773. }
  774. }
  775. }
  776. }
  777. - (void)willRemoveLogger {
  778. // If you override me be sure to invoke [super willRemoveLogger];
  779. [self rollLogFileNow];
  780. }
  781. - (NSString *)loggerName {
  782. return @"cocoa.lumberjack.fileLogger";
  783. }
  784. @end
  785. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  786. #pragma mark -
  787. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  788. #if TARGET_IPHONE_SIMULATOR
  789. static NSString * const kDDXAttrArchivedName = @"archived";
  790. #else
  791. static NSString * const kDDXAttrArchivedName = @"lumberjack.log.archived";
  792. #endif
  793. @interface DDLogFileInfo () {
  794. __strong NSString *_filePath;
  795. __strong NSString *_fileName;
  796. __strong NSDictionary *_fileAttributes;
  797. __strong NSDate *_creationDate;
  798. __strong NSDate *_modificationDate;
  799. unsigned long long _fileSize;
  800. }
  801. @end
  802. @implementation DDLogFileInfo
  803. @synthesize filePath;
  804. @dynamic fileName;
  805. @dynamic fileAttributes;
  806. @dynamic creationDate;
  807. @dynamic modificationDate;
  808. @dynamic fileSize;
  809. @dynamic age;
  810. @dynamic isArchived;
  811. #pragma mark Lifecycle
  812. + (instancetype)logFileWithPath:(NSString *)aFilePath {
  813. return [[self alloc] initWithFilePath:aFilePath];
  814. }
  815. - (instancetype)initWithFilePath:(NSString *)aFilePath {
  816. if ((self = [super init])) {
  817. filePath = [aFilePath copy];
  818. }
  819. return self;
  820. }
  821. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  822. #pragma mark Standard Info
  823. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  824. - (NSDictionary *)fileAttributes {
  825. if (_fileAttributes == nil) {
  826. _fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
  827. }
  828. return _fileAttributes;
  829. }
  830. - (NSString *)fileName {
  831. if (_fileName == nil) {
  832. _fileName = [filePath lastPathComponent];
  833. }
  834. return _fileName;
  835. }
  836. - (NSDate *)modificationDate {
  837. if (_modificationDate == nil) {
  838. _modificationDate = self.fileAttributes[NSFileModificationDate];
  839. }
  840. return _modificationDate;
  841. }
  842. - (NSDate *)creationDate {
  843. if (_creationDate == nil) {
  844. _creationDate = self.fileAttributes[NSFileCreationDate];
  845. }
  846. return _creationDate;
  847. }
  848. - (unsigned long long)fileSize {
  849. if (_fileSize == 0) {
  850. _fileSize = [self.fileAttributes[NSFileSize] unsignedLongLongValue];
  851. }
  852. return _fileSize;
  853. }
  854. - (NSTimeInterval)age {
  855. return [[self creationDate] timeIntervalSinceNow] * -1.0;
  856. }
  857. - (NSString *)description {
  858. return [@{ @"filePath": self.filePath ? : @"",
  859. @"fileName": self.fileName ? : @"",
  860. @"fileAttributes": self.fileAttributes ? : @"",
  861. @"creationDate": self.creationDate ? : @"",
  862. @"modificationDate": self.modificationDate ? : @"",
  863. @"fileSize": @(self.fileSize),
  864. @"age": @(self.age),
  865. @"isArchived": @(self.isArchived) } description];
  866. }
  867. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  868. #pragma mark Archiving
  869. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  870. - (BOOL)isArchived {
  871. #if TARGET_IPHONE_SIMULATOR
  872. // Extended attributes don't work properly on the simulator.
  873. // So we have to use a less attractive alternative.
  874. // See full explanation in the header file.
  875. return [self hasExtensionAttributeWithName:kDDXAttrArchivedName];
  876. #else
  877. return [self hasExtendedAttributeWithName:kDDXAttrArchivedName];
  878. #endif
  879. }
  880. - (void)setIsArchived:(BOOL)flag {
  881. #if TARGET_IPHONE_SIMULATOR
  882. // Extended attributes don't work properly on the simulator.
  883. // So we have to use a less attractive alternative.
  884. // See full explanation in the header file.
  885. if (flag) {
  886. [self addExtensionAttributeWithName:kDDXAttrArchivedName];
  887. } else {
  888. [self removeExtensionAttributeWithName:kDDXAttrArchivedName];
  889. }
  890. #else
  891. if (flag) {
  892. [self addExtendedAttributeWithName:kDDXAttrArchivedName];
  893. } else {
  894. [self removeExtendedAttributeWithName:kDDXAttrArchivedName];
  895. }
  896. #endif
  897. }
  898. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  899. #pragma mark Changes
  900. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  901. - (void)reset {
  902. _fileName = nil;
  903. _fileAttributes = nil;
  904. _creationDate = nil;
  905. _modificationDate = nil;
  906. }
  907. - (void)renameFile:(NSString *)newFileName {
  908. // This method is only used on the iPhone simulator, where normal extended attributes are broken.
  909. // See full explanation in the header file.
  910. if (![newFileName isEqualToString:[self fileName]]) {
  911. NSString *fileDir = [filePath stringByDeletingLastPathComponent];
  912. NSString *newFilePath = [fileDir stringByAppendingPathComponent:newFileName];
  913. NSLogVerbose(@"DDLogFileInfo: Renaming file: '%@' -> '%@'", self.fileName, newFileName);
  914. NSError *error = nil;
  915. if ([[NSFileManager defaultManager] fileExistsAtPath:newFilePath] &&
  916. ![[NSFileManager defaultManager] removeItemAtPath:newFilePath error:&error]) {
  917. NSLogError(@"DDLogFileInfo: Error deleting archive (%@): %@", self.fileName, error);
  918. }
  919. if (![[NSFileManager defaultManager] moveItemAtPath:filePath toPath:newFilePath error:&error]) {
  920. NSLogError(@"DDLogFileInfo: Error renaming file (%@): %@", self.fileName, error);
  921. }
  922. filePath = newFilePath;
  923. [self reset];
  924. }
  925. }
  926. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  927. #pragma mark Attribute Management
  928. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  929. #if TARGET_IPHONE_SIMULATOR
  930. // Extended attributes don't work properly on the simulator.
  931. // So we have to use a less attractive alternative.
  932. // See full explanation in the header file.
  933. - (BOOL)hasExtensionAttributeWithName:(NSString *)attrName {
  934. // This method is only used on the iPhone simulator, where normal extended attributes are broken.
  935. // See full explanation in the header file.
  936. // Split the file name into components. File name may have various format, but generally
  937. // structure is same:
  938. //
  939. // <name part>.<extension part> and <name part>.archived.<extension part>
  940. // or
  941. // <name part> and <name part>.archived
  942. //
  943. // So we want to search for the attrName in the components (ignoring the first array index).
  944. NSArray *components = [[self fileName] componentsSeparatedByString:@"."];
  945. // Watch out for file names without an extension
  946. for (NSUInteger i = 1; i < components.count; i++) {
  947. NSString *attr = components[i];
  948. if ([attrName isEqualToString:attr]) {
  949. return YES;
  950. }
  951. }
  952. return NO;
  953. }
  954. - (void)addExtensionAttributeWithName:(NSString *)attrName {
  955. // This method is only used on the iPhone simulator, where normal extended attributes are broken.
  956. // See full explanation in the header file.
  957. if ([attrName length] == 0) {
  958. return;
  959. }
  960. // Example:
  961. // attrName = "archived"
  962. //
  963. // "mylog.txt" -> "mylog.archived.txt"
  964. // "mylog" -> "mylog.archived"
  965. NSArray *components = [[self fileName] componentsSeparatedByString:@"."];
  966. NSUInteger count = [components count];
  967. NSUInteger estimatedNewLength = [[self fileName] length] + [attrName length] + 1;
  968. NSMutableString *newFileName = [NSMutableString stringWithCapacity:estimatedNewLength];
  969. if (count > 0) {
  970. [newFileName appendString:components.firstObject];
  971. }
  972. NSString *lastExt = @"";
  973. NSUInteger i;
  974. for (i = 1; i < count; i++) {
  975. NSString *attr = components[i];
  976. if ([attr length] == 0) {
  977. continue;
  978. }
  979. if ([attrName isEqualToString:attr]) {
  980. // Extension attribute already exists in file name
  981. return;
  982. }
  983. if ([lastExt length] > 0) {
  984. [newFileName appendFormat:@".%@", lastExt];
  985. }
  986. lastExt = attr;
  987. }
  988. [newFileName appendFormat:@".%@", attrName];
  989. if ([lastExt length] > 0) {
  990. [newFileName appendFormat:@".%@", lastExt];
  991. }
  992. [self renameFile:newFileName];
  993. }
  994. - (void)removeExtensionAttributeWithName:(NSString *)attrName {
  995. // This method is only used on the iPhone simulator, where normal extended attributes are broken.
  996. // See full explanation in the header file.
  997. if ([attrName length] == 0) {
  998. return;
  999. }
  1000. // Example:
  1001. // attrName = "archived"
  1002. //
  1003. // "mylog.archived.txt" -> "mylog.txt"
  1004. // "mylog.archived" -> "mylog"
  1005. NSArray *components = [[self fileName] componentsSeparatedByString:@"."];
  1006. NSUInteger count = [components count];
  1007. NSUInteger estimatedNewLength = [[self fileName] length];
  1008. NSMutableString *newFileName = [NSMutableString stringWithCapacity:estimatedNewLength];
  1009. if (count > 0) {
  1010. [newFileName appendString:components.firstObject];
  1011. }
  1012. BOOL found = NO;
  1013. NSUInteger i;
  1014. for (i = 1; i < count; i++) {
  1015. NSString *attr = components[i];
  1016. if ([attrName isEqualToString:attr]) {
  1017. found = YES;
  1018. } else {
  1019. [newFileName appendFormat:@".%@", attr];
  1020. }
  1021. }
  1022. if (found) {
  1023. [self renameFile:newFileName];
  1024. }
  1025. }
  1026. #else /* if TARGET_IPHONE_SIMULATOR */
  1027. - (BOOL)hasExtendedAttributeWithName:(NSString *)attrName {
  1028. const char *path = [filePath UTF8String];
  1029. const char *name = [attrName UTF8String];
  1030. ssize_t result = getxattr(path, name, NULL, 0, 0, 0);
  1031. return (result >= 0);
  1032. }
  1033. - (void)addExtendedAttributeWithName:(NSString *)attrName {
  1034. const char *path = [filePath UTF8String];
  1035. const char *name = [attrName UTF8String];
  1036. int result = setxattr(path, name, NULL, 0, 0, 0);
  1037. if (result < 0) {
  1038. NSLogError(@"DDLogFileInfo: setxattr(%@, %@): error = %s",
  1039. attrName,
  1040. filePath,
  1041. strerror(errno));
  1042. }
  1043. }
  1044. - (void)removeExtendedAttributeWithName:(NSString *)attrName {
  1045. const char *path = [filePath UTF8String];
  1046. const char *name = [attrName UTF8String];
  1047. int result = removexattr(path, name, 0);
  1048. if (result < 0 && errno != ENOATTR) {
  1049. NSLogError(@"DDLogFileInfo: removexattr(%@, %@): error = %s",
  1050. attrName,
  1051. self.fileName,
  1052. strerror(errno));
  1053. }
  1054. }
  1055. #endif /* if TARGET_IPHONE_SIMULATOR */
  1056. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1057. #pragma mark Comparisons
  1058. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1059. - (BOOL)isEqual:(id)object {
  1060. if ([object isKindOfClass:[self class]]) {
  1061. DDLogFileInfo *another = (DDLogFileInfo *)object;
  1062. return [filePath isEqualToString:[another filePath]];
  1063. }
  1064. return NO;
  1065. }
  1066. - (NSComparisonResult)reverseCompareByCreationDate:(DDLogFileInfo *)another {
  1067. NSDate *us = [self creationDate];
  1068. NSDate *them = [another creationDate];
  1069. NSComparisonResult result = [us compare:them];
  1070. if (result == NSOrderedAscending) {
  1071. return NSOrderedDescending;
  1072. }
  1073. if (result == NSOrderedDescending) {
  1074. return NSOrderedAscending;
  1075. }
  1076. return NSOrderedSame;
  1077. }
  1078. - (NSComparisonResult)reverseCompareByModificationDate:(DDLogFileInfo *)another {
  1079. NSDate *us = [self modificationDate];
  1080. NSDate *them = [another modificationDate];
  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. @end
  1091. #if TARGET_OS_IPHONE
  1092. /**
  1093. * When creating log file on iOS we're setting NSFileProtectionKey attribute to NSFileProtectionCompleteUnlessOpen.
  1094. *
  1095. * But in case if app is able to launch from background we need to have an ability to open log file any time we
  1096. * want (even if device is locked). Thats why that attribute have to be changed to
  1097. * NSFileProtectionCompleteUntilFirstUserAuthentication.
  1098. */
  1099. BOOL doesAppRunInBackground() {
  1100. BOOL answer = NO;
  1101. NSArray *backgroundModes = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIBackgroundModes"];
  1102. for (NSString *mode in backgroundModes) {
  1103. if (mode.length > 0) {
  1104. answer = YES;
  1105. break;
  1106. }
  1107. }
  1108. return answer;
  1109. }
  1110. #endif