No Description

AWSDDFileLogger.h 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. // Disable legacy macros
  16. #ifndef AWSDD_LEGACY_MACROS
  17. #define AWSDD_LEGACY_MACROS 0
  18. #endif
  19. #import "AWSDDLog.h"
  20. @class AWSDDLogFileInfo;
  21. /**
  22. * This class provides a logger to write log statements to a file.
  23. **/
  24. // Default configuration and safety/sanity values.
  25. //
  26. // maximumFileSize -> kAWSDDDefaultLogMaxFileSize
  27. // rollingFrequency -> kAWSDDDefaultLogRollingFrequency
  28. // maximumNumberOfLogFiles -> kAWSDDDefaultLogMaxNumLogFiles
  29. // logFilesDiskQuota -> kAWSDDDefaultLogFilesDiskQuota
  30. //
  31. // You should carefully consider the proper configuration values for your application.
  32. extern unsigned long long const kAWSDDDefaultLogMaxFileSize;
  33. extern NSTimeInterval const kAWSDDDefaultLogRollingFrequency;
  34. extern NSUInteger const kAWSDDDefaultLogMaxNumLogFiles;
  35. extern unsigned long long const kAWSDDDefaultLogFilesDiskQuota;
  36. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  37. #pragma mark -
  38. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  39. /**
  40. * The LogFileManager protocol is designed to allow you to control all aspects of your log files.
  41. *
  42. * The primary purpose of this is to allow you to do something with the log files after they have been rolled.
  43. * Perhaps you want to compress them to save disk space.
  44. * Perhaps you want to upload them to an FTP server.
  45. * Perhaps you want to run some analytics on the file.
  46. *
  47. * A default LogFileManager is, of course, provided.
  48. * The default LogFileManager simply deletes old log files according to the maximumNumberOfLogFiles property.
  49. *
  50. * This protocol provides various methods to fetch the list of log files.
  51. *
  52. * There are two variants: sorted and unsorted.
  53. * If sorting is not necessary, the unsorted variant is obviously faster.
  54. * The sorted variant will return an array sorted by when the log files were created,
  55. * with the most recently created log file at index 0, and the oldest log file at the end of the array.
  56. *
  57. * You can fetch only the log file paths (full path including name), log file names (name only),
  58. * or an array of `AWSDDLogFileInfo` objects.
  59. * The `AWSDDLogFileInfo` class is documented below, and provides a handy wrapper that
  60. * gives you easy access to various file attributes such as the creation date or the file size.
  61. */
  62. @protocol AWSDDLogFileManager <NSObject>
  63. @required
  64. // Public properties
  65. /**
  66. * The maximum number of archived log files to keep on disk.
  67. * For example, if this property is set to 3,
  68. * then the LogFileManager will only keep 3 archived log files (plus the current active log file) on disk.
  69. * Once the active log file is rolled/archived, then the oldest of the existing 3 rolled/archived log files is deleted.
  70. *
  71. * You may optionally disable this option by setting it to zero.
  72. **/
  73. @property (readwrite, assign, atomic) NSUInteger maximumNumberOfLogFiles;
  74. /**
  75. * The maximum space that logs can take. On rolling logfile all old logfiles that exceed logFilesDiskQuota will
  76. * be deleted.
  77. *
  78. * You may optionally disable this option by setting it to zero.
  79. **/
  80. @property (readwrite, assign, atomic) unsigned long long logFilesDiskQuota;
  81. // Public methods
  82. /**
  83. * Returns the logs directory (path)
  84. */
  85. @property (nonatomic, readonly, copy) NSString *logsDirectory;
  86. /**
  87. * Returns an array of `NSString` objects,
  88. * each of which is the filePath to an existing log file on disk.
  89. **/
  90. @property (nonatomic, readonly, strong) NSArray<NSString *> *unsortedLogFilePaths;
  91. /**
  92. * Returns an array of `NSString` objects,
  93. * each of which is the fileName of an existing log file on disk.
  94. **/
  95. @property (nonatomic, readonly, strong) NSArray<NSString *> *unsortedLogFileNames;
  96. /**
  97. * Returns an array of `AWSDDLogFileInfo` objects,
  98. * each representing an existing log file on disk,
  99. * and containing important information about the log file such as it's modification date and size.
  100. **/
  101. @property (nonatomic, readonly, strong) NSArray<AWSDDLogFileInfo *> *unsortedLogFileInfos;
  102. /**
  103. * Just like the `unsortedLogFilePaths` method, but sorts the array.
  104. * The items in the array are sorted by creation date.
  105. * The first item in the array will be the most recently created log file.
  106. **/
  107. @property (nonatomic, readonly, strong) NSArray<NSString *> *sortedLogFilePaths;
  108. /**
  109. * Just like the `unsortedLogFileNames` method, but sorts the array.
  110. * The items in the array are sorted by creation date.
  111. * The first item in the array will be the most recently created log file.
  112. **/
  113. @property (nonatomic, readonly, strong) NSArray<NSString *> *sortedLogFileNames;
  114. /**
  115. * Just like the `unsortedLogFileInfos` method, but sorts the array.
  116. * The items in the array are sorted by creation date.
  117. * The first item in the array will be the most recently created log file.
  118. **/
  119. @property (nonatomic, readonly, strong) NSArray<AWSDDLogFileInfo *> *sortedLogFileInfos;
  120. // Private methods (only to be used by AWSDDFileLogger)
  121. /**
  122. * Generates a new unique log file path, and creates the corresponding log file.
  123. **/
  124. - (NSString *)createNewLogFile;
  125. @optional
  126. // Notifications from AWSDDFileLogger
  127. /**
  128. * Called when a log file was archieved
  129. */
  130. - (void)didArchiveLogFile:(NSString *)logFilePath NS_SWIFT_NAME(didArchiveLogFile(atPath:));
  131. /**
  132. * Called when the roll action was executed and the log was archieved
  133. */
  134. - (void)didRollAndArchiveLogFile:(NSString *)logFilePath NS_SWIFT_NAME(didRollAndArchiveLogFile(atPath:));
  135. @end
  136. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  137. #pragma mark -
  138. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  139. /**
  140. * Default log file manager.
  141. *
  142. * All log files are placed inside the logsDirectory.
  143. * If a specific logsDirectory isn't specified, the default directory is used.
  144. * On Mac, this is in `~/Library/Logs/<Application Name>`.
  145. * On iPhone, this is in `~/Library/Caches/Logs`.
  146. *
  147. * Log files are named `"<bundle identifier> <date> <time>.log"`
  148. * Example: `com.organization.myapp 2013-12-03 17-14.log`
  149. *
  150. * Archived log files are automatically deleted according to the `maximumNumberOfLogFiles` property.
  151. **/
  152. @interface AWSDDLogFileManagerDefault : NSObject <AWSDDLogFileManager>
  153. /**
  154. * Default initializer
  155. */
  156. - (instancetype)init;
  157. /**
  158. * Designated initialized, requires the logs directory
  159. */
  160. - (instancetype)initWithLogsDirectory:(NSString *)logsDirectory NS_DESIGNATED_INITIALIZER;
  161. #if TARGET_OS_IPHONE
  162. /*
  163. * Calling this constructor you can override the default "automagically" chosen NSFileProtection level.
  164. * Useful if you are writing a command line utility / CydiaSubstrate addon for iOS that has no NSBundle
  165. * or like SpringBoard no BackgroundModes key in the NSBundle:
  166. * iPhone:~ root# cycript -p SpringBoard
  167. * cy# [NSBundle mainBundle]
  168. * #"NSBundle </System/Library/CoreServices/SpringBoard.app> (loaded)"
  169. * cy# [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIBackgroundModes"];
  170. * null
  171. * cy#
  172. **/
  173. - (instancetype)initWithLogsDirectory:(NSString *)logsDirectory defaultFileProtectionLevel:(NSString *)fileProtectionLevel;
  174. #endif
  175. /*
  176. * Methods to override.
  177. *
  178. * Log files are named `"<bundle identifier> <date> <time>.log"`
  179. * Example: `com.organization.myapp 2013-12-03 17-14.log`
  180. *
  181. * If you wish to change default filename, you can override following two methods.
  182. * - `newLogFileName` method would be called on new logfile creation.
  183. * - `isLogFile:` method would be called to filter logfiles from all other files in logsDirectory.
  184. * You have to parse given filename and return YES if it is logFile.
  185. *
  186. * **NOTE**
  187. * `newLogFileName` returns filename. If appropriate file already exists, number would be added
  188. * to filename before extension. You have to handle this case in isLogFile: method.
  189. *
  190. * Example:
  191. * - newLogFileName returns `"com.organization.myapp 2013-12-03.log"`,
  192. * file `"com.organization.myapp 2013-12-03.log"` would be created.
  193. * - after some time `"com.organization.myapp 2013-12-03.log"` is archived
  194. * - newLogFileName again returns `"com.organization.myapp 2013-12-03.log"`,
  195. * file `"com.organization.myapp 2013-12-03 2.log"` would be created.
  196. * - after some time `"com.organization.myapp 2013-12-03 1.log"` is archived
  197. * - newLogFileName again returns `"com.organization.myapp 2013-12-03.log"`,
  198. * file `"com.organization.myapp 2013-12-03 3.log"` would be created.
  199. **/
  200. /**
  201. * Generates log file name with default format `"<bundle identifier> <date> <time>.log"`
  202. * Example: `MobileSafari 2013-12-03 17-14.log`
  203. *
  204. * You can change it by overriding `newLogFileName` and `isLogFile:` methods.
  205. **/
  206. @property (readonly, copy) NSString *newLogFileName;
  207. /**
  208. * Default log file name is `"<bundle identifier> <date> <time>.log"`.
  209. * Example: `MobileSafari 2013-12-03 17-14.log`
  210. *
  211. * You can change it by overriding `newLogFileName` and `isLogFile:` methods.
  212. **/
  213. - (BOOL)isLogFile:(NSString *)fileName NS_SWIFT_NAME(isLogFile(withName:));
  214. /* Inherited from AWSDDLogFileManager protocol:
  215. @property (readwrite, assign, atomic) NSUInteger maximumNumberOfLogFiles;
  216. @property (readwrite, assign, atomic) NSUInteger logFilesDiskQuota;
  217. - (NSString *)logsDirectory;
  218. - (NSArray *)unsortedLogFilePaths;
  219. - (NSArray *)unsortedLogFileNames;
  220. - (NSArray *)unsortedLogFileInfos;
  221. - (NSArray *)sortedLogFilePaths;
  222. - (NSArray *)sortedLogFileNames;
  223. - (NSArray *)sortedLogFileInfos;
  224. */
  225. @end
  226. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  227. #pragma mark -
  228. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  229. /**
  230. * Most users will want file log messages to be prepended with the date and time.
  231. * Rather than forcing the majority of users to write their own formatter,
  232. * we will supply a logical default formatter.
  233. * Users can easily replace this formatter with their own by invoking the `setLogFormatter:` method.
  234. * It can also be removed by calling `setLogFormatter:`, and passing a nil parameter.
  235. *
  236. * In addition to the convenience of having a logical default formatter,
  237. * it will also provide a template that makes it easy for developers to copy and change.
  238. **/
  239. @interface AWSDDLogFileFormatterDefault : NSObject <AWSDDLogFormatter>
  240. /**
  241. * Default initializer
  242. */
  243. - (instancetype)init;
  244. /**
  245. * Designated initializer, requires a date formatter
  246. */
  247. - (instancetype)initWithDateFormatter:(NSDateFormatter *)dateFormatter NS_DESIGNATED_INITIALIZER;
  248. @end
  249. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  250. #pragma mark -
  251. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  252. /**
  253. * The standard implementation for a file logger
  254. */
  255. @interface AWSDDFileLogger : AWSDDAbstractLogger <AWSDDLogger> {
  256. AWSDDLogFileInfo *_currentLogFileInfo;
  257. }
  258. /**
  259. * Default initializer
  260. */
  261. - (instancetype)init;
  262. /**
  263. * Designated initializer, requires a `AWSDDLogFileManager` instance
  264. */
  265. - (instancetype)initWithLogFileManager:(id <AWSDDLogFileManager>)logFileManager NS_DESIGNATED_INITIALIZER;
  266. /**
  267. * Called when the logger is about to write message. Call super before your implementation.
  268. */
  269. - (void)willLogMessage NS_REQUIRES_SUPER;
  270. /**
  271. * Called when the logger wrote message. Call super after your implementation.
  272. */
  273. - (void)didLogMessage NS_REQUIRES_SUPER;
  274. /**
  275. * Called when the logger checks archive or not current log file.
  276. * Override this method to exdend standart behavior. By default returns NO.
  277. */
  278. - (BOOL)shouldArchiveRecentLogFileInfo:(AWSDDLogFileInfo *)recentLogFileInfo;
  279. /**
  280. * Log File Rolling:
  281. *
  282. * `maximumFileSize`:
  283. * The approximate maximum size (in bytes) to allow log files to grow.
  284. * If a log file is larger than this value after a log statement is appended,
  285. * then the log file is rolled.
  286. *
  287. * `rollingFrequency`
  288. * How often to roll the log file.
  289. * The frequency is given as an `NSTimeInterval`, which is a double that specifies the interval in seconds.
  290. * Once the log file gets to be this old, it is rolled.
  291. *
  292. * `doNotReuseLogFiles`
  293. * When set, will always create a new log file at application launch.
  294. *
  295. * Both the `maximumFileSize` and the `rollingFrequency` are used to manage rolling.
  296. * Whichever occurs first will cause the log file to be rolled.
  297. *
  298. * For example:
  299. * The `rollingFrequency` is 24 hours,
  300. * but the log file surpasses the `maximumFileSize` after only 20 hours.
  301. * The log file will be rolled at that 20 hour mark.
  302. * A new log file will be created, and the 24 hour timer will be restarted.
  303. *
  304. * You may optionally disable rolling due to filesize by setting `maximumFileSize` to zero.
  305. * If you do so, rolling is based solely on `rollingFrequency`.
  306. *
  307. * You may optionally disable rolling due to time by setting `rollingFrequency` to zero (or any non-positive number).
  308. * If you do so, rolling is based solely on `maximumFileSize`.
  309. *
  310. * If you disable both `maximumFileSize` and `rollingFrequency`, then the log file won't ever be rolled.
  311. * This is strongly discouraged.
  312. **/
  313. @property (readwrite, assign) unsigned long long maximumFileSize;
  314. /**
  315. * See description for `maximumFileSize`
  316. */
  317. @property (readwrite, assign) NSTimeInterval rollingFrequency;
  318. /**
  319. * See description for `maximumFileSize`
  320. */
  321. @property (readwrite, assign, atomic) BOOL doNotReuseLogFiles;
  322. /**
  323. * The AWSDDLogFileManager instance can be used to retrieve the list of log files,
  324. * and configure the maximum number of archived log files to keep.
  325. *
  326. * @see AWSDDLogFileManager.maximumNumberOfLogFiles
  327. **/
  328. @property (strong, nonatomic, readonly) id <AWSDDLogFileManager> logFileManager;
  329. /**
  330. * When using a custom formatter you can set the `logMessage` method not to append
  331. * `\n` character after each output. This allows for some greater flexibility with
  332. * custom formatters. Default value is YES.
  333. **/
  334. @property (nonatomic, readwrite, assign) BOOL automaticallyAppendNewlineForCustomFormatters;
  335. /**
  336. * You can optionally force the current log file to be rolled with this method.
  337. * CompletionBlock will be called on main queue.
  338. */
  339. - (void)rollLogFileWithCompletionBlock:(void (^)(void))completionBlock NS_SWIFT_NAME(rollLogFile(withCompletion:));
  340. /**
  341. * Method is deprecated.
  342. * @deprecated Use `rollLogFileWithCompletionBlock:` method instead.
  343. */
  344. - (void)rollLogFile __attribute((deprecated));
  345. // Inherited from AWSDDAbstractLogger
  346. // - (id <AWSDDLogFormatter>)logFormatter;
  347. // - (void)setLogFormatter:(id <AWSDDLogFormatter>)formatter;
  348. /**
  349. * Returns the log file that should be used.
  350. * If there is an existing log file that is suitable,
  351. * within the constraints of `maximumFileSize` and `rollingFrequency`, then it is returned.
  352. *
  353. * Otherwise a new file is created and returned.
  354. **/
  355. @property (nonatomic, readonly, strong) AWSDDLogFileInfo *currentLogFileInfo;
  356. @end
  357. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  358. #pragma mark -
  359. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  360. /**
  361. * `AWSDDLogFileInfo` is a simple class that provides access to various file attributes.
  362. * It provides good performance as it only fetches the information if requested,
  363. * and it caches the information to prevent duplicate fetches.
  364. *
  365. * It was designed to provide quick snapshots of the current state of log files,
  366. * and to help sort log files in an array.
  367. *
  368. * This class does not monitor the files, or update it's cached attribute values if the file changes on disk.
  369. * This is not what the class was designed for.
  370. *
  371. * If you absolutely must get updated values,
  372. * you can invoke the reset method which will clear the cache.
  373. **/
  374. @interface AWSDDLogFileInfo : NSObject
  375. @property (strong, nonatomic, readonly) NSString *filePath;
  376. @property (strong, nonatomic, readonly) NSString *fileName;
  377. #if FOUNDATION_SWIFT_SDK_EPOCH_AT_LEAST(8)
  378. @property (strong, nonatomic, readonly) NSDictionary<NSFileAttributeKey, id> *fileAttributes;
  379. #else
  380. @property (strong, nonatomic, readonly) NSDictionary<NSString *, id> *fileAttributes;
  381. #endif
  382. @property (strong, nonatomic, readonly) NSDate *creationDate;
  383. @property (strong, nonatomic, readonly) NSDate *modificationDate;
  384. @property (nonatomic, readonly) unsigned long long fileSize;
  385. @property (nonatomic, readonly) NSTimeInterval age;
  386. @property (nonatomic, readwrite) BOOL isArchived;
  387. + (instancetype)logFileWithPath:(NSString *)filePath NS_SWIFT_UNAVAILABLE("Use init(filePath:)");
  388. - (instancetype)init NS_UNAVAILABLE;
  389. - (instancetype)initWithFilePath:(NSString *)filePath NS_DESIGNATED_INITIALIZER;
  390. - (void)reset;
  391. - (void)renameFile:(NSString *)newFileName NS_SWIFT_NAME(renameFile(to:));
  392. #if TARGET_IPHONE_SIMULATOR
  393. // So here's the situation.
  394. // Extended attributes are perfect for what we're trying to do here (marking files as archived).
  395. // This is exactly what extended attributes were designed for.
  396. //
  397. // But Apple screws us over on the simulator.
  398. // Everytime you build-and-go, they copy the application into a new folder on the hard drive,
  399. // and as part of the process they strip extended attributes from our log files.
  400. // Normally, a copy of a file preserves extended attributes.
  401. // So obviously Apple has gone to great lengths to piss us off.
  402. //
  403. // Thus we use a slightly different tactic for marking log files as archived in the simulator.
  404. // That way it "just works" and there's no confusion when testing.
  405. //
  406. // The difference in method names is indicative of the difference in functionality.
  407. // On the simulator we add an attribute by appending a filename extension.
  408. //
  409. // For example:
  410. // "mylog.txt" -> "mylog.archived.txt"
  411. // "mylog" -> "mylog.archived"
  412. - (BOOL)hasExtensionAttributeWithName:(NSString *)attrName;
  413. - (void)addExtensionAttributeWithName:(NSString *)attrName;
  414. - (void)removeExtensionAttributeWithName:(NSString *)attrName;
  415. #else /* if TARGET_IPHONE_SIMULATOR */
  416. // Normal use of extended attributes used everywhere else,
  417. // such as on Macs and on iPhone devices.
  418. - (BOOL)hasExtendedAttributeWithName:(NSString *)attrName;
  419. - (void)addExtendedAttributeWithName:(NSString *)attrName;
  420. - (void)removeExtendedAttributeWithName:(NSString *)attrName;
  421. #endif /* if TARGET_IPHONE_SIMULATOR */
  422. - (NSComparisonResult)reverseCompareByCreationDate:(AWSDDLogFileInfo *)another;
  423. - (NSComparisonResult)reverseCompareByModificationDate:(AWSDDLogFileInfo *)another;
  424. @end