You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

1154 lines
40 KiB

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