DDDispatchQueueLogFormatter.m 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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 <libkern/OSAtomic.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. OSSpinLock _lock;
  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. _lock = OS_SPINLOCK_INIT;
  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. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  66. #pragma mark Configuration
  67. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  68. @synthesize minQueueLength = _minQueueLength;
  69. @synthesize maxQueueLength = _maxQueueLength;
  70. - (NSString *)replacementStringForQueueLabel:(NSString *)longLabel {
  71. NSString *result = nil;
  72. OSSpinLockLock(&_lock);
  73. {
  74. result = _replacements[longLabel];
  75. }
  76. OSSpinLockUnlock(&_lock);
  77. return result;
  78. }
  79. - (void)setReplacementString:(NSString *)shortLabel forQueueLabel:(NSString *)longLabel {
  80. OSSpinLockLock(&_lock);
  81. {
  82. if (shortLabel) {
  83. _replacements[longLabel] = shortLabel;
  84. } else {
  85. [_replacements removeObjectForKey:longLabel];
  86. }
  87. }
  88. OSSpinLockUnlock(&_lock);
  89. }
  90. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  91. #pragma mark DDLogFormatter
  92. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  93. - (NSDateFormatter *)createDateFormatter {
  94. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  95. [self configureDateFormatter:formatter];
  96. return formatter;
  97. }
  98. - (void)configureDateFormatter:(NSDateFormatter *)dateFormatter {
  99. [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
  100. [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss:SSS"];
  101. [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
  102. NSString *calendarIdentifier = nil;
  103. #if defined(__IPHONE_8_0) || defined(__MAC_10_10)
  104. calendarIdentifier = NSCalendarIdentifierGregorian;
  105. #else
  106. calendarIdentifier = NSGregorianCalendar;
  107. #endif
  108. [dateFormatter setCalendar:[[NSCalendar alloc] initWithCalendarIdentifier:calendarIdentifier]];
  109. }
  110. - (NSString *)stringFromDate:(NSDate *)date {
  111. NSDateFormatter *dateFormatter = nil;
  112. if (_mode == DDDispatchQueueLogFormatterModeNonShareble) {
  113. // Single-threaded mode.
  114. dateFormatter = _threadUnsafeDateFormatter;
  115. if (dateFormatter == nil) {
  116. dateFormatter = [self createDateFormatter];
  117. _threadUnsafeDateFormatter = dateFormatter;
  118. }
  119. } else {
  120. // Multi-threaded mode.
  121. // NSDateFormatter is NOT thread-safe.
  122. NSString *key = _dateFormatterKey;
  123. NSMutableDictionary *threadDictionary = [[NSThread currentThread] threadDictionary];
  124. dateFormatter = threadDictionary[key];
  125. if (dateFormatter == nil) {
  126. dateFormatter = [self createDateFormatter];
  127. threadDictionary[key] = dateFormatter;
  128. }
  129. }
  130. return [dateFormatter stringFromDate:date];
  131. }
  132. - (NSString *)queueThreadLabelForLogMessage:(DDLogMessage *)logMessage {
  133. // As per the DDLogFormatter contract, this method is always invoked on the same thread/dispatch_queue
  134. NSUInteger minQueueLength = self.minQueueLength;
  135. NSUInteger maxQueueLength = self.maxQueueLength;
  136. // Get the name of the queue, thread, or machID (whichever we are to use).
  137. NSString *queueThreadLabel = nil;
  138. BOOL useQueueLabel = YES;
  139. BOOL useThreadName = NO;
  140. if (logMessage->_queueLabel) {
  141. // If you manually create a thread, it's dispatch_queue will have one of the thread names below.
  142. // Since all such threads have the same name, we'd prefer to use the threadName or the machThreadID.
  143. NSArray *names = @[
  144. @"com.apple.root.low-priority",
  145. @"com.apple.root.default-priority",
  146. @"com.apple.root.high-priority",
  147. @"com.apple.root.low-overcommit-priority",
  148. @"com.apple.root.default-overcommit-priority",
  149. @"com.apple.root.high-overcommit-priority"
  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. OSSpinLockLock(&_lock);
  171. {
  172. abrvLabel = _replacements[fullLabel];
  173. }
  174. OSSpinLockUnlock(&_lock);
  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. int32_t count = 0;
  210. count = OSAtomicIncrement32(&_atomicLoggerCount);
  211. NSAssert(count <= 1 || _mode == DDDispatchQueueLogFormatterModeShareble, @"Can't reuse formatter with multiple loggers in non-shareable mode.");
  212. }
  213. - (void)willRemoveFromLogger:(id <DDLogger> __attribute__((unused)))logger {
  214. OSAtomicDecrement32(&_atomicLoggerCount);
  215. }
  216. @end