DDLog.m 43 KB

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