DDDispatchQueueLogFormatter.m 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. // Software License Agreement (BSD License)
  2. //
  3. // Copyright (c) 2010-2016, Deusty, LLC
  4. // All rights reserved.
  5. //
  6. // Redistribution and use of this software in source and binary forms,
  7. // with or without modification, are permitted provided that the following conditions are met:
  8. //
  9. // * Redistributions of source code must retain the above copyright notice,
  10. // this list of conditions and the following disclaimer.
  11. //
  12. // * Neither the name of Deusty nor the names of its contributors may be used
  13. // to endorse or promote products derived from this software without specific
  14. // prior written permission of Deusty, LLC.
  15. #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. @interface DDDispatchQueueLogFormatter () {
  22. DDDispatchQueueLogFormatterMode _mode;
  23. NSString *_dateFormatterKey;
  24. int32_t _atomicLoggerCount;
  25. NSDateFormatter *_threadUnsafeDateFormatter; // Use [self stringFromDate]
  26. pthread_mutex_t _mutex;
  27. NSUInteger _minQueueLength; // _prefix == Only access via atomic property
  28. NSUInteger _maxQueueLength; // _prefix == Only access via atomic property
  29. NSMutableDictionary *_replacements; // _prefix == Only access from within spinlock
  30. }
  31. @end
  32. @implementation DDDispatchQueueLogFormatter
  33. - (instancetype)init {
  34. if ((self = [super init])) {
  35. _mode = DDDispatchQueueLogFormatterModeShareble;
  36. // We need to carefully pick the name for storing in thread dictionary to not
  37. // use a formatter configured by subclass and avoid surprises.
  38. Class cls = [self class];
  39. Class superClass = class_getSuperclass(cls);
  40. SEL configMethodName = @selector(configureDateFormatter:);
  41. Method configMethod = class_getInstanceMethod(cls, configMethodName);
  42. while (class_getInstanceMethod(superClass, configMethodName) == configMethod) {
  43. cls = superClass;
  44. superClass = class_getSuperclass(cls);
  45. }
  46. // now `cls` is the class that provides implementation for `configureDateFormatter:`
  47. _dateFormatterKey = [NSString stringWithFormat:@"%s_NSDateFormatter", class_getName(cls)];
  48. _atomicLoggerCount = 0;
  49. _threadUnsafeDateFormatter = nil;
  50. _minQueueLength = 0;
  51. _maxQueueLength = 0;
  52. pthread_mutex_init(&_mutex, NULL);
  53. _replacements = [[NSMutableDictionary alloc] init];
  54. // Set default replacements:
  55. _replacements[@"com.apple.main-thread"] = @"main";
  56. }
  57. return self;
  58. }
  59. - (instancetype)initWithMode:(DDDispatchQueueLogFormatterMode)mode {
  60. if ((self = [self init])) {
  61. _mode = mode;
  62. }
  63. return self;
  64. }
  65. - (void)dealloc {
  66. pthread_mutex_destroy(&_mutex);
  67. }
  68. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  69. #pragma mark Configuration
  70. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  71. @synthesize minQueueLength = _minQueueLength;
  72. @synthesize maxQueueLength = _maxQueueLength;
  73. - (NSString *)replacementStringForQueueLabel:(NSString *)longLabel {
  74. NSString *result = nil;
  75. pthread_mutex_lock(&_mutex);
  76. {
  77. result = _replacements[longLabel];
  78. }
  79. pthread_mutex_unlock(&_mutex);
  80. return result;
  81. }
  82. - (void)setReplacementString:(NSString *)shortLabel forQueueLabel:(NSString *)longLabel {
  83. pthread_mutex_lock(&_mutex);
  84. {
  85. if (shortLabel) {
  86. _replacements[longLabel] = shortLabel;
  87. } else {
  88. [_replacements removeObjectForKey:longLabel];
  89. }
  90. }
  91. pthread_mutex_unlock(&_mutex);
  92. }
  93. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  94. #pragma mark DDLogFormatter
  95. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  96. - (NSDateFormatter *)createDateFormatter {
  97. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  98. [self configureDateFormatter:formatter];
  99. return formatter;
  100. }
  101. - (void)configureDateFormatter:(NSDateFormatter *)dateFormatter {
  102. [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
  103. [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss:SSS"];
  104. [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
  105. NSString *calendarIdentifier = nil;
  106. #if defined(__IPHONE_8_0) || defined(__MAC_10_10)
  107. calendarIdentifier = NSCalendarIdentifierGregorian;
  108. #else
  109. calendarIdentifier = NSGregorianCalendar;
  110. #endif
  111. [dateFormatter setCalendar:[[NSCalendar alloc] initWithCalendarIdentifier:calendarIdentifier]];
  112. }
  113. - (NSString *)stringFromDate:(NSDate *)date {
  114. NSDateFormatter *dateFormatter = nil;
  115. if (_mode == DDDispatchQueueLogFormatterModeNonShareble) {
  116. // Single-threaded mode.
  117. dateFormatter = _threadUnsafeDateFormatter;
  118. if (dateFormatter == nil) {
  119. dateFormatter = [self createDateFormatter];
  120. _threadUnsafeDateFormatter = dateFormatter;
  121. }
  122. } else {
  123. // Multi-threaded mode.
  124. // NSDateFormatter is NOT thread-safe.
  125. NSString *key = _dateFormatterKey;
  126. NSMutableDictionary *threadDictionary = [[NSThread currentThread] threadDictionary];
  127. dateFormatter = threadDictionary[key];
  128. if (dateFormatter == nil) {
  129. dateFormatter = [self createDateFormatter];
  130. threadDictionary[key] = dateFormatter;
  131. }
  132. }
  133. return [dateFormatter stringFromDate:date];
  134. }
  135. - (NSString *)queueThreadLabelForLogMessage:(DDLogMessage *)logMessage {
  136. // As per the DDLogFormatter contract, this method is always invoked on the same thread/dispatch_queue
  137. NSUInteger minQueueLength = self.minQueueLength;
  138. NSUInteger maxQueueLength = self.maxQueueLength;
  139. // Get the name of the queue, thread, or machID (whichever we are to use).
  140. NSString *queueThreadLabel = nil;
  141. BOOL useQueueLabel = YES;
  142. BOOL useThreadName = NO;
  143. if (logMessage->_queueLabel) {
  144. // If you manually create a thread, it's dispatch_queue will have one of the thread names below.
  145. // Since all such threads have the same name, we'd prefer to use the threadName or the machThreadID.
  146. NSArray *names = @[
  147. @"com.apple.root.low-priority",
  148. @"com.apple.root.default-priority",
  149. @"com.apple.root.high-priority",
  150. @"com.apple.root.low-overcommit-priority",
  151. @"com.apple.root.default-overcommit-priority",
  152. @"com.apple.root.high-overcommit-priority"
  153. ];
  154. for (NSString * name in names) {
  155. if ([logMessage->_queueLabel isEqualToString:name]) {
  156. useQueueLabel = NO;
  157. useThreadName = [logMessage->_threadName length] > 0;
  158. break;
  159. }
  160. }
  161. } else {
  162. useQueueLabel = NO;
  163. useThreadName = [logMessage->_threadName length] > 0;
  164. }
  165. if (useQueueLabel || useThreadName) {
  166. NSString *fullLabel;
  167. NSString *abrvLabel;
  168. if (useQueueLabel) {
  169. fullLabel = logMessage->_queueLabel;
  170. } else {
  171. fullLabel = logMessage->_threadName;
  172. }
  173. pthread_mutex_lock(&_mutex);
  174. {
  175. abrvLabel = _replacements[fullLabel];
  176. }
  177. pthread_mutex_unlock(&_mutex);
  178. if (abrvLabel) {
  179. queueThreadLabel = abrvLabel;
  180. } else {
  181. queueThreadLabel = fullLabel;
  182. }
  183. } else {
  184. queueThreadLabel = logMessage->_threadID;
  185. }
  186. // Now use the thread label in the output
  187. NSUInteger labelLength = [queueThreadLabel length];
  188. // labelLength > maxQueueLength : truncate
  189. // labelLength < minQueueLength : padding
  190. // : exact
  191. if ((maxQueueLength > 0) && (labelLength > maxQueueLength)) {
  192. // Truncate
  193. return [queueThreadLabel substringToIndex:maxQueueLength];
  194. } else if (labelLength < minQueueLength) {
  195. // Padding
  196. NSUInteger numSpaces = minQueueLength - labelLength;
  197. char spaces[numSpaces + 1];
  198. memset(spaces, ' ', numSpaces);
  199. spaces[numSpaces] = '\0';
  200. return [NSString stringWithFormat:@"%@%s", queueThreadLabel, spaces];
  201. } else {
  202. // Exact
  203. return queueThreadLabel;
  204. }
  205. }
  206. - (NSString *)formatLogMessage:(DDLogMessage *)logMessage {
  207. NSString *timestamp = [self stringFromDate:(logMessage->_timestamp)];
  208. NSString *queueThreadLabel = [self queueThreadLabelForLogMessage:logMessage];
  209. return [NSString stringWithFormat:@"%@ [%@] %@", timestamp, queueThreadLabel, logMessage->_message];
  210. }
  211. - (void)didAddToLogger:(id <DDLogger> __attribute__((unused)))logger {
  212. int32_t count = 0;
  213. count = OSAtomicIncrement32(&_atomicLoggerCount);
  214. NSAssert(count <= 1 || _mode == DDDispatchQueueLogFormatterModeShareble, @"Can't reuse formatter with multiple loggers in non-shareable mode.");
  215. }
  216. - (void)willRemoveFromLogger:(id <DDLogger> __attribute__((unused)))logger {
  217. OSAtomicDecrement32(&_atomicLoggerCount);
  218. }
  219. @end