No Description

AWSDDLog.m 48KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406
  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. #import <pthread.h>
  21. #import <dispatch/dispatch.h>
  22. #import <objc/runtime.h>
  23. #import <mach/mach_host.h>
  24. #import <mach/host_info.h>
  25. #import <libkern/OSAtomic.h>
  26. #import <Availability.h>
  27. #if TARGET_OS_IOS
  28. #import <UIKit/UIDevice.h>
  29. #endif
  30. #if !__has_feature(objc_arc)
  31. #error This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
  32. #endif
  33. // We probably shouldn't be using AWSDDLog() statements within the AWSDDLog implementation.
  34. // But we still want to leave our log statements for any future debugging,
  35. // and to allow other developers to trace the implementation (which is a great learning tool).
  36. //
  37. // So we use a primitive logging macro around NSLog.
  38. // We maintain the NS prefix on the macros to be explicit about the fact that we're using NSLog.
  39. #ifndef AWSDD_DEBUG
  40. #define AWSDD_DEBUG NO
  41. #endif
  42. #define NSLogDebug(frmt, ...) do{ if(AWSDD_DEBUG) NSLog((frmt), ##__VA_ARGS__); } while(0)
  43. // Specifies the maximum queue size of the logging thread.
  44. //
  45. // Since most logging is asynchronous, its possible for rogue threads to flood the logging queue.
  46. // That is, to issue an abundance of log statements faster than the logging thread can keepup.
  47. // Typically such a scenario occurs when log statements are added haphazardly within large loops,
  48. // but may also be possible if relatively slow loggers are being used.
  49. //
  50. // This property caps the queue size at a given number of outstanding log statements.
  51. // If a thread attempts to issue a log statement when the queue is already maxed out,
  52. // the issuing thread will block until the queue size drops below the max again.
  53. #ifndef AWSDDLOG_MAX_QUEUE_SIZE
  54. #define AWSDDLOG_MAX_QUEUE_SIZE 1000 // Should not exceed INT32_MAX
  55. #endif
  56. // The "global logging queue" refers to [AWSDDLog loggingQueue].
  57. // It is the queue that all log statements go through.
  58. //
  59. // The logging queue sets a flag via dispatch_queue_set_specific using this key.
  60. // We can check for this key via dispatch_get_specific() to see if we're on the "global logging queue".
  61. static void *const GlobalLoggingQueueIdentityKey = (void *)&GlobalLoggingQueueIdentityKey;
  62. @interface AWSDDLoggerNode : NSObject
  63. {
  64. // Direct accessors to be used only for performance
  65. @public
  66. id <AWSDDLogger> _logger;
  67. AWSDDLogLevel _level;
  68. dispatch_queue_t _loggerQueue;
  69. }
  70. @property (nonatomic, readonly) id <AWSDDLogger> logger;
  71. @property (nonatomic, readonly) AWSDDLogLevel level;
  72. @property (nonatomic, readonly) dispatch_queue_t loggerQueue;
  73. + (AWSDDLoggerNode *)nodeWithLogger:(id <AWSDDLogger>)logger
  74. loggerQueue:(dispatch_queue_t)loggerQueue
  75. level:(AWSDDLogLevel)level;
  76. @end
  77. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  78. #pragma mark -
  79. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  80. @interface AWSDDLog ()
  81. // An array used to manage all the individual loggers.
  82. // The array is only modified on the loggingQueue/loggingThread.
  83. @property (nonatomic, strong) NSMutableArray *_loggers;
  84. @end
  85. @implementation AWSDDLog
  86. // All logging statements are added to the same queue to ensure FIFO operation.
  87. static dispatch_queue_t _loggingQueue;
  88. // Individual loggers are executed concurrently per log statement.
  89. // Each logger has it's own associated queue, and a dispatch group is used for synchrnoization.
  90. static dispatch_group_t _loggingGroup;
  91. // In order to prevent to queue from growing infinitely large,
  92. // a maximum size is enforced (AWSDDLOG_MAX_QUEUE_SIZE).
  93. static dispatch_semaphore_t _queueSemaphore;
  94. // Minor optimization for uniprocessor machines
  95. static NSUInteger _numProcessors;
  96. /**
  97. * Returns the singleton `AWSDDLog`.
  98. * The instance is used by `AWSDDLog` class methods.
  99. *
  100. * @return The singleton `AWSDDLog`.
  101. */
  102. + (instancetype)sharedInstance {
  103. static id sharedInstance = nil;
  104. static dispatch_once_t onceToken;
  105. dispatch_once(&onceToken, ^{
  106. sharedInstance = [[self alloc] init];
  107. });
  108. return sharedInstance;
  109. }
  110. /**
  111. * The runtime sends initialize to each class in a program exactly one time just before the class,
  112. * or any class that inherits from it, is sent its first message from within the program. (Thus the
  113. * method may never be invoked if the class is not used.) The runtime sends the initialize message to
  114. * classes in a thread-safe manner. Superclasses receive this message before their subclasses.
  115. *
  116. * This method may also be called directly (assumably by accident), hence the safety mechanism.
  117. **/
  118. + (void)initialize {
  119. static dispatch_once_t AWSDDLogOnceToken;
  120. dispatch_once(&AWSDDLogOnceToken, ^{
  121. NSLogDebug(@"AWSDDLog: Using grand central dispatch");
  122. _loggingQueue = dispatch_queue_create("cocoa.lumberjack", NULL);
  123. _loggingGroup = dispatch_group_create();
  124. void *nonNullValue = GlobalLoggingQueueIdentityKey; // Whatever, just not null
  125. dispatch_queue_set_specific(_loggingQueue, GlobalLoggingQueueIdentityKey, nonNullValue, NULL);
  126. _queueSemaphore = dispatch_semaphore_create(AWSDDLOG_MAX_QUEUE_SIZE);
  127. // Figure out how many processors are available.
  128. // This may be used later for an optimization on uniprocessor machines.
  129. _numProcessors = MAX([NSProcessInfo processInfo].processorCount, (NSUInteger) 1);
  130. NSLogDebug(@"AWSDDLog: numProcessors = %@", @(_numProcessors));
  131. });
  132. }
  133. /**
  134. * The `AWSDDLog` initializer.
  135. * Static variables are set only once.
  136. *
  137. * @return An initialized `AWSDDLog` instance.
  138. */
  139. - (id)init {
  140. self = [super init];
  141. if (self) {
  142. self._loggers = [[NSMutableArray alloc] initWithCapacity:4];
  143. self.logLevel = AWSDDLogLevelWarning;//default to warning
  144. #if TARGET_OS_IOS
  145. NSString *notificationName = @"UIApplicationWillTerminateNotification";
  146. #else
  147. NSString *notificationName = nil;
  148. // On Command Line Tool apps AppKit may not be avaliable
  149. #ifdef NSAppKitVersionNumber10_0
  150. if (NSApp) {
  151. notificationName = @"NSApplicationWillTerminateNotification";
  152. }
  153. #endif
  154. if (!notificationName) {
  155. // If there is no NSApp -> we are running Command Line Tool app.
  156. // In this case terminate notification wouldn't be fired, so we use workaround.
  157. atexit_b (^{
  158. [self applicationWillTerminate:nil];
  159. });
  160. }
  161. #endif /* if TARGET_OS_IOS */
  162. if (notificationName) {
  163. [[NSNotificationCenter defaultCenter] addObserver:self
  164. selector:@selector(applicationWillTerminate:)
  165. name:notificationName
  166. object:nil];
  167. }
  168. }
  169. return self;
  170. }
  171. /**
  172. * Provides access to the logging queue.
  173. **/
  174. + (dispatch_queue_t)loggingQueue {
  175. return _loggingQueue;
  176. }
  177. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  178. #pragma mark Notifications
  179. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  180. - (void)applicationWillTerminate:(NSNotification * __attribute__((unused)))notification {
  181. [self flushLog];
  182. }
  183. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  184. #pragma mark Logger Management
  185. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  186. + (void)addLogger:(id <AWSDDLogger>)logger {
  187. [self.sharedInstance addLogger:logger];
  188. }
  189. - (void)addLogger:(id <AWSDDLogger>)logger {
  190. [self addLogger:logger withLevel:AWSDDLogLevelAll]; // AWSDDLogLevelAll has all bits set
  191. }
  192. + (void)addLogger:(id <AWSDDLogger>)logger withLevel:(AWSDDLogLevel)level {
  193. [self.sharedInstance addLogger:logger withLevel:level];
  194. }
  195. - (void)addLogger:(id <AWSDDLogger>)logger withLevel:(AWSDDLogLevel)level {
  196. if (!logger) {
  197. return;
  198. }
  199. dispatch_async(_loggingQueue, ^{ @autoreleasepool {
  200. [self lt_addLogger:logger level:level];
  201. } });
  202. }
  203. + (void)removeLogger:(id <AWSDDLogger>)logger {
  204. [self.sharedInstance removeLogger:logger];
  205. }
  206. - (void)removeLogger:(id <AWSDDLogger>)logger {
  207. if (!logger) {
  208. return;
  209. }
  210. dispatch_async(_loggingQueue, ^{ @autoreleasepool {
  211. [self lt_removeLogger:logger];
  212. } });
  213. }
  214. + (void)removeAllLoggers {
  215. [self.sharedInstance removeAllLoggers];
  216. }
  217. - (void)removeAllLoggers {
  218. dispatch_async(_loggingQueue, ^{ @autoreleasepool {
  219. [self lt_removeAllLoggers];
  220. } });
  221. }
  222. + (NSArray<id<AWSDDLogger>> *)allLoggers {
  223. return [self.sharedInstance allLoggers];
  224. }
  225. - (NSArray<id<AWSDDLogger>> *)allLoggers {
  226. __block NSArray *theLoggers;
  227. dispatch_sync(_loggingQueue, ^{ @autoreleasepool {
  228. theLoggers = [self lt_allLoggers];
  229. } });
  230. return theLoggers;
  231. }
  232. + (NSArray<AWSDDLoggerInformation *> *)allLoggersWithLevel {
  233. return [self.sharedInstance allLoggersWithLevel];
  234. }
  235. - (NSArray<AWSDDLoggerInformation *> *)allLoggersWithLevel {
  236. __block NSArray *theLoggersWithLevel;
  237. dispatch_sync(_loggingQueue, ^{ @autoreleasepool {
  238. theLoggersWithLevel = [self lt_allLoggersWithLevel];
  239. } });
  240. return theLoggersWithLevel;
  241. }
  242. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  243. #pragma mark - Master Logging
  244. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  245. - (void)queueLogMessage:(AWSDDLogMessage *)logMessage asynchronously:(BOOL)asyncFlag {
  246. // We have a tricky situation here...
  247. //
  248. // In the common case, when the queueSize is below the maximumQueueSize,
  249. // we want to simply enqueue the logMessage. And we want to do this as fast as possible,
  250. // which means we don't want to block and we don't want to use any locks.
  251. //
  252. // However, if the queueSize gets too big, we want to block.
  253. // But we have very strict requirements as to when we block, and how long we block.
  254. //
  255. // The following example should help illustrate our requirements:
  256. //
  257. // Imagine that the maximum queue size is configured to be 5,
  258. // and that there are already 5 log messages queued.
  259. // Let us call these 5 queued log messages A, B, C, D, and E. (A is next to be executed)
  260. //
  261. // Now if our thread issues a log statement (let us call the log message F),
  262. // it should block before the message is added to the queue.
  263. // Furthermore, it should be unblocked immediately after A has been unqueued.
  264. //
  265. // The requirements are strict in this manner so that we block only as long as necessary,
  266. // and so that blocked threads are unblocked in the order in which they were blocked.
  267. //
  268. // Returning to our previous example, let us assume that log messages A through E are still queued.
  269. // Our aforementioned thread is blocked attempting to queue log message F.
  270. // Now assume we have another separate thread that attempts to issue log message G.
  271. // It should block until log messages A and B have been unqueued.
  272. // We are using a counting semaphore provided by GCD.
  273. // The semaphore is initialized with our AWSDDLOG_MAX_QUEUE_SIZE value.
  274. // Everytime we want to queue a log message we decrement this value.
  275. // If the resulting value is less than zero,
  276. // the semaphore function waits in FIFO order for a signal to occur before returning.
  277. //
  278. // A dispatch semaphore is an efficient implementation of a traditional counting semaphore.
  279. // Dispatch semaphores call down to the kernel only when the calling thread needs to be blocked.
  280. // If the calling semaphore does not need to block, no kernel call is made.
  281. dispatch_semaphore_wait(_queueSemaphore, DISPATCH_TIME_FOREVER);
  282. // We've now sure we won't overflow the queue.
  283. // It is time to queue our log message.
  284. dispatch_block_t logBlock = ^{
  285. @autoreleasepool {
  286. [self lt_log:logMessage];
  287. }
  288. };
  289. if (asyncFlag) {
  290. dispatch_async(_loggingQueue, logBlock);
  291. } else {
  292. dispatch_sync(_loggingQueue, logBlock);
  293. }
  294. }
  295. + (void)log:(BOOL)asynchronous
  296. level:(AWSDDLogLevel)level
  297. flag:(AWSDDLogFlag)flag
  298. context:(NSInteger)context
  299. file:(const char *)file
  300. function:(const char *)function
  301. line:(NSUInteger)line
  302. tag:(id)tag
  303. format:(NSString *)format, ... {
  304. va_list args;
  305. if (format) {
  306. va_start(args, format);
  307. NSString *message = [[NSString alloc] initWithFormat:format arguments:args];
  308. va_end(args);
  309. va_start(args, format);
  310. [self log:asynchronous
  311. message:message
  312. level:level
  313. flag:flag
  314. context:context
  315. file:file
  316. function:function
  317. line:line
  318. tag:tag];
  319. va_end(args);
  320. }
  321. }
  322. - (void)log:(BOOL)asynchronous
  323. level:(AWSDDLogLevel)level
  324. flag:(AWSDDLogFlag)flag
  325. context:(NSInteger)context
  326. file:(const char *)file
  327. function:(const char *)function
  328. line:(NSUInteger)line
  329. tag:(id)tag
  330. format:(NSString *)format, ... {
  331. va_list args;
  332. if (format) {
  333. va_start(args, format);
  334. NSString *message = [[NSString alloc] initWithFormat:format arguments:args];
  335. va_end(args);
  336. va_start(args, format);
  337. [self log:asynchronous
  338. message:message
  339. level:level
  340. flag:flag
  341. context:context
  342. file:file
  343. function:function
  344. line:line
  345. tag:tag];
  346. va_end(args);
  347. }
  348. }
  349. + (void)log:(BOOL)asynchronous
  350. level:(AWSDDLogLevel)level
  351. flag:(AWSDDLogFlag)flag
  352. context:(NSInteger)context
  353. file:(const char *)file
  354. function:(const char *)function
  355. line:(NSUInteger)line
  356. tag:(id)tag
  357. format:(NSString *)format
  358. args:(va_list)args {
  359. [self.sharedInstance log:asynchronous level:level flag:flag context:context file:file function:function line:line tag:tag format:format args:args];
  360. }
  361. - (void)log:(BOOL)asynchronous
  362. level:(AWSDDLogLevel)level
  363. flag:(AWSDDLogFlag)flag
  364. context:(NSInteger)context
  365. file:(const char *)file
  366. function:(const char *)function
  367. line:(NSUInteger)line
  368. tag:(id)tag
  369. format:(NSString *)format
  370. args:(va_list)args {
  371. if (format) {
  372. NSString *message = [[NSString alloc] initWithFormat:format arguments:args];
  373. [self log:asynchronous
  374. message:message
  375. level:level
  376. flag:flag
  377. context:context
  378. file:file
  379. function:function
  380. line:line
  381. tag:tag];
  382. }
  383. }
  384. + (void)log:(BOOL)asynchronous
  385. message:(NSString *)message
  386. level:(AWSDDLogLevel)level
  387. flag:(AWSDDLogFlag)flag
  388. context:(NSInteger)context
  389. file:(const char *)file
  390. function:(const char *)function
  391. line:(NSUInteger)line
  392. tag:(id)tag {
  393. [self.sharedInstance log:asynchronous message:message level:level flag:flag context:context file:file function:function line:line tag:tag];
  394. }
  395. - (void)log:(BOOL)asynchronous
  396. message:(NSString *)message
  397. level:(AWSDDLogLevel)level
  398. flag:(AWSDDLogFlag)flag
  399. context:(NSInteger)context
  400. file:(const char *)file
  401. function:(const char *)function
  402. line:(NSUInteger)line
  403. tag:(id)tag {
  404. if(level & flag){
  405. AWSDDLogMessage *logMessage = [[AWSDDLogMessage alloc] initWithMessage:message
  406. level:level
  407. flag:flag
  408. context:context
  409. file:[NSString stringWithFormat:@"%s", file]
  410. function:[NSString stringWithFormat:@"%s", function]
  411. line:line
  412. tag:tag
  413. options:(AWSDDLogMessageOptions)0
  414. timestamp:nil];
  415. [self queueLogMessage:logMessage asynchronously:asynchronous];
  416. }
  417. }
  418. + (void)log:(BOOL)asynchronous
  419. message:(AWSDDLogMessage *)logMessage {
  420. [self.sharedInstance log:asynchronous message:logMessage];
  421. }
  422. - (void)log:(BOOL)asynchronous
  423. message:(AWSDDLogMessage *)logMessage {
  424. [self queueLogMessage:logMessage asynchronously:asynchronous];
  425. }
  426. + (void)flushLog {
  427. [self.sharedInstance flushLog];
  428. }
  429. - (void)flushLog {
  430. dispatch_sync(_loggingQueue, ^{ @autoreleasepool {
  431. [self lt_flush];
  432. } });
  433. }
  434. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  435. #pragma mark Registered Dynamic Logging
  436. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  437. + (BOOL)isRegisteredClass:(Class)class {
  438. SEL getterSel = @selector(ddLogLevel);
  439. SEL setterSel = @selector(ddSetLogLevel:);
  440. #if TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR
  441. // Issue #6 (GoogleCode) - Crashes on iOS 4.2.1 and iPhone 4
  442. //
  443. // Crash caused by class_getClassMethod(2).
  444. //
  445. // "It's a bug with UIAccessibilitySafeCategory__NSObject so it didn't pop up until
  446. // users had VoiceOver enabled [...]. I was able to work around it by searching the
  447. // result of class_copyMethodList() instead of calling class_getClassMethod()"
  448. BOOL result = NO;
  449. unsigned int methodCount, i;
  450. Method *methodList = class_copyMethodList(object_getClass(class), &methodCount);
  451. if (methodList != NULL) {
  452. BOOL getterFound = NO;
  453. BOOL setterFound = NO;
  454. for (i = 0; i < methodCount; ++i) {
  455. SEL currentSel = method_getName(methodList[i]);
  456. if (currentSel == getterSel) {
  457. getterFound = YES;
  458. } else if (currentSel == setterSel) {
  459. setterFound = YES;
  460. }
  461. if (getterFound && setterFound) {
  462. result = YES;
  463. break;
  464. }
  465. }
  466. free(methodList);
  467. }
  468. return result;
  469. #else /* if TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR */
  470. // Issue #24 (GitHub) - Crashing in in ARC+Simulator
  471. //
  472. // The method +[AWSDDLog isRegisteredClass] will crash a project when using it with ARC + Simulator.
  473. // For running in the Simulator, it needs to execute the non-iOS code.
  474. Method getter = class_getClassMethod(class, getterSel);
  475. Method setter = class_getClassMethod(class, setterSel);
  476. if ((getter != NULL) && (setter != NULL)) {
  477. return YES;
  478. }
  479. return NO;
  480. #endif /* if TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR */
  481. }
  482. + (NSArray *)registeredClasses {
  483. // We're going to get the list of all registered classes.
  484. // The Objective-C runtime library automatically registers all the classes defined in your source code.
  485. //
  486. // To do this we use the following method (documented in the Objective-C Runtime Reference):
  487. //
  488. // int objc_getClassList(Class *buffer, int bufferLen)
  489. //
  490. // We can pass (NULL, 0) to obtain the total number of
  491. // registered class definitions without actually retrieving any class definitions.
  492. // This allows us to allocate the minimum amount of memory needed for the application.
  493. NSUInteger numClasses = 0;
  494. Class *classes = NULL;
  495. while (numClasses == 0) {
  496. numClasses = (NSUInteger)MAX(objc_getClassList(NULL, 0), 0);
  497. // numClasses now tells us how many classes we have (but it might change)
  498. // So we can allocate our buffer, and get pointers to all the class definitions.
  499. NSUInteger bufferSize = numClasses;
  500. classes = numClasses ? (Class *)malloc(sizeof(Class) * bufferSize) : NULL;
  501. if (classes == NULL) {
  502. return @[]; //no memory or classes?
  503. }
  504. numClasses = (NSUInteger)MAX(objc_getClassList(classes, (int)bufferSize),0);
  505. if (numClasses > bufferSize || numClasses == 0) {
  506. //apparently more classes added between calls (or a problem); try again
  507. free(classes);
  508. numClasses = 0;
  509. }
  510. }
  511. // We can now loop through the classes, and test each one to see if it is a AWSDDLogging class.
  512. NSMutableArray *result = [NSMutableArray arrayWithCapacity:numClasses];
  513. for (NSUInteger i = 0; i < numClasses; i++) {
  514. Class class = classes[i];
  515. if ([self isRegisteredClass:class]) {
  516. [result addObject:class];
  517. }
  518. }
  519. free(classes);
  520. return result;
  521. }
  522. + (NSArray *)registeredClassNames {
  523. NSArray *registeredClasses = [self registeredClasses];
  524. NSMutableArray *result = [NSMutableArray arrayWithCapacity:[registeredClasses count]];
  525. for (Class class in registeredClasses) {
  526. [result addObject:NSStringFromClass(class)];
  527. }
  528. return result;
  529. }
  530. + (AWSDDLogLevel)levelForClass:(Class)aClass {
  531. if ([self isRegisteredClass:aClass]) {
  532. return [aClass ddLogLevel];
  533. }
  534. return (AWSDDLogLevel)-1;
  535. }
  536. + (AWSDDLogLevel)levelForClassWithName:(NSString *)aClassName {
  537. Class aClass = NSClassFromString(aClassName);
  538. return [self levelForClass:aClass];
  539. }
  540. + (void)setLevel:(AWSDDLogLevel)level forClass:(Class)aClass {
  541. if ([self isRegisteredClass:aClass]) {
  542. [aClass ddSetLogLevel:level];
  543. }
  544. }
  545. + (void)setLevel:(AWSDDLogLevel)level forClassWithName:(NSString *)aClassName {
  546. Class aClass = NSClassFromString(aClassName);
  547. [self setLevel:level forClass:aClass];
  548. }
  549. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  550. #pragma mark Logging Thread
  551. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  552. - (void)lt_addLogger:(id <AWSDDLogger>)logger level:(AWSDDLogLevel)level {
  553. // Add to loggers array.
  554. // Need to create loggerQueue if loggerNode doesn't provide one.
  555. for (AWSDDLoggerNode* node in self._loggers) {
  556. if (node->_logger == logger
  557. && node->_level == level) {
  558. // Exactly same logger already added, exit
  559. return;
  560. }
  561. }
  562. NSAssert(dispatch_get_specific(GlobalLoggingQueueIdentityKey),
  563. @"This method should only be run on the logging thread/queue");
  564. dispatch_queue_t loggerQueue = NULL;
  565. if ([logger respondsToSelector:@selector(loggerQueue)]) {
  566. // Logger may be providing its own queue
  567. loggerQueue = [logger loggerQueue];
  568. }
  569. if (loggerQueue == nil) {
  570. // Automatically create queue for the logger.
  571. // Use the logger name as the queue name if possible.
  572. const char *loggerQueueName = NULL;
  573. if ([logger respondsToSelector:@selector(loggerName)]) {
  574. loggerQueueName = [[logger loggerName] UTF8String];
  575. }
  576. loggerQueue = dispatch_queue_create(loggerQueueName, NULL);
  577. }
  578. AWSDDLoggerNode *loggerNode = [AWSDDLoggerNode nodeWithLogger:logger loggerQueue:loggerQueue level:level];
  579. [self._loggers addObject:loggerNode];
  580. if ([logger respondsToSelector:@selector(didAddLoggerInQueue:)]) {
  581. dispatch_async(loggerNode->_loggerQueue, ^{ @autoreleasepool {
  582. [logger didAddLoggerInQueue:loggerNode->_loggerQueue];
  583. } });
  584. } else if ([logger respondsToSelector:@selector(didAddLogger)]) {
  585. dispatch_async(loggerNode->_loggerQueue, ^{ @autoreleasepool {
  586. [logger didAddLogger];
  587. } });
  588. }
  589. }
  590. - (void)lt_removeLogger:(id <AWSDDLogger>)logger {
  591. // Find associated loggerNode in list of added loggers
  592. NSAssert(dispatch_get_specific(GlobalLoggingQueueIdentityKey),
  593. @"This method should only be run on the logging thread/queue");
  594. AWSDDLoggerNode *loggerNode = nil;
  595. for (AWSDDLoggerNode *node in self._loggers) {
  596. if (node->_logger == logger) {
  597. loggerNode = node;
  598. break;
  599. }
  600. }
  601. if (loggerNode == nil) {
  602. NSLogDebug(@"AWSDDLog: Request to remove logger which wasn't added");
  603. return;
  604. }
  605. // Notify logger
  606. if ([logger respondsToSelector:@selector(willRemoveLogger)]) {
  607. dispatch_async(loggerNode->_loggerQueue, ^{ @autoreleasepool {
  608. [logger willRemoveLogger];
  609. } });
  610. }
  611. // Remove from loggers array
  612. [self._loggers removeObject:loggerNode];
  613. }
  614. - (void)lt_removeAllLoggers {
  615. NSAssert(dispatch_get_specific(GlobalLoggingQueueIdentityKey),
  616. @"This method should only be run on the logging thread/queue");
  617. // Notify all loggers
  618. for (AWSDDLoggerNode *loggerNode in self._loggers) {
  619. if ([loggerNode->_logger respondsToSelector:@selector(willRemoveLogger)]) {
  620. dispatch_async(loggerNode->_loggerQueue, ^{ @autoreleasepool {
  621. [loggerNode->_logger willRemoveLogger];
  622. } });
  623. }
  624. }
  625. // Remove all loggers from array
  626. [self._loggers removeAllObjects];
  627. }
  628. - (NSArray *)lt_allLoggers {
  629. NSAssert(dispatch_get_specific(GlobalLoggingQueueIdentityKey),
  630. @"This method should only be run on the logging thread/queue");
  631. NSMutableArray *theLoggers = [NSMutableArray new];
  632. for (AWSDDLoggerNode *loggerNode in self._loggers) {
  633. [theLoggers addObject:loggerNode->_logger];
  634. }
  635. return [theLoggers copy];
  636. }
  637. - (NSArray *)lt_allLoggersWithLevel {
  638. NSAssert(dispatch_get_specific(GlobalLoggingQueueIdentityKey),
  639. @"This method should only be run on the logging thread/queue");
  640. NSMutableArray *theLoggersWithLevel = [NSMutableArray new];
  641. for (AWSDDLoggerNode *loggerNode in self._loggers) {
  642. [theLoggersWithLevel addObject:[AWSDDLoggerInformation informationWithLogger:loggerNode->_logger
  643. andLevel:loggerNode->_level]];
  644. }
  645. return [theLoggersWithLevel copy];
  646. }
  647. - (void)lt_log:(AWSDDLogMessage *)logMessage {
  648. // Execute the given log message on each of our loggers.
  649. NSAssert(dispatch_get_specific(GlobalLoggingQueueIdentityKey),
  650. @"This method should only be run on the logging thread/queue");
  651. if (_numProcessors > 1) {
  652. // Execute each logger concurrently, each within its own queue.
  653. // All blocks are added to same group.
  654. // After each block has been queued, wait on group.
  655. //
  656. // The waiting ensures that a slow logger doesn't end up with a large queue of pending log messages.
  657. // This would defeat the purpose of the efforts we made earlier to restrict the max queue size.
  658. for (AWSDDLoggerNode *loggerNode in self._loggers) {
  659. // skip the loggers that shouldn't write this message based on the log level
  660. if (!(logMessage->_flag & loggerNode->_level)) {
  661. continue;
  662. }
  663. dispatch_group_async(_loggingGroup, loggerNode->_loggerQueue, ^{ @autoreleasepool {
  664. [loggerNode->_logger logMessage:logMessage];
  665. } });
  666. }
  667. dispatch_group_wait(_loggingGroup, DISPATCH_TIME_FOREVER);
  668. } else {
  669. // Execute each logger serialy, each within its own queue.
  670. for (AWSDDLoggerNode *loggerNode in self._loggers) {
  671. // skip the loggers that shouldn't write this message based on the log level
  672. if (!(logMessage->_flag & loggerNode->_level)) {
  673. continue;
  674. }
  675. dispatch_sync(loggerNode->_loggerQueue, ^{ @autoreleasepool {
  676. [loggerNode->_logger logMessage:logMessage];
  677. } });
  678. }
  679. }
  680. // If our queue got too big, there may be blocked threads waiting to add log messages to the queue.
  681. // Since we've now dequeued an item from the log, we may need to unblock the next thread.
  682. // We are using a counting semaphore provided by GCD.
  683. // The semaphore is initialized with our AWSDDLOG_MAX_QUEUE_SIZE value.
  684. // When a log message is queued this value is decremented.
  685. // When a log message is dequeued this value is incremented.
  686. // If the value ever drops below zero,
  687. // the queueing thread blocks and waits in FIFO order for us to signal it.
  688. //
  689. // A dispatch semaphore is an efficient implementation of a traditional counting semaphore.
  690. // Dispatch semaphores call down to the kernel only when the calling thread needs to be blocked.
  691. // If the calling semaphore does not need to block, no kernel call is made.
  692. dispatch_semaphore_signal(_queueSemaphore);
  693. }
  694. - (void)lt_flush {
  695. // All log statements issued before the flush method was invoked have now been executed.
  696. //
  697. // Now we need to propogate the flush request to any loggers that implement the flush method.
  698. // This is designed for loggers that buffer IO.
  699. NSAssert(dispatch_get_specific(GlobalLoggingQueueIdentityKey),
  700. @"This method should only be run on the logging thread/queue");
  701. for (AWSDDLoggerNode *loggerNode in self._loggers) {
  702. if ([loggerNode->_logger respondsToSelector:@selector(flush)]) {
  703. dispatch_group_async(_loggingGroup, loggerNode->_loggerQueue, ^{ @autoreleasepool {
  704. [loggerNode->_logger flush];
  705. } });
  706. }
  707. }
  708. dispatch_group_wait(_loggingGroup, DISPATCH_TIME_FOREVER);
  709. }
  710. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  711. #pragma mark Utilities
  712. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  713. NSString * __nullable AWSDDExtractFileNameWithoutExtension(const char *filePath, BOOL copy) {
  714. if (filePath == NULL) {
  715. return nil;
  716. }
  717. char *lastSlash = NULL;
  718. char *lastDot = NULL;
  719. char *p = (char *)filePath;
  720. while (*p != '\0') {
  721. if (*p == '/') {
  722. lastSlash = p;
  723. } else if (*p == '.') {
  724. lastDot = p;
  725. }
  726. p++;
  727. }
  728. char *subStr;
  729. NSUInteger subLen;
  730. if (lastSlash) {
  731. if (lastDot) {
  732. // lastSlash -> lastDot
  733. subStr = lastSlash + 1;
  734. subLen = (NSUInteger)(lastDot - subStr);
  735. } else {
  736. // lastSlash -> endOfString
  737. subStr = lastSlash + 1;
  738. subLen = (NSUInteger)(p - subStr);
  739. }
  740. } else {
  741. if (lastDot) {
  742. // startOfString -> lastDot
  743. subStr = (char *)filePath;
  744. subLen = (NSUInteger)(lastDot - subStr);
  745. } else {
  746. // startOfString -> endOfString
  747. subStr = (char *)filePath;
  748. subLen = (NSUInteger)(p - subStr);
  749. }
  750. }
  751. if (copy) {
  752. return [[NSString alloc] initWithBytes:subStr
  753. length:subLen
  754. encoding:NSUTF8StringEncoding];
  755. } else {
  756. // We can take advantage of the fact that __FILE__ is a string literal.
  757. // Specifically, we don't need to waste time copying the string.
  758. // We can just tell NSString to point to a range within the string literal.
  759. return [[NSString alloc] initWithBytesNoCopy:subStr
  760. length:subLen
  761. encoding:NSUTF8StringEncoding
  762. freeWhenDone:NO];
  763. }
  764. }
  765. @end
  766. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  767. #pragma mark -
  768. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  769. @implementation AWSDDLoggerNode
  770. - (instancetype)initWithLogger:(id <AWSDDLogger>)logger loggerQueue:(dispatch_queue_t)loggerQueue level:(AWSDDLogLevel)level {
  771. if ((self = [super init])) {
  772. _logger = logger;
  773. if (loggerQueue) {
  774. _loggerQueue = loggerQueue;
  775. #if !OS_OBJECT_USE_OBJC
  776. dispatch_retain(loggerQueue);
  777. #endif
  778. }
  779. _level = level;
  780. }
  781. return self;
  782. }
  783. + (AWSDDLoggerNode *)nodeWithLogger:(id <AWSDDLogger>)logger loggerQueue:(dispatch_queue_t)loggerQueue level:(AWSDDLogLevel)level {
  784. return [[AWSDDLoggerNode alloc] initWithLogger:logger loggerQueue:loggerQueue level:level];
  785. }
  786. - (void)dealloc {
  787. #if !OS_OBJECT_USE_OBJC
  788. if (_loggerQueue) {
  789. dispatch_release(_loggerQueue);
  790. }
  791. #endif
  792. }
  793. @end
  794. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  795. #pragma mark -
  796. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  797. @implementation AWSDDLogMessage
  798. // Can we use DISPATCH_CURRENT_QUEUE_LABEL ?
  799. // Can we use dispatch_get_current_queue (without it crashing) ?
  800. //
  801. // a) Compiling against newer SDK's (iOS 7+/OS X 10.9+) where DISPATCH_CURRENT_QUEUE_LABEL is defined
  802. // on a (iOS 7.0+/OS X 10.9+) runtime version
  803. //
  804. // b) Systems where dispatch_get_current_queue is not yet deprecated and won't crash (< iOS 6.0/OS X 10.9)
  805. //
  806. // dispatch_get_current_queue(void);
  807. // __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_6,__MAC_10_9,__IPHONE_4_0,__IPHONE_6_0)
  808. #if TARGET_OS_IOS
  809. // Compiling for iOS
  810. static BOOL _use_dispatch_current_queue_label;
  811. static BOOL _use_dispatch_get_current_queue;
  812. static void _dispatch_queue_label_init_once(void * __attribute__((unused)) context)
  813. {
  814. _use_dispatch_current_queue_label = (UIDevice.currentDevice.systemVersion.floatValue >= 7.0f);
  815. _use_dispatch_get_current_queue = (!_use_dispatch_current_queue_label && UIDevice.currentDevice.systemVersion.floatValue >= 6.1f);
  816. }
  817. static __inline__ __attribute__((__always_inline__)) void _dispatch_queue_label_init()
  818. {
  819. static dispatch_once_t onceToken;
  820. dispatch_once_f(&onceToken, NULL, _dispatch_queue_label_init_once);
  821. }
  822. #define USE_DISPATCH_CURRENT_QUEUE_LABEL (_dispatch_queue_label_init(), _use_dispatch_current_queue_label)
  823. #define USE_DISPATCH_GET_CURRENT_QUEUE (_dispatch_queue_label_init(), _use_dispatch_get_current_queue)
  824. #elif TARGET_OS_WATCH || TARGET_OS_TV
  825. // Compiling for watchOS, tvOS
  826. #define USE_DISPATCH_CURRENT_QUEUE_LABEL YES
  827. #define USE_DISPATCH_GET_CURRENT_QUEUE NO
  828. #else
  829. // Compiling for Mac OS X
  830. #ifndef MAC_OS_X_VERSION_10_9
  831. #define MAC_OS_X_VERSION_10_9 1090
  832. #endif
  833. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_9 // Mac OS X 10.9 or later required
  834. #define USE_DISPATCH_CURRENT_QUEUE_LABEL YES
  835. #define USE_DISPATCH_GET_CURRENT_QUEUE NO
  836. #else
  837. static BOOL _use_dispatch_current_queue_label;
  838. static BOOL _use_dispatch_get_current_queue;
  839. static void _dispatch_queue_label_init_once(void * __attribute__((unused)) context)
  840. {
  841. _use_dispatch_current_queue_label = [NSTimer instancesRespondToSelector : @selector(tolerance)]; // OS X 10.9+
  842. _use_dispatch_get_current_queue = !_use_dispatch_current_queue_label; // < OS X 10.9
  843. }
  844. static __inline__ __attribute__((__always_inline__)) void _dispatch_queue_label_init()
  845. {
  846. static dispatch_once_t onceToken;
  847. dispatch_once_f(&onceToken, NULL, _dispatch_queue_label_init_once);
  848. }
  849. #define USE_DISPATCH_CURRENT_QUEUE_LABEL (_dispatch_queue_label_init(), _use_dispatch_current_queue_label)
  850. #define USE_DISPATCH_GET_CURRENT_QUEUE (_dispatch_queue_label_init(), _use_dispatch_get_current_queue)
  851. #endif
  852. #endif /* if TARGET_OS_IOS */
  853. // Should we use pthread_threadid_np ?
  854. // With iOS 8+/OSX 10.10+ NSLog uses pthread_threadid_np instead of pthread_mach_thread_np
  855. #if TARGET_OS_IOS
  856. // Compiling for iOS
  857. #ifndef kCFCoreFoundationVersionNumber_iOS_8_0
  858. #define kCFCoreFoundationVersionNumber_iOS_8_0 1140.10
  859. #endif
  860. #define USE_PTHREAD_THREADID_NP (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_8_0)
  861. #elif TARGET_OS_WATCH || TARGET_OS_TV
  862. // Compiling for watchOS, tvOS
  863. #define USE_PTHREAD_THREADID_NP YES
  864. #else
  865. // Compiling for Mac OS X
  866. #ifndef kCFCoreFoundationVersionNumber10_10
  867. #define kCFCoreFoundationVersionNumber10_10 1151.16
  868. #endif
  869. #define USE_PTHREAD_THREADID_NP (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber10_10)
  870. #endif /* if TARGET_OS_IOS */
  871. - (instancetype)init {
  872. self = [super init];
  873. return self;
  874. }
  875. - (instancetype)initWithMessage:(NSString *)message
  876. level:(AWSDDLogLevel)level
  877. flag:(AWSDDLogFlag)flag
  878. context:(NSInteger)context
  879. file:(NSString *)file
  880. function:(NSString *)function
  881. line:(NSUInteger)line
  882. tag:(id)tag
  883. options:(AWSDDLogMessageOptions)options
  884. timestamp:(NSDate *)timestamp {
  885. if ((self = [super init])) {
  886. BOOL copyMessage = (options & AWSDDLogMessageDontCopyMessage) == 0;
  887. _message = copyMessage ? [message copy] : message;
  888. _level = level;
  889. _flag = flag;
  890. _context = context;
  891. BOOL copyFile = (options & AWSDDLogMessageCopyFile) != 0;
  892. _file = copyFile ? [file copy] : file;
  893. BOOL copyFunction = (options & AWSDDLogMessageCopyFunction) != 0;
  894. _function = copyFunction ? [function copy] : function;
  895. _line = line;
  896. _tag = tag;
  897. _options = options;
  898. _timestamp = timestamp ?: [NSDate new];
  899. if (USE_PTHREAD_THREADID_NP) {
  900. __uint64_t tid;
  901. pthread_threadid_np(NULL, &tid);
  902. _threadID = [[NSString alloc] initWithFormat:@"%llu", tid];
  903. } else {
  904. _threadID = [[NSString alloc] initWithFormat:@"%x", pthread_mach_thread_np(pthread_self())];
  905. }
  906. _threadName = NSThread.currentThread.name;
  907. // Get the file name without extension
  908. _fileName = [_file lastPathComponent];
  909. NSUInteger dotLocation = [_fileName rangeOfString:@"." options:NSBackwardsSearch].location;
  910. if (dotLocation != NSNotFound)
  911. {
  912. _fileName = [_fileName substringToIndex:dotLocation];
  913. }
  914. // Try to get the current queue's label
  915. if (USE_DISPATCH_CURRENT_QUEUE_LABEL) {
  916. _queueLabel = [[NSString alloc] initWithFormat:@"%s", dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL)];
  917. } else if (USE_DISPATCH_GET_CURRENT_QUEUE) {
  918. #pragma clang diagnostic push
  919. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  920. dispatch_queue_t currentQueue = dispatch_get_current_queue();
  921. #pragma clang diagnostic pop
  922. _queueLabel = [[NSString alloc] initWithFormat:@"%s", dispatch_queue_get_label(currentQueue)];
  923. } else {
  924. _queueLabel = @""; // iOS 6.x only
  925. }
  926. }
  927. return self;
  928. }
  929. - (id)copyWithZone:(NSZone * __attribute__((unused)))zone {
  930. AWSDDLogMessage *newMessage = [AWSDDLogMessage new];
  931. newMessage->_message = _message;
  932. newMessage->_level = _level;
  933. newMessage->_flag = _flag;
  934. newMessage->_context = _context;
  935. newMessage->_file = _file;
  936. newMessage->_fileName = _fileName;
  937. newMessage->_function = _function;
  938. newMessage->_line = _line;
  939. newMessage->_tag = _tag;
  940. newMessage->_options = _options;
  941. newMessage->_timestamp = _timestamp;
  942. newMessage->_threadID = _threadID;
  943. newMessage->_threadName = _threadName;
  944. newMessage->_queueLabel = _queueLabel;
  945. return newMessage;
  946. }
  947. @end
  948. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  949. #pragma mark -
  950. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  951. @implementation AWSDDAbstractLogger
  952. - (instancetype)init {
  953. if ((self = [super init])) {
  954. const char *loggerQueueName = NULL;
  955. if ([self respondsToSelector:@selector(loggerName)]) {
  956. loggerQueueName = [[self loggerName] UTF8String];
  957. }
  958. _loggerQueue = dispatch_queue_create(loggerQueueName, NULL);
  959. // We're going to use dispatch_queue_set_specific() to "mark" our loggerQueue.
  960. // Later we can use dispatch_get_specific() to determine if we're executing on our loggerQueue.
  961. // The documentation states:
  962. //
  963. // > Keys are only compared as pointers and are never dereferenced.
  964. // > Thus, you can use a pointer to a static variable for a specific subsystem or
  965. // > any other value that allows you to identify the value uniquely.
  966. // > Specifying a pointer to a string constant is not recommended.
  967. //
  968. // So we're going to use the very convenient key of "self",
  969. // which also works when multiple logger classes extend this class, as each will have a different "self" key.
  970. //
  971. // This is used primarily for thread-safety assertions (via the isOnInternalLoggerQueue method below).
  972. void *key = (__bridge void *)self;
  973. void *nonNullValue = (__bridge void *)self;
  974. dispatch_queue_set_specific(_loggerQueue, key, nonNullValue, NULL);
  975. }
  976. return self;
  977. }
  978. - (void)dealloc {
  979. #if !OS_OBJECT_USE_OBJC
  980. if (_loggerQueue) {
  981. dispatch_release(_loggerQueue);
  982. }
  983. #endif
  984. }
  985. - (void)logMessage:(AWSDDLogMessage * __attribute__((unused)))logMessage {
  986. // Override me
  987. }
  988. - (id <AWSDDLogFormatter>)logFormatter {
  989. // This method must be thread safe and intuitive.
  990. // Therefore if somebody executes the following code:
  991. //
  992. // [logger setLogFormatter:myFormatter];
  993. // formatter = [logger logFormatter];
  994. //
  995. // They would expect formatter to equal myFormatter.
  996. // This functionality must be ensured by the getter and setter method.
  997. //
  998. // The thread safety must not come at a cost to the performance of the logMessage method.
  999. // This method is likely called sporadically, while the logMessage method is called repeatedly.
  1000. // This means, the implementation of this method:
  1001. // - Must NOT require the logMessage method to acquire a lock.
  1002. // - Must NOT require the logMessage method to access an atomic property (also a lock of sorts).
  1003. //
  1004. // Thread safety is ensured by executing access to the formatter variable on the loggerQueue.
  1005. // This is the same queue that the logMessage method operates on.
  1006. //
  1007. // Note: The last time I benchmarked the performance of direct access vs atomic property access,
  1008. // direct access was over twice as fast on the desktop and over 6 times as fast on the iPhone.
  1009. //
  1010. // Furthermore, consider the following code:
  1011. //
  1012. // AWSDDLogVerbose(@"log msg 1");
  1013. // AWSDDLogVerbose(@"log msg 2");
  1014. // [logger setFormatter:myFormatter];
  1015. // AWSDDLogVerbose(@"log msg 3");
  1016. //
  1017. // Our intuitive requirement means that the new formatter will only apply to the 3rd log message.
  1018. // This must remain true even when using asynchronous logging.
  1019. // We must keep in mind the various queue's that are in play here:
  1020. //
  1021. // loggerQueue : Our own private internal queue that the logMessage method runs on.
  1022. // Operations are added to this queue from the global loggingQueue.
  1023. //
  1024. // globalLoggingQueue : The queue that all log messages go through before they arrive in our loggerQueue.
  1025. //
  1026. // All log statements go through the serial gloabalLoggingQueue before they arrive at our loggerQueue.
  1027. // Thus this method also goes through the serial globalLoggingQueue to ensure intuitive operation.
  1028. // IMPORTANT NOTE:
  1029. //
  1030. // Methods within the AWSDDLogger implementation MUST access the formatter ivar directly.
  1031. // This method is designed explicitly for external access.
  1032. //
  1033. // Using "self." syntax to go through this method will cause immediate deadlock.
  1034. // This is the intended result. Fix it by accessing the ivar directly.
  1035. // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster.
  1036. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  1037. NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax.");
  1038. dispatch_queue_t globalLoggingQueue = [AWSDDLog loggingQueue];
  1039. __block id <AWSDDLogFormatter> result;
  1040. dispatch_sync(globalLoggingQueue, ^{
  1041. dispatch_sync(self->_loggerQueue, ^{
  1042. result = self->_logFormatter;
  1043. });
  1044. });
  1045. return result;
  1046. }
  1047. - (void)setLogFormatter:(id <AWSDDLogFormatter>)logFormatter {
  1048. // The design of this method is documented extensively in the logFormatter message (above in code).
  1049. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  1050. NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax.");
  1051. dispatch_block_t block = ^{
  1052. @autoreleasepool {
  1053. if (self->_logFormatter != logFormatter) {
  1054. if ([self->_logFormatter respondsToSelector:@selector(willRemoveFromLogger:)]) {
  1055. [self->_logFormatter willRemoveFromLogger:self];
  1056. }
  1057. self->_logFormatter = logFormatter;
  1058. if ([self->_logFormatter respondsToSelector:@selector(didAddToLogger:inQueue:)]) {
  1059. [self->_logFormatter didAddToLogger:self inQueue:self->_loggerQueue];
  1060. } else if ([self->_logFormatter respondsToSelector:@selector(didAddToLogger:)]) {
  1061. [self->_logFormatter didAddToLogger:self];
  1062. }
  1063. }
  1064. }
  1065. };
  1066. dispatch_queue_t globalLoggingQueue = [AWSDDLog loggingQueue];
  1067. dispatch_async(globalLoggingQueue, ^{
  1068. dispatch_async(self->_loggerQueue, block);
  1069. });
  1070. }
  1071. - (dispatch_queue_t)loggerQueue {
  1072. return _loggerQueue;
  1073. }
  1074. - (NSString *)loggerName {
  1075. return NSStringFromClass([self class]);
  1076. }
  1077. - (BOOL)isOnGlobalLoggingQueue {
  1078. return (dispatch_get_specific(GlobalLoggingQueueIdentityKey) != NULL);
  1079. }
  1080. - (BOOL)isOnInternalLoggerQueue {
  1081. void *key = (__bridge void *)self;
  1082. return (dispatch_get_specific(key) != NULL);
  1083. }
  1084. @end
  1085. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1086. #pragma mark -
  1087. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1088. @interface AWSDDLoggerInformation()
  1089. {
  1090. // Direct accessors to be used only for performance
  1091. @public
  1092. id <AWSDDLogger> _logger;
  1093. AWSDDLogLevel _level;
  1094. }
  1095. @end
  1096. @implementation AWSDDLoggerInformation
  1097. - (instancetype)initWithLogger:(id <AWSDDLogger>)logger andLevel:(AWSDDLogLevel)level {
  1098. if ((self = [super init])) {
  1099. _logger = logger;
  1100. _level = level;
  1101. }
  1102. return self;
  1103. }
  1104. + (AWSDDLoggerInformation *)informationWithLogger:(id <AWSDDLogger>)logger andLevel:(AWSDDLogLevel)level {
  1105. return [[AWSDDLoggerInformation alloc] initWithLogger:logger andLevel:level];
  1106. }
  1107. @end