OSSFileLogger.m 50 KB

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