DDDispatchQueueLogFormatter.m 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. #import "DDDispatchQueueLogFormatter.h"
  16. #import <pthread/pthread.h>
  17. #import <objc/runtime.h>
  18. #if !__has_feature(objc_arc)
  19. #error This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
  20. #endif
  21. #pragma mark - DDDispatchQueueLogFormatter
  22. @interface DDDispatchQueueLogFormatter () {
  23. DDDispatchQueueLogFormatterMode _mode;
  24. NSString *_dateFormatterKey;
  25. DDAtomicCounter *_atomicLoggerCounter;
  26. NSDateFormatter *_threadUnsafeDateFormatter; // Use [self stringFromDate]
  27. pthread_mutex_t _mutex;
  28. NSUInteger _minQueueLength; // _prefix == Only access via atomic property
  29. NSUInteger _maxQueueLength; // _prefix == Only access via atomic property
  30. NSMutableDictionary *_replacements; // _prefix == Only access from within spinlock
  31. }
  32. @end
  33. @implementation DDDispatchQueueLogFormatter
  34. - (instancetype)init {
  35. if ((self = [super init])) {
  36. _mode = DDDispatchQueueLogFormatterModeShareble;
  37. // We need to carefully pick the name for storing in thread dictionary to not
  38. // use a formatter configured by subclass and avoid surprises.
  39. Class cls = [self class];
  40. Class superClass = class_getSuperclass(cls);
  41. SEL configMethodName = @selector(configureDateFormatter:);
  42. Method configMethod = class_getInstanceMethod(cls, configMethodName);
  43. while (class_getInstanceMethod(superClass, configMethodName) == configMethod) {
  44. cls = superClass;
  45. superClass = class_getSuperclass(cls);
  46. }
  47. // now `cls` is the class that provides implementation for `configureDateFormatter:`
  48. _dateFormatterKey = [NSString stringWithFormat:@"%s_NSDateFormatter", class_getName(cls)];
  49. _atomicLoggerCounter = [[DDAtomicCounter alloc] initWithDefaultValue:0];
  50. _threadUnsafeDateFormatter = nil;
  51. _minQueueLength = 0;
  52. _maxQueueLength = 0;
  53. pthread_mutex_init(&_mutex, NULL);
  54. _replacements = [[NSMutableDictionary alloc] init];
  55. // Set default replacements:
  56. _replacements[@"com.apple.main-thread"] = @"main";
  57. }
  58. return self;
  59. }
  60. - (instancetype)initWithMode:(DDDispatchQueueLogFormatterMode)mode {
  61. if ((self = [self init])) {
  62. _mode = mode;
  63. }
  64. return self;
  65. }
  66. - (void)dealloc {
  67. pthread_mutex_destroy(&_mutex);
  68. }
  69. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  70. #pragma mark Configuration
  71. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  72. @synthesize minQueueLength = _minQueueLength;
  73. @synthesize maxQueueLength = _maxQueueLength;
  74. - (NSString *)replacementStringForQueueLabel:(NSString *)longLabel {
  75. NSString *result = nil;
  76. pthread_mutex_lock(&_mutex);
  77. {
  78. result = _replacements[longLabel];
  79. }
  80. pthread_mutex_unlock(&_mutex);
  81. return result;
  82. }
  83. - (void)setReplacementString:(NSString *)shortLabel forQueueLabel:(NSString *)longLabel {
  84. pthread_mutex_lock(&_mutex);
  85. {
  86. if (shortLabel) {
  87. _replacements[longLabel] = shortLabel;
  88. } else {
  89. [_replacements removeObjectForKey:longLabel];
  90. }
  91. }
  92. pthread_mutex_unlock(&_mutex);
  93. }
  94. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  95. #pragma mark DDLogFormatter
  96. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  97. - (NSDateFormatter *)createDateFormatter {
  98. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  99. [self configureDateFormatter:formatter];
  100. return formatter;
  101. }
  102. - (void)configureDateFormatter:(NSDateFormatter *)dateFormatter {
  103. [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
  104. [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss:SSS"];
  105. [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
  106. NSString *calendarIdentifier = NSCalendarIdentifierGregorian;
  107. [dateFormatter setCalendar:[[NSCalendar alloc] initWithCalendarIdentifier:calendarIdentifier]];
  108. }
  109. - (NSString *)stringFromDate:(NSDate *)date {
  110. NSDateFormatter *dateFormatter = nil;
  111. if (_mode == DDDispatchQueueLogFormatterModeNonShareble) {
  112. // Single-threaded mode.
  113. dateFormatter = _threadUnsafeDateFormatter;
  114. if (dateFormatter == nil) {
  115. dateFormatter = [self createDateFormatter];
  116. _threadUnsafeDateFormatter = dateFormatter;
  117. }
  118. } else {
  119. // Multi-threaded mode.
  120. // NSDateFormatter is NOT thread-safe.
  121. NSString *key = _dateFormatterKey;
  122. NSMutableDictionary *threadDictionary = [[NSThread currentThread] threadDictionary];
  123. dateFormatter = threadDictionary[key];
  124. if (dateFormatter == nil) {
  125. dateFormatter = [self createDateFormatter];
  126. threadDictionary[key] = dateFormatter;
  127. }
  128. }
  129. return [dateFormatter stringFromDate:date];
  130. }
  131. - (NSString *)queueThreadLabelForLogMessage:(DDLogMessage *)logMessage {
  132. // As per the DDLogFormatter contract, this method is always invoked on the same thread/dispatch_queue
  133. NSUInteger minQueueLength = self.minQueueLength;
  134. NSUInteger maxQueueLength = self.maxQueueLength;
  135. // Get the name of the queue, thread, or machID (whichever we are to use).
  136. NSString *queueThreadLabel = nil;
  137. BOOL useQueueLabel = YES;
  138. BOOL useThreadName = NO;
  139. if (logMessage->_queueLabel) {
  140. // If you manually create a thread, it's dispatch_queue will have one of the thread names below.
  141. // Since all such threads have the same name, we'd prefer to use the threadName or the machThreadID.
  142. NSArray *names = @[
  143. @"com.apple.root.low-priority",
  144. @"com.apple.root.default-priority",
  145. @"com.apple.root.high-priority",
  146. @"com.apple.root.low-overcommit-priority",
  147. @"com.apple.root.default-overcommit-priority",
  148. @"com.apple.root.high-overcommit-priority",
  149. @"com.apple.root.default-qos.overcommit"
  150. ];
  151. for (NSString * name in names) {
  152. if ([logMessage->_queueLabel isEqualToString:name]) {
  153. useQueueLabel = NO;
  154. useThreadName = [logMessage->_threadName length] > 0;
  155. break;
  156. }
  157. }
  158. } else {
  159. useQueueLabel = NO;
  160. useThreadName = [logMessage->_threadName length] > 0;
  161. }
  162. if (useQueueLabel || useThreadName) {
  163. NSString *fullLabel;
  164. NSString *abrvLabel;
  165. if (useQueueLabel) {
  166. fullLabel = logMessage->_queueLabel;
  167. } else {
  168. fullLabel = logMessage->_threadName;
  169. }
  170. pthread_mutex_lock(&_mutex);
  171. {
  172. abrvLabel = _replacements[fullLabel];
  173. }
  174. pthread_mutex_unlock(&_mutex);
  175. if (abrvLabel) {
  176. queueThreadLabel = abrvLabel;
  177. } else {
  178. queueThreadLabel = fullLabel;
  179. }
  180. } else {
  181. queueThreadLabel = logMessage->_threadID;
  182. }
  183. // Now use the thread label in the output
  184. NSUInteger labelLength = [queueThreadLabel length];
  185. // labelLength > maxQueueLength : truncate
  186. // labelLength < minQueueLength : padding
  187. // : exact
  188. if ((maxQueueLength > 0) && (labelLength > maxQueueLength)) {
  189. // Truncate
  190. return [queueThreadLabel substringToIndex:maxQueueLength];
  191. } else if (labelLength < minQueueLength) {
  192. // Padding
  193. NSUInteger numSpaces = minQueueLength - labelLength;
  194. char spaces[numSpaces + 1];
  195. memset(spaces, ' ', numSpaces);
  196. spaces[numSpaces] = '\0';
  197. return [NSString stringWithFormat:@"%@%s", queueThreadLabel, spaces];
  198. } else {
  199. // Exact
  200. return queueThreadLabel;
  201. }
  202. }
  203. - (NSString *)formatLogMessage:(DDLogMessage *)logMessage {
  204. NSString *timestamp = [self stringFromDate:(logMessage->_timestamp)];
  205. NSString *queueThreadLabel = [self queueThreadLabelForLogMessage:logMessage];
  206. return [NSString stringWithFormat:@"%@ [%@] %@", timestamp, queueThreadLabel, logMessage->_message];
  207. }
  208. - (void)didAddToLogger:(id <DDLogger> __attribute__((unused)))logger {
  209. NSAssert([_atomicLoggerCounter increment] <= 1 || _mode == DDDispatchQueueLogFormatterModeShareble, @"Can't reuse formatter with multiple loggers in non-shareable mode.");
  210. }
  211. - (void)willRemoveFromLogger:(id <DDLogger> __attribute__((unused)))logger {
  212. [_atomicLoggerCounter decrement];
  213. }
  214. @end
  215. #pragma mark - DDAtomicCounter
  216. #define DD_OSATOMIC_API_DEPRECATED (TARGET_OS_OSX && MAC_OS_X_VERSION_MIN_REQUIRED >= 101200) || (TARGET_OS_IOS && __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000) || (TARGET_OS_WATCH && __WATCH_OS_VERSION_MIN_REQUIRED >= 30000) || (TARGET_OS_TV && __TV_OS_VERSION_MIN_REQUIRED >= 100000)
  217. #if DD_OSATOMIC_API_DEPRECATED
  218. #import <stdatomic.h>
  219. #else
  220. #import <libkern/OSAtomic.h>
  221. #endif
  222. @interface DDAtomicCounter() {
  223. #if DD_OSATOMIC_API_DEPRECATED
  224. _Atomic(int32_t) _value;
  225. #else
  226. int32_t _value;
  227. #endif
  228. }
  229. @end
  230. @implementation DDAtomicCounter
  231. - (instancetype)initWithDefaultValue:(int32_t)defaultValue {
  232. if ((self = [super init])) {
  233. _value = defaultValue;
  234. }
  235. return self;
  236. }
  237. - (int32_t)value {
  238. return _value;
  239. }
  240. #if DD_OSATOMIC_API_DEPRECATED
  241. - (int32_t)increment {
  242. atomic_fetch_add_explicit(&_value, 1, memory_order_relaxed);
  243. return _value;
  244. }
  245. - (int32_t)decrement {
  246. atomic_fetch_sub_explicit(&_value, 1, memory_order_relaxed);
  247. return _value;
  248. }
  249. #else
  250. - (int32_t)increment {
  251. return OSAtomicIncrement32(&_value);
  252. }
  253. - (int32_t)decrement {
  254. return OSAtomicDecrement32(&_value);
  255. }
  256. #endif
  257. @end