DDDispatchQueueLogFormatter.m 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. #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. _replacements = [[NSMutableDictionary alloc] init];
  53. // Set default replacements:
  54. _replacements[@"com.apple.main-thread"] = @"main";
  55. }
  56. return self;
  57. }
  58. - (instancetype)initWithMode:(DDDispatchQueueLogFormatterMode)mode {
  59. if ((self = [self init])) {
  60. _mode = mode;
  61. }
  62. return self;
  63. }
  64. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  65. #pragma mark Configuration
  66. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  67. @synthesize minQueueLength = _minQueueLength;
  68. @synthesize maxQueueLength = _maxQueueLength;
  69. - (NSString *)replacementStringForQueueLabel:(NSString *)longLabel {
  70. NSString *result = nil;
  71. OSSpinLockLock(&_lock);
  72. {
  73. result = _replacements[longLabel];
  74. }
  75. OSSpinLockUnlock(&_lock);
  76. return result;
  77. }
  78. - (void)setReplacementString:(NSString *)shortLabel forQueueLabel:(NSString *)longLabel {
  79. OSSpinLockLock(&_lock);
  80. {
  81. if (shortLabel) {
  82. _replacements[longLabel] = shortLabel;
  83. } else {
  84. [_replacements removeObjectForKey:longLabel];
  85. }
  86. }
  87. OSSpinLockUnlock(&_lock);
  88. }
  89. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  90. #pragma mark DDLogFormatter
  91. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  92. - (NSDateFormatter *)createDateFormatter {
  93. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  94. [self configureDateFormatter:formatter];
  95. return formatter;
  96. }
  97. - (void)configureDateFormatter:(NSDateFormatter *)dateFormatter {
  98. [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
  99. [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss:SSS"];
  100. [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
  101. NSString *calendarIdentifier = nil;
  102. #if defined(__IPHONE_8_0) || defined(__MAC_10_10)
  103. calendarIdentifier = NSCalendarIdentifierGregorian;
  104. #else
  105. calendarIdentifier = NSGregorianCalendar;
  106. #endif
  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. ];
  150. for (NSString * name in names) {
  151. if ([logMessage->_queueLabel isEqualToString:name]) {
  152. useQueueLabel = NO;
  153. useThreadName = [logMessage->_threadName length] > 0;
  154. break;
  155. }
  156. }
  157. } else {
  158. useQueueLabel = NO;
  159. useThreadName = [logMessage->_threadName length] > 0;
  160. }
  161. if (useQueueLabel || useThreadName) {
  162. NSString *fullLabel;
  163. NSString *abrvLabel;
  164. if (useQueueLabel) {
  165. fullLabel = logMessage->_queueLabel;
  166. } else {
  167. fullLabel = logMessage->_threadName;
  168. }
  169. OSSpinLockLock(&_lock);
  170. {
  171. abrvLabel = _replacements[fullLabel];
  172. }
  173. OSSpinLockUnlock(&_lock);
  174. if (abrvLabel) {
  175. queueThreadLabel = abrvLabel;
  176. } else {
  177. queueThreadLabel = fullLabel;
  178. }
  179. } else {
  180. queueThreadLabel = logMessage->_threadID;
  181. }
  182. // Now use the thread label in the output
  183. NSUInteger labelLength = [queueThreadLabel length];
  184. // labelLength > maxQueueLength : truncate
  185. // labelLength < minQueueLength : padding
  186. // : exact
  187. if ((maxQueueLength > 0) && (labelLength > maxQueueLength)) {
  188. // Truncate
  189. return [queueThreadLabel substringToIndex:maxQueueLength];
  190. } else if (labelLength < minQueueLength) {
  191. // Padding
  192. NSUInteger numSpaces = minQueueLength - labelLength;
  193. char spaces[numSpaces + 1];
  194. memset(spaces, ' ', numSpaces);
  195. spaces[numSpaces] = '\0';
  196. return [NSString stringWithFormat:@"%@%s", queueThreadLabel, spaces];
  197. } else {
  198. // Exact
  199. return queueThreadLabel;
  200. }
  201. }
  202. - (NSString *)formatLogMessage:(DDLogMessage *)logMessage {
  203. NSString *timestamp = [self stringFromDate:(logMessage->_timestamp)];
  204. NSString *queueThreadLabel = [self queueThreadLabelForLogMessage:logMessage];
  205. return [NSString stringWithFormat:@"%@ [%@] %@", timestamp, queueThreadLabel, logMessage->_message];
  206. }
  207. - (void)didAddToLogger:(id <DDLogger> __attribute__((unused)))logger {
  208. int32_t count = 0;
  209. count = OSAtomicIncrement32(&_atomicLoggerCount);
  210. NSAssert(count <= 1 || _mode == DDDispatchQueueLogFormatterModeShareble, @"Can't reuse formatter with multiple loggers in non-shareable mode.");
  211. }
  212. - (void)willRemoveFromLogger:(id <DDLogger> __attribute__((unused)))logger {
  213. OSAtomicDecrement32(&_atomicLoggerCount);
  214. }
  215. @end