DDLog.m 47 KB

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