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_semaphore_wait(_queueSemaphore, DISPATCH_TIME_FOREVER);
  281. // We've now sure we won't overflow the queue.
  282. // It is time to queue our log message.
  283. dispatch_block_t logBlock = ^{
  284. @autoreleasepool {
  285. [self lt_log:logMessage];
  286. }
  287. };
  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. numClasses = 0;
  506. }
  507. }
  508. // We can now loop through the classes, and test each one to see if it is a DDLogging class.
  509. NSMutableArray *result = [NSMutableArray arrayWithCapacity:numClasses];
  510. for (NSUInteger i = 0; i < numClasses; i++) {
  511. Class class = classes[i];
  512. if ([self isRegisteredClass:class]) {
  513. [result addObject:class];
  514. }
  515. }
  516. free(classes);
  517. return result;
  518. }
  519. + (NSArray *)registeredClassNames {
  520. NSArray *registeredClasses = [self registeredClasses];
  521. NSMutableArray *result = [NSMutableArray arrayWithCapacity:[registeredClasses count]];
  522. for (Class class in registeredClasses) {
  523. [result addObject:NSStringFromClass(class)];
  524. }
  525. return result;
  526. }
  527. + (DDLogLevel)levelForClass:(Class)aClass {
  528. if ([self isRegisteredClass:aClass]) {
  529. return [aClass ddLogLevel];
  530. }
  531. return (DDLogLevel)-1;
  532. }
  533. + (DDLogLevel)levelForClassWithName:(NSString *)aClassName {
  534. Class aClass = NSClassFromString(aClassName);
  535. return [self levelForClass:aClass];
  536. }
  537. + (void)setLevel:(DDLogLevel)level forClass:(Class)aClass {
  538. if ([self isRegisteredClass:aClass]) {
  539. [aClass ddSetLogLevel:level];
  540. }
  541. }
  542. + (void)setLevel:(DDLogLevel)level forClassWithName:(NSString *)aClassName {
  543. Class aClass = NSClassFromString(aClassName);
  544. [self setLevel:level forClass:aClass];
  545. }
  546. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  547. #pragma mark Logging Thread
  548. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  549. - (void)lt_addLogger:(id <DDLogger>)logger level:(DDLogLevel)level {
  550. // Add to loggers array.
  551. // Need to create loggerQueue if loggerNode doesn't provide one.
  552. for (DDLoggerNode* node in self._loggers) {
  553. if (node->_logger == logger
  554. && node->_level == level) {
  555. // Exactly same logger already added, exit
  556. return;
  557. }
  558. }
  559. NSAssert(dispatch_get_specific(GlobalLoggingQueueIdentityKey),
  560. @"This method should only be run on the logging thread/queue");
  561. dispatch_queue_t loggerQueue = NULL;
  562. if ([logger respondsToSelector:@selector(loggerQueue)]) {
  563. // Logger may be providing its own queue
  564. loggerQueue = [logger loggerQueue];
  565. }
  566. if (loggerQueue == nil) {
  567. // Automatically create queue for the logger.
  568. // Use the logger name as the queue name if possible.
  569. const char *loggerQueueName = NULL;
  570. if ([logger respondsToSelector:@selector(loggerName)]) {
  571. loggerQueueName = [[logger loggerName] UTF8String];
  572. }
  573. loggerQueue = dispatch_queue_create(loggerQueueName, NULL);
  574. }
  575. DDLoggerNode *loggerNode = [DDLoggerNode nodeWithLogger:logger loggerQueue:loggerQueue level:level];
  576. [self._loggers addObject:loggerNode];
  577. if ([logger respondsToSelector:@selector(didAddLoggerInQueue:)]) {
  578. dispatch_async(loggerNode->_loggerQueue, ^{ @autoreleasepool {
  579. [logger didAddLoggerInQueue:loggerNode->_loggerQueue];
  580. } });
  581. } else if ([logger respondsToSelector:@selector(didAddLogger)]) {
  582. dispatch_async(loggerNode->_loggerQueue, ^{ @autoreleasepool {
  583. [logger didAddLogger];
  584. } });
  585. }
  586. }
  587. - (void)lt_removeLogger:(id <DDLogger>)logger {
  588. // Find associated loggerNode in list of added loggers
  589. NSAssert(dispatch_get_specific(GlobalLoggingQueueIdentityKey),
  590. @"This method should only be run on the logging thread/queue");
  591. DDLoggerNode *loggerNode = nil;
  592. for (DDLoggerNode *node in self._loggers) {
  593. if (node->_logger == logger) {
  594. loggerNode = node;
  595. break;
  596. }
  597. }
  598. if (loggerNode == nil) {
  599. NSLogDebug(@"DDLog: Request to remove logger which wasn't added");
  600. return;
  601. }
  602. // Notify logger
  603. if ([logger respondsToSelector:@selector(willRemoveLogger)]) {
  604. dispatch_async(loggerNode->_loggerQueue, ^{ @autoreleasepool {
  605. [logger willRemoveLogger];
  606. } });
  607. }
  608. // Remove from loggers array
  609. [self._loggers removeObject:loggerNode];
  610. }
  611. - (void)lt_removeAllLoggers {
  612. NSAssert(dispatch_get_specific(GlobalLoggingQueueIdentityKey),
  613. @"This method should only be run on the logging thread/queue");
  614. // Notify all loggers
  615. for (DDLoggerNode *loggerNode in self._loggers) {
  616. if ([loggerNode->_logger respondsToSelector:@selector(willRemoveLogger)]) {
  617. dispatch_async(loggerNode->_loggerQueue, ^{ @autoreleasepool {
  618. [loggerNode->_logger willRemoveLogger];
  619. } });
  620. }
  621. }
  622. // Remove all loggers from array
  623. [self._loggers removeAllObjects];
  624. }
  625. - (NSArray *)lt_allLoggers {
  626. NSAssert(dispatch_get_specific(GlobalLoggingQueueIdentityKey),
  627. @"This method should only be run on the logging thread/queue");
  628. NSMutableArray *theLoggers = [NSMutableArray new];
  629. for (DDLoggerNode *loggerNode in self._loggers) {
  630. [theLoggers addObject:loggerNode->_logger];
  631. }
  632. return [theLoggers copy];
  633. }
  634. - (NSArray *)lt_allLoggersWithLevel {
  635. NSAssert(dispatch_get_specific(GlobalLoggingQueueIdentityKey),
  636. @"This method should only be run on the logging thread/queue");
  637. NSMutableArray *theLoggersWithLevel = [NSMutableArray new];
  638. for (DDLoggerNode *loggerNode in self._loggers) {
  639. [theLoggersWithLevel addObject:[DDLoggerInformation informationWithLogger:loggerNode->_logger
  640. andLevel:loggerNode->_level]];
  641. }
  642. return [theLoggersWithLevel copy];
  643. }
  644. - (void)lt_log:(DDLogMessage *)logMessage {
  645. // Execute the given log message on each of our loggers.
  646. NSAssert(dispatch_get_specific(GlobalLoggingQueueIdentityKey),
  647. @"This method should only be run on the logging thread/queue");
  648. if (_numProcessors > 1) {
  649. // Execute each logger concurrently, each within its own queue.
  650. // All blocks are added to same group.
  651. // After each block has been queued, wait on group.
  652. //
  653. // The waiting ensures that a slow logger doesn't end up with a large queue of pending log messages.
  654. // This would defeat the purpose of the efforts we made earlier to restrict the max queue size.
  655. for (DDLoggerNode *loggerNode in self._loggers) {
  656. // skip the loggers that shouldn't write this message based on the log level
  657. if (!(logMessage->_flag & loggerNode->_level)) {
  658. continue;
  659. }
  660. dispatch_group_async(_loggingGroup, loggerNode->_loggerQueue, ^{ @autoreleasepool {
  661. [loggerNode->_logger logMessage:logMessage];
  662. } });
  663. }
  664. dispatch_group_wait(_loggingGroup, DISPATCH_TIME_FOREVER);
  665. } else {
  666. // Execute each logger serialy, each within its own queue.
  667. for (DDLoggerNode *loggerNode in self._loggers) {
  668. // skip the loggers that shouldn't write this message based on the log level
  669. if (!(logMessage->_flag & loggerNode->_level)) {
  670. continue;
  671. }
  672. dispatch_sync(loggerNode->_loggerQueue, ^{ @autoreleasepool {
  673. [loggerNode->_logger logMessage:logMessage];
  674. } });
  675. }
  676. }
  677. // If our queue got too big, there may be blocked threads waiting to add log messages to the queue.
  678. // Since we've now dequeued an item from the log, we may need to unblock the next thread.
  679. // We are using a counting semaphore provided by GCD.
  680. // The semaphore is initialized with our DDLOG_MAX_QUEUE_SIZE value.
  681. // When a log message is queued this value is decremented.
  682. // When a log message is dequeued this value is incremented.
  683. // If the value ever drops below zero,
  684. // the queueing thread blocks and waits in FIFO order for us to signal it.
  685. //
  686. // A dispatch semaphore is an efficient implementation of a traditional counting semaphore.
  687. // Dispatch semaphores call down to the kernel only when the calling thread needs to be blocked.
  688. // If the calling semaphore does not need to block, no kernel call is made.
  689. dispatch_semaphore_signal(_queueSemaphore);
  690. }
  691. - (void)lt_flush {
  692. // All log statements issued before the flush method was invoked have now been executed.
  693. //
  694. // Now we need to propogate the flush request to any loggers that implement the flush method.
  695. // This is designed for loggers that buffer IO.
  696. NSAssert(dispatch_get_specific(GlobalLoggingQueueIdentityKey),
  697. @"This method should only be run on the logging thread/queue");
  698. for (DDLoggerNode *loggerNode in self._loggers) {
  699. if ([loggerNode->_logger respondsToSelector:@selector(flush)]) {
  700. dispatch_group_async(_loggingGroup, loggerNode->_loggerQueue, ^{ @autoreleasepool {
  701. [loggerNode->_logger flush];
  702. } });
  703. }
  704. }
  705. dispatch_group_wait(_loggingGroup, DISPATCH_TIME_FOREVER);
  706. }
  707. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  708. #pragma mark Utilities
  709. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  710. NSString * __nullable DDExtractFileNameWithoutExtension(const char *filePath, BOOL copy) {
  711. if (filePath == NULL) {
  712. return nil;
  713. }
  714. char *lastSlash = NULL;
  715. char *lastDot = NULL;
  716. char *p = (char *)filePath;
  717. while (*p != '\0') {
  718. if (*p == '/') {
  719. lastSlash = p;
  720. } else if (*p == '.') {
  721. lastDot = p;
  722. }
  723. p++;
  724. }
  725. char *subStr;
  726. NSUInteger subLen;
  727. if (lastSlash) {
  728. if (lastDot) {
  729. // lastSlash -> lastDot
  730. subStr = lastSlash + 1;
  731. subLen = (NSUInteger)(lastDot - subStr);
  732. } else {
  733. // lastSlash -> endOfString
  734. subStr = lastSlash + 1;
  735. subLen = (NSUInteger)(p - subStr);
  736. }
  737. } else {
  738. if (lastDot) {
  739. // startOfString -> lastDot
  740. subStr = (char *)filePath;
  741. subLen = (NSUInteger)(lastDot - subStr);
  742. } else {
  743. // startOfString -> endOfString
  744. subStr = (char *)filePath;
  745. subLen = (NSUInteger)(p - subStr);
  746. }
  747. }
  748. if (copy) {
  749. return [[NSString alloc] initWithBytes:subStr
  750. length:subLen
  751. encoding:NSUTF8StringEncoding];
  752. } else {
  753. // We can take advantage of the fact that __FILE__ is a string literal.
  754. // Specifically, we don't need to waste time copying the string.
  755. // We can just tell NSString to point to a range within the string literal.
  756. return [[NSString alloc] initWithBytesNoCopy:subStr
  757. length:subLen
  758. encoding:NSUTF8StringEncoding
  759. freeWhenDone:NO];
  760. }
  761. }
  762. @end
  763. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  764. #pragma mark -
  765. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  766. @implementation DDLoggerNode
  767. - (instancetype)initWithLogger:(id <DDLogger>)logger loggerQueue:(dispatch_queue_t)loggerQueue level:(DDLogLevel)level {
  768. if ((self = [super init])) {
  769. _logger = logger;
  770. if (loggerQueue) {
  771. _loggerQueue = loggerQueue;
  772. #if !OS_OBJECT_USE_OBJC
  773. dispatch_retain(loggerQueue);
  774. #endif
  775. }
  776. _level = level;
  777. }
  778. return self;
  779. }
  780. + (DDLoggerNode *)nodeWithLogger:(id <DDLogger>)logger loggerQueue:(dispatch_queue_t)loggerQueue level:(DDLogLevel)level {
  781. return [[DDLoggerNode alloc] initWithLogger:logger loggerQueue:loggerQueue level:level];
  782. }
  783. - (void)dealloc {
  784. #if !OS_OBJECT_USE_OBJC
  785. if (_loggerQueue) {
  786. dispatch_release(_loggerQueue);
  787. }
  788. #endif
  789. }
  790. @end
  791. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  792. #pragma mark -
  793. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  794. @implementation DDLogMessage
  795. // Can we use DISPATCH_CURRENT_QUEUE_LABEL ?
  796. // Can we use dispatch_get_current_queue (without it crashing) ?
  797. //
  798. // a) Compiling against newer SDK's (iOS 7+/OS X 10.9+) where DISPATCH_CURRENT_QUEUE_LABEL is defined
  799. // on a (iOS 7.0+/OS X 10.9+) runtime version
  800. //
  801. // b) Systems where dispatch_get_current_queue is not yet deprecated and won't crash (< iOS 6.0/OS X 10.9)
  802. //
  803. // dispatch_get_current_queue(void);
  804. // __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_6,__MAC_10_9,__IPHONE_4_0,__IPHONE_6_0)
  805. #if TARGET_OS_IOS
  806. // Compiling for iOS
  807. static BOOL _use_dispatch_current_queue_label;
  808. static BOOL _use_dispatch_get_current_queue;
  809. static void _dispatch_queue_label_init_once(void * __attribute__((unused)) context)
  810. {
  811. _use_dispatch_current_queue_label = (UIDevice.currentDevice.systemVersion.floatValue >= 7.0f);
  812. _use_dispatch_get_current_queue = (!_use_dispatch_current_queue_label && UIDevice.currentDevice.systemVersion.floatValue >= 6.1f);
  813. }
  814. static __inline__ __attribute__((__always_inline__)) void _dispatch_queue_label_init()
  815. {
  816. static dispatch_once_t onceToken;
  817. dispatch_once_f(&onceToken, NULL, _dispatch_queue_label_init_once);
  818. }
  819. #define USE_DISPATCH_CURRENT_QUEUE_LABEL (_dispatch_queue_label_init(), _use_dispatch_current_queue_label)
  820. #define USE_DISPATCH_GET_CURRENT_QUEUE (_dispatch_queue_label_init(), _use_dispatch_get_current_queue)
  821. #elif TARGET_OS_WATCH || TARGET_OS_TV
  822. // Compiling for watchOS, tvOS
  823. #define USE_DISPATCH_CURRENT_QUEUE_LABEL YES
  824. #define USE_DISPATCH_GET_CURRENT_QUEUE NO
  825. #else
  826. // Compiling for Mac OS X
  827. #ifndef MAC_OS_X_VERSION_10_9
  828. #define MAC_OS_X_VERSION_10_9 1090
  829. #endif
  830. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_9 // Mac OS X 10.9 or later required
  831. #define USE_DISPATCH_CURRENT_QUEUE_LABEL YES
  832. #define USE_DISPATCH_GET_CURRENT_QUEUE NO
  833. #else
  834. static BOOL _use_dispatch_current_queue_label;
  835. static BOOL _use_dispatch_get_current_queue;
  836. static void _dispatch_queue_label_init_once(void * __attribute__((unused)) context)
  837. {
  838. _use_dispatch_current_queue_label = [NSTimer instancesRespondToSelector : @selector(tolerance)]; // OS X 10.9+
  839. _use_dispatch_get_current_queue = !_use_dispatch_current_queue_label; // < OS X 10.9
  840. }
  841. static __inline__ __attribute__((__always_inline__)) void _dispatch_queue_label_init()
  842. {
  843. static dispatch_once_t onceToken;
  844. dispatch_once_f(&onceToken, NULL, _dispatch_queue_label_init_once);
  845. }
  846. #define USE_DISPATCH_CURRENT_QUEUE_LABEL (_dispatch_queue_label_init(), _use_dispatch_current_queue_label)
  847. #define USE_DISPATCH_GET_CURRENT_QUEUE (_dispatch_queue_label_init(), _use_dispatch_get_current_queue)
  848. #endif
  849. #endif /* if TARGET_OS_IOS */
  850. // Should we use pthread_threadid_np ?
  851. // With iOS 8+/OSX 10.10+ NSLog uses pthread_threadid_np instead of pthread_mach_thread_np
  852. #if TARGET_OS_IOS
  853. // Compiling for iOS
  854. #ifndef kCFCoreFoundationVersionNumber_iOS_8_0
  855. #define kCFCoreFoundationVersionNumber_iOS_8_0 1140.10
  856. #endif
  857. #define USE_PTHREAD_THREADID_NP (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_8_0)
  858. #elif TARGET_OS_WATCH || TARGET_OS_TV
  859. // Compiling for watchOS, tvOS
  860. #define USE_PTHREAD_THREADID_NP YES
  861. #else
  862. // Compiling for Mac OS X
  863. #ifndef kCFCoreFoundationVersionNumber10_10
  864. #define kCFCoreFoundationVersionNumber10_10 1151.16
  865. #endif
  866. #define USE_PTHREAD_THREADID_NP (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber10_10)
  867. #endif /* if TARGET_OS_IOS */
  868. - (instancetype)init {
  869. self = [super init];
  870. return self;
  871. }
  872. - (instancetype)initWithMessage:(NSString *)message
  873. level:(DDLogLevel)level
  874. flag:(DDLogFlag)flag
  875. context:(NSInteger)context
  876. file:(NSString *)file
  877. function:(NSString *)function
  878. line:(NSUInteger)line
  879. tag:(id)tag
  880. options:(DDLogMessageOptions)options
  881. timestamp:(NSDate *)timestamp {
  882. if ((self = [super init])) {
  883. BOOL copyMessage = (options & DDLogMessageDontCopyMessage) == 0;
  884. _message = copyMessage ? [message copy] : message;
  885. _level = level;
  886. _flag = flag;
  887. _context = context;
  888. BOOL copyFile = (options & DDLogMessageCopyFile) != 0;
  889. _file = copyFile ? [file copy] : file;
  890. BOOL copyFunction = (options & DDLogMessageCopyFunction) != 0;
  891. _function = copyFunction ? [function copy] : function;
  892. _line = line;
  893. _tag = tag;
  894. _options = options;
  895. _timestamp = timestamp ?: [NSDate new];
  896. if (USE_PTHREAD_THREADID_NP) {
  897. __uint64_t tid;
  898. pthread_threadid_np(NULL, &tid);
  899. _threadID = [[NSString alloc] initWithFormat:@"%llu", tid];
  900. } else {
  901. _threadID = [[NSString alloc] initWithFormat:@"%x", pthread_mach_thread_np(pthread_self())];
  902. }
  903. _threadName = NSThread.currentThread.name;
  904. // Get the file name without extension
  905. _fileName = [_file lastPathComponent];
  906. NSUInteger dotLocation = [_fileName rangeOfString:@"." options:NSBackwardsSearch].location;
  907. if (dotLocation != NSNotFound)
  908. {
  909. _fileName = [_fileName substringToIndex:dotLocation];
  910. }
  911. // Try to get the current queue's label
  912. if (USE_DISPATCH_CURRENT_QUEUE_LABEL) {
  913. _queueLabel = [[NSString alloc] initWithFormat:@"%s", dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL)];
  914. } else if (USE_DISPATCH_GET_CURRENT_QUEUE) {
  915. #pragma clang diagnostic push
  916. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  917. dispatch_queue_t currentQueue = dispatch_get_current_queue();
  918. #pragma clang diagnostic pop
  919. _queueLabel = [[NSString alloc] initWithFormat:@"%s", dispatch_queue_get_label(currentQueue)];
  920. } else {
  921. _queueLabel = @""; // iOS 6.x only
  922. }
  923. }
  924. return self;
  925. }
  926. - (id)copyWithZone:(NSZone * __attribute__((unused)))zone {
  927. DDLogMessage *newMessage = [DDLogMessage new];
  928. newMessage->_message = _message;
  929. newMessage->_level = _level;
  930. newMessage->_flag = _flag;
  931. newMessage->_context = _context;
  932. newMessage->_file = _file;
  933. newMessage->_fileName = _fileName;
  934. newMessage->_function = _function;
  935. newMessage->_line = _line;
  936. newMessage->_tag = _tag;
  937. newMessage->_options = _options;
  938. newMessage->_timestamp = _timestamp;
  939. newMessage->_threadID = _threadID;
  940. newMessage->_threadName = _threadName;
  941. newMessage->_queueLabel = _queueLabel;
  942. return newMessage;
  943. }
  944. @end
  945. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  946. #pragma mark -
  947. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  948. @implementation DDAbstractLogger
  949. - (instancetype)init {
  950. if ((self = [super init])) {
  951. const char *loggerQueueName = NULL;
  952. if ([self respondsToSelector:@selector(loggerName)]) {
  953. loggerQueueName = [[self loggerName] UTF8String];
  954. }
  955. _loggerQueue = dispatch_queue_create(loggerQueueName, NULL);
  956. // We're going to use dispatch_queue_set_specific() to "mark" our loggerQueue.
  957. // Later we can use dispatch_get_specific() to determine if we're executing on our loggerQueue.
  958. // The documentation states:
  959. //
  960. // > Keys are only compared as pointers and are never dereferenced.
  961. // > Thus, you can use a pointer to a static variable for a specific subsystem or
  962. // > any other value that allows you to identify the value uniquely.
  963. // > Specifying a pointer to a string constant is not recommended.
  964. //
  965. // So we're going to use the very convenient key of "self",
  966. // which also works when multiple logger classes extend this class, as each will have a different "self" key.
  967. //
  968. // This is used primarily for thread-safety assertions (via the isOnInternalLoggerQueue method below).
  969. void *key = (__bridge void *)self;
  970. void *nonNullValue = (__bridge void *)self;
  971. dispatch_queue_set_specific(_loggerQueue, key, nonNullValue, NULL);
  972. }
  973. return self;
  974. }
  975. - (void)dealloc {
  976. #if !OS_OBJECT_USE_OBJC
  977. if (_loggerQueue) {
  978. dispatch_release(_loggerQueue);
  979. }
  980. #endif
  981. }
  982. - (void)logMessage:(DDLogMessage * __attribute__((unused)))logMessage {
  983. // Override me
  984. }
  985. - (id <DDLogFormatter>)logFormatter {
  986. // This method must be thread safe and intuitive.
  987. // Therefore if somebody executes the following code:
  988. //
  989. // [logger setLogFormatter:myFormatter];
  990. // formatter = [logger logFormatter];
  991. //
  992. // They would expect formatter to equal myFormatter.
  993. // This functionality must be ensured by the getter and setter method.
  994. //
  995. // The thread safety must not come at a cost to the performance of the logMessage method.
  996. // This method is likely called sporadically, while the logMessage method is called repeatedly.
  997. // This means, the implementation of this method:
  998. // - Must NOT require the logMessage method to acquire a lock.
  999. // - Must NOT require the logMessage method to access an atomic property (also a lock of sorts).
  1000. //
  1001. // Thread safety is ensured by executing access to the formatter variable on the loggerQueue.
  1002. // This is the same queue that the logMessage method operates on.
  1003. //
  1004. // Note: The last time I benchmarked the performance of direct access vs atomic property access,
  1005. // direct access was over twice as fast on the desktop and over 6 times as fast on the iPhone.
  1006. //
  1007. // Furthermore, consider the following code:
  1008. //
  1009. // DDLogVerbose(@"log msg 1");
  1010. // DDLogVerbose(@"log msg 2");
  1011. // [logger setFormatter:myFormatter];
  1012. // DDLogVerbose(@"log msg 3");
  1013. //
  1014. // Our intuitive requirement means that the new formatter will only apply to the 3rd log message.
  1015. // This must remain true even when using asynchronous logging.
  1016. // We must keep in mind the various queue's that are in play here:
  1017. //
  1018. // loggerQueue : Our own private internal queue that the logMessage method runs on.
  1019. // Operations are added to this queue from the global loggingQueue.
  1020. //
  1021. // globalLoggingQueue : The queue that all log messages go through before they arrive in our loggerQueue.
  1022. //
  1023. // All log statements go through the serial gloabalLoggingQueue before they arrive at our loggerQueue.
  1024. // Thus this method also goes through the serial globalLoggingQueue to ensure intuitive operation.
  1025. // IMPORTANT NOTE:
  1026. //
  1027. // Methods within the DDLogger implementation MUST access the formatter ivar directly.
  1028. // This method is designed explicitly for external access.
  1029. //
  1030. // Using "self." syntax to go through this method will cause immediate deadlock.
  1031. // This is the intended result. Fix it by accessing the ivar directly.
  1032. // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster.
  1033. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  1034. NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax.");
  1035. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  1036. __block id <DDLogFormatter> result;
  1037. dispatch_sync(globalLoggingQueue, ^{
  1038. dispatch_sync(_loggerQueue, ^{
  1039. result = _logFormatter;
  1040. });
  1041. });
  1042. return result;
  1043. }
  1044. - (void)setLogFormatter:(id <DDLogFormatter>)logFormatter {
  1045. // The design of this method is documented extensively in the logFormatter message (above in code).
  1046. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  1047. NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax.");
  1048. dispatch_block_t block = ^{
  1049. @autoreleasepool {
  1050. if (_logFormatter != logFormatter) {
  1051. if ([_logFormatter respondsToSelector:@selector(willRemoveFromLogger:)]) {
  1052. [_logFormatter willRemoveFromLogger:self];
  1053. }
  1054. _logFormatter = logFormatter;
  1055. if ([_logFormatter respondsToSelector:@selector(didAddToLogger:inQueue:)]) {
  1056. [_logFormatter didAddToLogger:self inQueue:_loggerQueue];
  1057. } else if ([_logFormatter respondsToSelector:@selector(didAddToLogger:)]) {
  1058. [_logFormatter didAddToLogger:self];
  1059. }
  1060. }
  1061. }
  1062. };
  1063. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  1064. dispatch_async(globalLoggingQueue, ^{
  1065. dispatch_async(_loggerQueue, block);
  1066. });
  1067. }
  1068. - (dispatch_queue_t)loggerQueue {
  1069. return _loggerQueue;
  1070. }
  1071. - (NSString *)loggerName {
  1072. return NSStringFromClass([self class]);
  1073. }
  1074. - (BOOL)isOnGlobalLoggingQueue {
  1075. return (dispatch_get_specific(GlobalLoggingQueueIdentityKey) != NULL);
  1076. }
  1077. - (BOOL)isOnInternalLoggerQueue {
  1078. void *key = (__bridge void *)self;
  1079. return (dispatch_get_specific(key) != NULL);
  1080. }
  1081. @end
  1082. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1083. #pragma mark -
  1084. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1085. @interface DDLoggerInformation()
  1086. {
  1087. // Direct accessors to be used only for performance
  1088. @public
  1089. id <DDLogger> _logger;
  1090. DDLogLevel _level;
  1091. }
  1092. @end
  1093. @implementation DDLoggerInformation
  1094. - (instancetype)initWithLogger:(id <DDLogger>)logger andLevel:(DDLogLevel)level {
  1095. if ((self = [super init])) {
  1096. _logger = logger;
  1097. _level = level;
  1098. }
  1099. return self;
  1100. }
  1101. + (DDLoggerInformation *)informationWithLogger:(id <DDLogger>)logger andLevel:(DDLogLevel)level {
  1102. return [[DDLoggerInformation alloc] initWithLogger:logger andLevel:level];
  1103. }
  1104. @end