DDTTYLogger.m 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473
  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 "DDTTYLogger.h"
  16. #import <unistd.h>
  17. #import <sys/uio.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. // We probably shouldn't be using DDLog() statements within the DDLog implementation.
  22. // But we still want to leave our log statements for any future debugging,
  23. // and to allow other developers to trace the implementation (which is a great learning tool).
  24. //
  25. // So we use primitive logging macros around NSLog.
  26. // We maintain the NS prefix on the macros to be explicit about the fact that we're using NSLog.
  27. #ifndef DD_NSLOG_LEVEL
  28. #define DD_NSLOG_LEVEL 2
  29. #endif
  30. #define NSLogError(frmt, ...) do{ if(DD_NSLOG_LEVEL >= 1) NSLog((frmt), ##__VA_ARGS__); } while(0)
  31. #define NSLogWarn(frmt, ...) do{ if(DD_NSLOG_LEVEL >= 2) NSLog((frmt), ##__VA_ARGS__); } while(0)
  32. #define NSLogInfo(frmt, ...) do{ if(DD_NSLOG_LEVEL >= 3) NSLog((frmt), ##__VA_ARGS__); } while(0)
  33. #define NSLogDebug(frmt, ...) do{ if(DD_NSLOG_LEVEL >= 4) NSLog((frmt), ##__VA_ARGS__); } while(0)
  34. #define NSLogVerbose(frmt, ...) do{ if(DD_NSLOG_LEVEL >= 5) NSLog((frmt), ##__VA_ARGS__); } while(0)
  35. // Xcode does NOT natively support colors in the Xcode debugging console.
  36. // You'll need to install the XcodeColors plugin to see colors in the Xcode console.
  37. // https://github.com/robbiehanson/XcodeColors
  38. //
  39. // The following is documentation from the XcodeColors project:
  40. //
  41. //
  42. // How to apply color formatting to your log statements:
  43. //
  44. // To set the foreground color:
  45. // Insert the ESCAPE_SEQ into your string, followed by "fg124,12,255;" where r=124, g=12, b=255.
  46. //
  47. // To set the background color:
  48. // Insert the ESCAPE_SEQ into your string, followed by "bg12,24,36;" where r=12, g=24, b=36.
  49. //
  50. // To reset the foreground color (to default value):
  51. // Insert the ESCAPE_SEQ into your string, followed by "fg;"
  52. //
  53. // To reset the background color (to default value):
  54. // Insert the ESCAPE_SEQ into your string, followed by "bg;"
  55. //
  56. // To reset the foreground and background color (to default values) in one operation:
  57. // Insert the ESCAPE_SEQ into your string, followed by ";"
  58. #define XCODE_COLORS_ESCAPE_SEQ "\033["
  59. #define XCODE_COLORS_RESET_FG XCODE_COLORS_ESCAPE_SEQ "fg;" // Clear any foreground color
  60. #define XCODE_COLORS_RESET_BG XCODE_COLORS_ESCAPE_SEQ "bg;" // Clear any background color
  61. #define XCODE_COLORS_RESET XCODE_COLORS_ESCAPE_SEQ ";" // Clear any foreground or background color
  62. // If running in a shell, not all RGB colors will be supported.
  63. // In this case we automatically map to the closest available color.
  64. // In order to provide this mapping, we have a hard-coded set of the standard RGB values available in the shell.
  65. // However, not every shell is the same, and Apple likes to think different even when it comes to shell colors.
  66. //
  67. // Map to standard Terminal.app colors (1), or
  68. // map to standard xterm colors (0).
  69. #define MAP_TO_TERMINAL_APP_COLORS 1
  70. @interface DDTTYLoggerColorProfile : NSObject {
  71. @public
  72. DDLogFlag mask;
  73. NSInteger context;
  74. uint8_t fg_r;
  75. uint8_t fg_g;
  76. uint8_t fg_b;
  77. uint8_t bg_r;
  78. uint8_t bg_g;
  79. uint8_t bg_b;
  80. NSUInteger fgCodeIndex;
  81. NSString *fgCodeRaw;
  82. NSUInteger bgCodeIndex;
  83. NSString *bgCodeRaw;
  84. char fgCode[24];
  85. size_t fgCodeLen;
  86. char bgCode[24];
  87. size_t bgCodeLen;
  88. char resetCode[8];
  89. size_t resetCodeLen;
  90. }
  91. - (instancetype)initWithForegroundColor:(DDColor *)fgColor backgroundColor:(DDColor *)bgColor flag:(DDLogFlag)mask context:(NSInteger)ctxt;
  92. @end
  93. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  94. #pragma mark -
  95. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  96. @interface DDTTYLogger () {
  97. NSString *_appName;
  98. char *_app;
  99. size_t _appLen;
  100. NSString *_processID;
  101. char *_pid;
  102. size_t _pidLen;
  103. BOOL _colorsEnabled;
  104. NSMutableArray *_colorProfilesArray;
  105. NSMutableDictionary *_colorProfilesDict;
  106. }
  107. @end
  108. @implementation DDTTYLogger
  109. static BOOL isaColorTTY;
  110. static BOOL isaColor256TTY;
  111. static BOOL isaXcodeColorTTY;
  112. static NSArray *codes_fg = nil;
  113. static NSArray *codes_bg = nil;
  114. static NSArray *colors = nil;
  115. static DDTTYLogger *sharedInstance;
  116. /**
  117. * Initializes the colors array, as well as the codes_fg and codes_bg arrays, for 16 color mode.
  118. *
  119. * This method is used when the application is running from within a shell that only supports 16 color mode.
  120. * This method is not invoked if the application is running within Xcode, or via normal UI app launch.
  121. **/
  122. + (void)initialize_colors_16 {
  123. if (codes_fg || codes_bg || colors) {
  124. return;
  125. }
  126. NSMutableArray *m_codes_fg = [NSMutableArray arrayWithCapacity:16];
  127. NSMutableArray *m_codes_bg = [NSMutableArray arrayWithCapacity:16];
  128. NSMutableArray *m_colors = [NSMutableArray arrayWithCapacity:16];
  129. // In a standard shell only 16 colors are supported.
  130. //
  131. // More information about ansi escape codes can be found online.
  132. // http://en.wikipedia.org/wiki/ANSI_escape_code
  133. [m_codes_fg addObject:@"30m"]; // normal - black
  134. [m_codes_fg addObject:@"31m"]; // normal - red
  135. [m_codes_fg addObject:@"32m"]; // normal - green
  136. [m_codes_fg addObject:@"33m"]; // normal - yellow
  137. [m_codes_fg addObject:@"34m"]; // normal - blue
  138. [m_codes_fg addObject:@"35m"]; // normal - magenta
  139. [m_codes_fg addObject:@"36m"]; // normal - cyan
  140. [m_codes_fg addObject:@"37m"]; // normal - gray
  141. [m_codes_fg addObject:@"1;30m"]; // bright - darkgray
  142. [m_codes_fg addObject:@"1;31m"]; // bright - red
  143. [m_codes_fg addObject:@"1;32m"]; // bright - green
  144. [m_codes_fg addObject:@"1;33m"]; // bright - yellow
  145. [m_codes_fg addObject:@"1;34m"]; // bright - blue
  146. [m_codes_fg addObject:@"1;35m"]; // bright - magenta
  147. [m_codes_fg addObject:@"1;36m"]; // bright - cyan
  148. [m_codes_fg addObject:@"1;37m"]; // bright - white
  149. [m_codes_bg addObject:@"40m"]; // normal - black
  150. [m_codes_bg addObject:@"41m"]; // normal - red
  151. [m_codes_bg addObject:@"42m"]; // normal - green
  152. [m_codes_bg addObject:@"43m"]; // normal - yellow
  153. [m_codes_bg addObject:@"44m"]; // normal - blue
  154. [m_codes_bg addObject:@"45m"]; // normal - magenta
  155. [m_codes_bg addObject:@"46m"]; // normal - cyan
  156. [m_codes_bg addObject:@"47m"]; // normal - gray
  157. [m_codes_bg addObject:@"1;40m"]; // bright - darkgray
  158. [m_codes_bg addObject:@"1;41m"]; // bright - red
  159. [m_codes_bg addObject:@"1;42m"]; // bright - green
  160. [m_codes_bg addObject:@"1;43m"]; // bright - yellow
  161. [m_codes_bg addObject:@"1;44m"]; // bright - blue
  162. [m_codes_bg addObject:@"1;45m"]; // bright - magenta
  163. [m_codes_bg addObject:@"1;46m"]; // bright - cyan
  164. [m_codes_bg addObject:@"1;47m"]; // bright - white
  165. #if MAP_TO_TERMINAL_APP_COLORS
  166. // Standard Terminal.app colors:
  167. //
  168. // These are the default colors used by Apple's Terminal.app.
  169. [m_colors addObject:DDMakeColor( 0, 0, 0)]; // normal - black
  170. [m_colors addObject:DDMakeColor(194, 54, 33)]; // normal - red
  171. [m_colors addObject:DDMakeColor( 37, 188, 36)]; // normal - green
  172. [m_colors addObject:DDMakeColor(173, 173, 39)]; // normal - yellow
  173. [m_colors addObject:DDMakeColor( 73, 46, 225)]; // normal - blue
  174. [m_colors addObject:DDMakeColor(211, 56, 211)]; // normal - magenta
  175. [m_colors addObject:DDMakeColor( 51, 187, 200)]; // normal - cyan
  176. [m_colors addObject:DDMakeColor(203, 204, 205)]; // normal - gray
  177. [m_colors addObject:DDMakeColor(129, 131, 131)]; // bright - darkgray
  178. [m_colors addObject:DDMakeColor(252, 57, 31)]; // bright - red
  179. [m_colors addObject:DDMakeColor( 49, 231, 34)]; // bright - green
  180. [m_colors addObject:DDMakeColor(234, 236, 35)]; // bright - yellow
  181. [m_colors addObject:DDMakeColor( 88, 51, 255)]; // bright - blue
  182. [m_colors addObject:DDMakeColor(249, 53, 248)]; // bright - magenta
  183. [m_colors addObject:DDMakeColor( 20, 240, 240)]; // bright - cyan
  184. [m_colors addObject:DDMakeColor(233, 235, 235)]; // bright - white
  185. #else /* if MAP_TO_TERMINAL_APP_COLORS */
  186. // Standard xterm colors:
  187. //
  188. // These are the default colors used by most xterm shells.
  189. [m_colors addObject:DDMakeColor( 0, 0, 0)]; // normal - black
  190. [m_colors addObject:DDMakeColor(205, 0, 0)]; // normal - red
  191. [m_colors addObject:DDMakeColor( 0, 205, 0)]; // normal - green
  192. [m_colors addObject:DDMakeColor(205, 205, 0)]; // normal - yellow
  193. [m_colors addObject:DDMakeColor( 0, 0, 238)]; // normal - blue
  194. [m_colors addObject:DDMakeColor(205, 0, 205)]; // normal - magenta
  195. [m_colors addObject:DDMakeColor( 0, 205, 205)]; // normal - cyan
  196. [m_colors addObject:DDMakeColor(229, 229, 229)]; // normal - gray
  197. [m_colors addObject:DDMakeColor(127, 127, 127)]; // bright - darkgray
  198. [m_colors addObject:DDMakeColor(255, 0, 0)]; // bright - red
  199. [m_colors addObject:DDMakeColor( 0, 255, 0)]; // bright - green
  200. [m_colors addObject:DDMakeColor(255, 255, 0)]; // bright - yellow
  201. [m_colors addObject:DDMakeColor( 92, 92, 255)]; // bright - blue
  202. [m_colors addObject:DDMakeColor(255, 0, 255)]; // bright - magenta
  203. [m_colors addObject:DDMakeColor( 0, 255, 255)]; // bright - cyan
  204. [m_colors addObject:DDMakeColor(255, 255, 255)]; // bright - white
  205. #endif /* if MAP_TO_TERMINAL_APP_COLORS */
  206. codes_fg = [m_codes_fg copy];
  207. codes_bg = [m_codes_bg copy];
  208. colors = [m_colors copy];
  209. NSAssert([codes_fg count] == [codes_bg count], @"Invalid colors/codes array(s)");
  210. NSAssert([codes_fg count] == [colors count], @"Invalid colors/codes array(s)");
  211. }
  212. /**
  213. * Initializes the colors array, as well as the codes_fg and codes_bg arrays, for 256 color mode.
  214. *
  215. * This method is used when the application is running from within a shell that supports 256 color mode.
  216. * This method is not invoked if the application is running within Xcode, or via normal UI app launch.
  217. **/
  218. + (void)initialize_colors_256 {
  219. if (codes_fg || codes_bg || colors) {
  220. return;
  221. }
  222. NSMutableArray *m_codes_fg = [NSMutableArray arrayWithCapacity:(256 - 16)];
  223. NSMutableArray *m_codes_bg = [NSMutableArray arrayWithCapacity:(256 - 16)];
  224. NSMutableArray *m_colors = [NSMutableArray arrayWithCapacity:(256 - 16)];
  225. #if MAP_TO_TERMINAL_APP_COLORS
  226. // Standard Terminal.app colors:
  227. //
  228. // These are the colors the Terminal.app uses in xterm-256color mode.
  229. // In this mode, the terminal supports 256 different colors, specified by 256 color codes.
  230. //
  231. // The first 16 color codes map to the original 16 color codes supported by the earlier xterm-color mode.
  232. // These are actually configurable, and thus we ignore them for the purposes of mapping,
  233. // as we can't rely on them being constant. They are largely duplicated anyway.
  234. //
  235. // The next 216 color codes are designed to run the spectrum, with several shades of every color.
  236. // While the color codes are standardized, the actual RGB values for each color code is not.
  237. // Apple's Terminal.app uses different RGB values from that of a standard xterm.
  238. // Apple's choices in colors are designed to be a little nicer on the eyes.
  239. //
  240. // The last 24 color codes represent a grayscale.
  241. //
  242. // Unfortunately, unlike the standard xterm color chart,
  243. // Apple's RGB values cannot be calculated using a simple formula (at least not that I know of).
  244. // Also, I don't know of any ways to programmatically query the shell for the RGB values.
  245. // So this big giant color chart had to be made by hand.
  246. //
  247. // More information about ansi escape codes can be found online.
  248. // http://en.wikipedia.org/wiki/ANSI_escape_code
  249. // Colors
  250. [m_colors addObject:DDMakeColor( 47, 49, 49)];
  251. [m_colors addObject:DDMakeColor( 60, 42, 144)];
  252. [m_colors addObject:DDMakeColor( 66, 44, 183)];
  253. [m_colors addObject:DDMakeColor( 73, 46, 222)];
  254. [m_colors addObject:DDMakeColor( 81, 50, 253)];
  255. [m_colors addObject:DDMakeColor( 88, 51, 255)];
  256. [m_colors addObject:DDMakeColor( 42, 128, 37)];
  257. [m_colors addObject:DDMakeColor( 42, 127, 128)];
  258. [m_colors addObject:DDMakeColor( 44, 126, 169)];
  259. [m_colors addObject:DDMakeColor( 56, 125, 209)];
  260. [m_colors addObject:DDMakeColor( 59, 124, 245)];
  261. [m_colors addObject:DDMakeColor( 66, 123, 255)];
  262. [m_colors addObject:DDMakeColor( 51, 163, 41)];
  263. [m_colors addObject:DDMakeColor( 39, 162, 121)];
  264. [m_colors addObject:DDMakeColor( 42, 161, 162)];
  265. [m_colors addObject:DDMakeColor( 53, 160, 202)];
  266. [m_colors addObject:DDMakeColor( 45, 159, 240)];
  267. [m_colors addObject:DDMakeColor( 58, 158, 255)];
  268. [m_colors addObject:DDMakeColor( 31, 196, 37)];
  269. [m_colors addObject:DDMakeColor( 48, 196, 115)];
  270. [m_colors addObject:DDMakeColor( 39, 195, 155)];
  271. [m_colors addObject:DDMakeColor( 49, 195, 195)];
  272. [m_colors addObject:DDMakeColor( 32, 194, 235)];
  273. [m_colors addObject:DDMakeColor( 53, 193, 255)];
  274. [m_colors addObject:DDMakeColor( 50, 229, 35)];
  275. [m_colors addObject:DDMakeColor( 40, 229, 109)];
  276. [m_colors addObject:DDMakeColor( 27, 229, 149)];
  277. [m_colors addObject:DDMakeColor( 49, 228, 189)];
  278. [m_colors addObject:DDMakeColor( 33, 228, 228)];
  279. [m_colors addObject:DDMakeColor( 53, 227, 255)];
  280. [m_colors addObject:DDMakeColor( 27, 254, 30)];
  281. [m_colors addObject:DDMakeColor( 30, 254, 103)];
  282. [m_colors addObject:DDMakeColor( 45, 254, 143)];
  283. [m_colors addObject:DDMakeColor( 38, 253, 182)];
  284. [m_colors addObject:DDMakeColor( 38, 253, 222)];
  285. [m_colors addObject:DDMakeColor( 42, 253, 252)];
  286. [m_colors addObject:DDMakeColor(140, 48, 40)];
  287. [m_colors addObject:DDMakeColor(136, 51, 136)];
  288. [m_colors addObject:DDMakeColor(135, 52, 177)];
  289. [m_colors addObject:DDMakeColor(134, 52, 217)];
  290. [m_colors addObject:DDMakeColor(135, 56, 248)];
  291. [m_colors addObject:DDMakeColor(134, 53, 255)];
  292. [m_colors addObject:DDMakeColor(125, 125, 38)];
  293. [m_colors addObject:DDMakeColor(124, 125, 125)];
  294. [m_colors addObject:DDMakeColor(122, 124, 166)];
  295. [m_colors addObject:DDMakeColor(123, 124, 207)];
  296. [m_colors addObject:DDMakeColor(123, 122, 247)];
  297. [m_colors addObject:DDMakeColor(124, 121, 255)];
  298. [m_colors addObject:DDMakeColor(119, 160, 35)];
  299. [m_colors addObject:DDMakeColor(117, 160, 120)];
  300. [m_colors addObject:DDMakeColor(117, 160, 160)];
  301. [m_colors addObject:DDMakeColor(115, 159, 201)];
  302. [m_colors addObject:DDMakeColor(116, 158, 240)];
  303. [m_colors addObject:DDMakeColor(117, 157, 255)];
  304. [m_colors addObject:DDMakeColor(113, 195, 39)];
  305. [m_colors addObject:DDMakeColor(110, 194, 114)];
  306. [m_colors addObject:DDMakeColor(111, 194, 154)];
  307. [m_colors addObject:DDMakeColor(108, 194, 194)];
  308. [m_colors addObject:DDMakeColor(109, 193, 234)];
  309. [m_colors addObject:DDMakeColor(108, 192, 255)];
  310. [m_colors addObject:DDMakeColor(105, 228, 30)];
  311. [m_colors addObject:DDMakeColor(103, 228, 109)];
  312. [m_colors addObject:DDMakeColor(105, 228, 148)];
  313. [m_colors addObject:DDMakeColor(100, 227, 188)];
  314. [m_colors addObject:DDMakeColor( 99, 227, 227)];
  315. [m_colors addObject:DDMakeColor( 99, 226, 253)];
  316. [m_colors addObject:DDMakeColor( 92, 253, 34)];
  317. [m_colors addObject:DDMakeColor( 96, 253, 103)];
  318. [m_colors addObject:DDMakeColor( 97, 253, 142)];
  319. [m_colors addObject:DDMakeColor( 88, 253, 182)];
  320. [m_colors addObject:DDMakeColor( 93, 253, 221)];
  321. [m_colors addObject:DDMakeColor( 88, 254, 251)];
  322. [m_colors addObject:DDMakeColor(177, 53, 34)];
  323. [m_colors addObject:DDMakeColor(174, 54, 131)];
  324. [m_colors addObject:DDMakeColor(172, 55, 172)];
  325. [m_colors addObject:DDMakeColor(171, 57, 213)];
  326. [m_colors addObject:DDMakeColor(170, 55, 249)];
  327. [m_colors addObject:DDMakeColor(170, 57, 255)];
  328. [m_colors addObject:DDMakeColor(165, 123, 37)];
  329. [m_colors addObject:DDMakeColor(163, 123, 123)];
  330. [m_colors addObject:DDMakeColor(162, 123, 164)];
  331. [m_colors addObject:DDMakeColor(161, 122, 205)];
  332. [m_colors addObject:DDMakeColor(161, 121, 241)];
  333. [m_colors addObject:DDMakeColor(161, 121, 255)];
  334. [m_colors addObject:DDMakeColor(158, 159, 33)];
  335. [m_colors addObject:DDMakeColor(157, 158, 118)];
  336. [m_colors addObject:DDMakeColor(157, 158, 159)];
  337. [m_colors addObject:DDMakeColor(155, 157, 199)];
  338. [m_colors addObject:DDMakeColor(155, 157, 239)];
  339. [m_colors addObject:DDMakeColor(154, 156, 255)];
  340. [m_colors addObject:DDMakeColor(152, 193, 40)];
  341. [m_colors addObject:DDMakeColor(151, 193, 113)];
  342. [m_colors addObject:DDMakeColor(150, 193, 153)];
  343. [m_colors addObject:DDMakeColor(150, 192, 193)];
  344. [m_colors addObject:DDMakeColor(148, 192, 232)];
  345. [m_colors addObject:DDMakeColor(149, 191, 253)];
  346. [m_colors addObject:DDMakeColor(146, 227, 28)];
  347. [m_colors addObject:DDMakeColor(144, 227, 108)];
  348. [m_colors addObject:DDMakeColor(144, 227, 147)];
  349. [m_colors addObject:DDMakeColor(144, 227, 187)];
  350. [m_colors addObject:DDMakeColor(142, 226, 227)];
  351. [m_colors addObject:DDMakeColor(142, 225, 252)];
  352. [m_colors addObject:DDMakeColor(138, 253, 36)];
  353. [m_colors addObject:DDMakeColor(137, 253, 102)];
  354. [m_colors addObject:DDMakeColor(136, 253, 141)];
  355. [m_colors addObject:DDMakeColor(138, 254, 181)];
  356. [m_colors addObject:DDMakeColor(135, 255, 220)];
  357. [m_colors addObject:DDMakeColor(133, 255, 250)];
  358. [m_colors addObject:DDMakeColor(214, 57, 30)];
  359. [m_colors addObject:DDMakeColor(211, 59, 126)];
  360. [m_colors addObject:DDMakeColor(209, 57, 168)];
  361. [m_colors addObject:DDMakeColor(208, 55, 208)];
  362. [m_colors addObject:DDMakeColor(207, 58, 247)];
  363. [m_colors addObject:DDMakeColor(206, 61, 255)];
  364. [m_colors addObject:DDMakeColor(204, 121, 32)];
  365. [m_colors addObject:DDMakeColor(202, 121, 121)];
  366. [m_colors addObject:DDMakeColor(201, 121, 161)];
  367. [m_colors addObject:DDMakeColor(200, 120, 202)];
  368. [m_colors addObject:DDMakeColor(200, 120, 241)];
  369. [m_colors addObject:DDMakeColor(198, 119, 255)];
  370. [m_colors addObject:DDMakeColor(198, 157, 37)];
  371. [m_colors addObject:DDMakeColor(196, 157, 116)];
  372. [m_colors addObject:DDMakeColor(195, 156, 157)];
  373. [m_colors addObject:DDMakeColor(195, 156, 197)];
  374. [m_colors addObject:DDMakeColor(194, 155, 236)];
  375. [m_colors addObject:DDMakeColor(193, 155, 255)];
  376. [m_colors addObject:DDMakeColor(191, 192, 36)];
  377. [m_colors addObject:DDMakeColor(190, 191, 112)];
  378. [m_colors addObject:DDMakeColor(189, 191, 152)];
  379. [m_colors addObject:DDMakeColor(189, 191, 191)];
  380. [m_colors addObject:DDMakeColor(188, 190, 230)];
  381. [m_colors addObject:DDMakeColor(187, 190, 253)];
  382. [m_colors addObject:DDMakeColor(185, 226, 28)];
  383. [m_colors addObject:DDMakeColor(184, 226, 106)];
  384. [m_colors addObject:DDMakeColor(183, 225, 146)];
  385. [m_colors addObject:DDMakeColor(183, 225, 186)];
  386. [m_colors addObject:DDMakeColor(182, 225, 225)];
  387. [m_colors addObject:DDMakeColor(181, 224, 252)];
  388. [m_colors addObject:DDMakeColor(178, 255, 35)];
  389. [m_colors addObject:DDMakeColor(178, 255, 101)];
  390. [m_colors addObject:DDMakeColor(177, 254, 141)];
  391. [m_colors addObject:DDMakeColor(176, 254, 180)];
  392. [m_colors addObject:DDMakeColor(176, 254, 220)];
  393. [m_colors addObject:DDMakeColor(175, 253, 249)];
  394. [m_colors addObject:DDMakeColor(247, 56, 30)];
  395. [m_colors addObject:DDMakeColor(245, 57, 122)];
  396. [m_colors addObject:DDMakeColor(243, 59, 163)];
  397. [m_colors addObject:DDMakeColor(244, 60, 204)];
  398. [m_colors addObject:DDMakeColor(242, 59, 241)];
  399. [m_colors addObject:DDMakeColor(240, 55, 255)];
  400. [m_colors addObject:DDMakeColor(241, 119, 36)];
  401. [m_colors addObject:DDMakeColor(240, 120, 118)];
  402. [m_colors addObject:DDMakeColor(238, 119, 158)];
  403. [m_colors addObject:DDMakeColor(237, 119, 199)];
  404. [m_colors addObject:DDMakeColor(237, 118, 238)];
  405. [m_colors addObject:DDMakeColor(236, 118, 255)];
  406. [m_colors addObject:DDMakeColor(235, 154, 36)];
  407. [m_colors addObject:DDMakeColor(235, 154, 114)];
  408. [m_colors addObject:DDMakeColor(234, 154, 154)];
  409. [m_colors addObject:DDMakeColor(232, 154, 194)];
  410. [m_colors addObject:DDMakeColor(232, 153, 234)];
  411. [m_colors addObject:DDMakeColor(232, 153, 255)];
  412. [m_colors addObject:DDMakeColor(230, 190, 30)];
  413. [m_colors addObject:DDMakeColor(229, 189, 110)];
  414. [m_colors addObject:DDMakeColor(228, 189, 150)];
  415. [m_colors addObject:DDMakeColor(227, 189, 190)];
  416. [m_colors addObject:DDMakeColor(227, 189, 229)];
  417. [m_colors addObject:DDMakeColor(226, 188, 255)];
  418. [m_colors addObject:DDMakeColor(224, 224, 35)];
  419. [m_colors addObject:DDMakeColor(223, 224, 105)];
  420. [m_colors addObject:DDMakeColor(222, 224, 144)];
  421. [m_colors addObject:DDMakeColor(222, 223, 184)];
  422. [m_colors addObject:DDMakeColor(222, 223, 224)];
  423. [m_colors addObject:DDMakeColor(220, 223, 253)];
  424. [m_colors addObject:DDMakeColor(217, 253, 28)];
  425. [m_colors addObject:DDMakeColor(217, 253, 99)];
  426. [m_colors addObject:DDMakeColor(216, 252, 139)];
  427. [m_colors addObject:DDMakeColor(216, 252, 179)];
  428. [m_colors addObject:DDMakeColor(215, 252, 218)];
  429. [m_colors addObject:DDMakeColor(215, 251, 250)];
  430. [m_colors addObject:DDMakeColor(255, 61, 30)];
  431. [m_colors addObject:DDMakeColor(255, 60, 118)];
  432. [m_colors addObject:DDMakeColor(255, 58, 159)];
  433. [m_colors addObject:DDMakeColor(255, 56, 199)];
  434. [m_colors addObject:DDMakeColor(255, 55, 238)];
  435. [m_colors addObject:DDMakeColor(255, 59, 255)];
  436. [m_colors addObject:DDMakeColor(255, 117, 29)];
  437. [m_colors addObject:DDMakeColor(255, 117, 115)];
  438. [m_colors addObject:DDMakeColor(255, 117, 155)];
  439. [m_colors addObject:DDMakeColor(255, 117, 195)];
  440. [m_colors addObject:DDMakeColor(255, 116, 235)];
  441. [m_colors addObject:DDMakeColor(254, 116, 255)];
  442. [m_colors addObject:DDMakeColor(255, 152, 27)];
  443. [m_colors addObject:DDMakeColor(255, 152, 111)];
  444. [m_colors addObject:DDMakeColor(254, 152, 152)];
  445. [m_colors addObject:DDMakeColor(255, 152, 192)];
  446. [m_colors addObject:DDMakeColor(254, 151, 231)];
  447. [m_colors addObject:DDMakeColor(253, 151, 253)];
  448. [m_colors addObject:DDMakeColor(255, 187, 33)];
  449. [m_colors addObject:DDMakeColor(253, 187, 107)];
  450. [m_colors addObject:DDMakeColor(252, 187, 148)];
  451. [m_colors addObject:DDMakeColor(253, 187, 187)];
  452. [m_colors addObject:DDMakeColor(254, 187, 227)];
  453. [m_colors addObject:DDMakeColor(252, 186, 252)];
  454. [m_colors addObject:DDMakeColor(252, 222, 34)];
  455. [m_colors addObject:DDMakeColor(251, 222, 103)];
  456. [m_colors addObject:DDMakeColor(251, 222, 143)];
  457. [m_colors addObject:DDMakeColor(250, 222, 182)];
  458. [m_colors addObject:DDMakeColor(251, 221, 222)];
  459. [m_colors addObject:DDMakeColor(252, 221, 252)];
  460. [m_colors addObject:DDMakeColor(251, 252, 15)];
  461. [m_colors addObject:DDMakeColor(251, 252, 97)];
  462. [m_colors addObject:DDMakeColor(249, 252, 137)];
  463. [m_colors addObject:DDMakeColor(247, 252, 177)];
  464. [m_colors addObject:DDMakeColor(247, 253, 217)];
  465. [m_colors addObject:DDMakeColor(254, 255, 255)];
  466. // Grayscale
  467. [m_colors addObject:DDMakeColor( 52, 53, 53)];
  468. [m_colors addObject:DDMakeColor( 57, 58, 59)];
  469. [m_colors addObject:DDMakeColor( 66, 67, 67)];
  470. [m_colors addObject:DDMakeColor( 75, 76, 76)];
  471. [m_colors addObject:DDMakeColor( 83, 85, 85)];
  472. [m_colors addObject:DDMakeColor( 92, 93, 94)];
  473. [m_colors addObject:DDMakeColor(101, 102, 102)];
  474. [m_colors addObject:DDMakeColor(109, 111, 111)];
  475. [m_colors addObject:DDMakeColor(118, 119, 119)];
  476. [m_colors addObject:DDMakeColor(126, 127, 128)];
  477. [m_colors addObject:DDMakeColor(134, 136, 136)];
  478. [m_colors addObject:DDMakeColor(143, 144, 145)];
  479. [m_colors addObject:DDMakeColor(151, 152, 153)];
  480. [m_colors addObject:DDMakeColor(159, 161, 161)];
  481. [m_colors addObject:DDMakeColor(167, 169, 169)];
  482. [m_colors addObject:DDMakeColor(176, 177, 177)];
  483. [m_colors addObject:DDMakeColor(184, 185, 186)];
  484. [m_colors addObject:DDMakeColor(192, 193, 194)];
  485. [m_colors addObject:DDMakeColor(200, 201, 202)];
  486. [m_colors addObject:DDMakeColor(208, 209, 210)];
  487. [m_colors addObject:DDMakeColor(216, 218, 218)];
  488. [m_colors addObject:DDMakeColor(224, 226, 226)];
  489. [m_colors addObject:DDMakeColor(232, 234, 234)];
  490. [m_colors addObject:DDMakeColor(240, 242, 242)];
  491. // Color codes
  492. int index = 16;
  493. while (index < 256) {
  494. [m_codes_fg addObject:[NSString stringWithFormat:@"38;5;%dm", index]];
  495. [m_codes_bg addObject:[NSString stringWithFormat:@"48;5;%dm", index]];
  496. index++;
  497. }
  498. #else /* if MAP_TO_TERMINAL_APP_COLORS */
  499. // Standard xterm colors:
  500. //
  501. // These are the colors xterm shells use in xterm-256color mode.
  502. // In this mode, the shell supports 256 different colors, specified by 256 color codes.
  503. //
  504. // The first 16 color codes map to the original 16 color codes supported by the earlier xterm-color mode.
  505. // These are generally configurable, and thus we ignore them for the purposes of mapping,
  506. // as we can't rely on them being constant. They are largely duplicated anyway.
  507. //
  508. // The next 216 color codes are designed to run the spectrum, with several shades of every color.
  509. // The last 24 color codes represent a grayscale.
  510. //
  511. // While the color codes are standardized, the actual RGB values for each color code is not.
  512. // However most standard xterms follow a well known color chart,
  513. // which can easily be calculated using the simple formula below.
  514. //
  515. // More information about ansi escape codes can be found online.
  516. // http://en.wikipedia.org/wiki/ANSI_escape_code
  517. int index = 16;
  518. int r; // red
  519. int g; // green
  520. int b; // blue
  521. int ri; // r increment
  522. int gi; // g increment
  523. int bi; // b increment
  524. // Calculate xterm colors (using standard algorithm)
  525. int r = 0;
  526. int g = 0;
  527. int b = 0;
  528. for (ri = 0; ri < 6; ri++) {
  529. r = (ri == 0) ? 0 : 95 + (40 * (ri - 1));
  530. for (gi = 0; gi < 6; gi++) {
  531. g = (gi == 0) ? 0 : 95 + (40 * (gi - 1));
  532. for (bi = 0; bi < 6; bi++) {
  533. b = (bi == 0) ? 0 : 95 + (40 * (bi - 1));
  534. [m_codes_fg addObject:[NSString stringWithFormat:@"38;5;%dm", index]];
  535. [m_codes_bg addObject:[NSString stringWithFormat:@"48;5;%dm", index]];
  536. [m_colors addObject:DDMakeColor(r, g, b)];
  537. index++;
  538. }
  539. }
  540. }
  541. // Calculate xterm grayscale (using standard algorithm)
  542. r = 8;
  543. g = 8;
  544. b = 8;
  545. while (index < 256) {
  546. [m_codes_fg addObject:[NSString stringWithFormat:@"38;5;%dm", index]];
  547. [m_codes_bg addObject:[NSString stringWithFormat:@"48;5;%dm", index]];
  548. [m_colors addObject:DDMakeColor(r, g, b)];
  549. r += 10;
  550. g += 10;
  551. b += 10;
  552. index++;
  553. }
  554. #endif /* if MAP_TO_TERMINAL_APP_COLORS */
  555. codes_fg = [m_codes_fg copy];
  556. codes_bg = [m_codes_bg copy];
  557. colors = [m_colors copy];
  558. NSAssert([codes_fg count] == [codes_bg count], @"Invalid colors/codes array(s)");
  559. NSAssert([codes_fg count] == [colors count], @"Invalid colors/codes array(s)");
  560. }
  561. + (void)getRed:(CGFloat *)rPtr green:(CGFloat *)gPtr blue:(CGFloat *)bPtr fromColor:(DDColor *)color {
  562. #if TARGET_OS_IPHONE
  563. // iOS
  564. BOOL done = NO;
  565. if ([color respondsToSelector:@selector(getRed:green:blue:alpha:)]) {
  566. done = [color getRed:rPtr green:gPtr blue:bPtr alpha:NULL];
  567. }
  568. if (!done) {
  569. // The method getRed:green:blue:alpha: was only available starting iOS 5.
  570. // So in iOS 4 and earlier, we have to jump through hoops.
  571. CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
  572. unsigned char pixel[4];
  573. CGContextRef context = CGBitmapContextCreate(&pixel, 1, 1, 8, 4, rgbColorSpace, (CGBitmapInfo)(kCGBitmapAlphaInfoMask & kCGImageAlphaNoneSkipLast));
  574. CGContextSetFillColorWithColor(context, [color CGColor]);
  575. CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
  576. if (rPtr) {
  577. *rPtr = pixel[0] / 255.0f;
  578. }
  579. if (gPtr) {
  580. *gPtr = pixel[1] / 255.0f;
  581. }
  582. if (bPtr) {
  583. *bPtr = pixel[2] / 255.0f;
  584. }
  585. CGContextRelease(context);
  586. CGColorSpaceRelease(rgbColorSpace);
  587. }
  588. #elif defined(DD_CLI) || !__has_include(<AppKit/NSColor.h>)
  589. // OS X without AppKit
  590. [color getRed:rPtr green:gPtr blue:bPtr alpha:NULL];
  591. #else /* if TARGET_OS_IPHONE */
  592. // OS X with AppKit
  593. NSColor *safeColor = [color colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
  594. [safeColor getRed:rPtr green:gPtr blue:bPtr alpha:NULL];
  595. #endif /* if TARGET_OS_IPHONE */
  596. }
  597. /**
  598. * Maps the given color to the closest available color supported by the shell.
  599. * The shell may support 256 colors, or only 16.
  600. *
  601. * This method loops through the known supported color set, and calculates the closest color.
  602. * The array index of that color, within the colors array, is then returned.
  603. * This array index may also be used as the index within the codes_fg and codes_bg arrays.
  604. **/
  605. + (NSUInteger)codeIndexForColor:(DDColor *)inColor {
  606. CGFloat inR, inG, inB;
  607. [self getRed:&inR green:&inG blue:&inB fromColor:inColor];
  608. NSUInteger bestIndex = 0;
  609. CGFloat lowestDistance = 100.0f;
  610. NSUInteger i = 0;
  611. for (DDColor *color in colors) {
  612. // Calculate Euclidean distance (lower value means closer to given color)
  613. CGFloat r, g, b;
  614. [self getRed:&r green:&g blue:&b fromColor:color];
  615. #if CGFLOAT_IS_DOUBLE
  616. CGFloat distance = sqrt(pow(r - inR, 2.0) + pow(g - inG, 2.0) + pow(b - inB, 2.0));
  617. #else
  618. CGFloat distance = sqrtf(powf(r - inR, 2.0f) + powf(g - inG, 2.0f) + powf(b - inB, 2.0f));
  619. #endif
  620. NSLogVerbose(@"DDTTYLogger: %3lu : %.3f,%.3f,%.3f & %.3f,%.3f,%.3f = %.6f",
  621. (unsigned long)i, inR, inG, inB, r, g, b, distance);
  622. if (distance < lowestDistance) {
  623. bestIndex = i;
  624. lowestDistance = distance;
  625. NSLogVerbose(@"DDTTYLogger: New best index = %lu", (unsigned long)bestIndex);
  626. }
  627. i++;
  628. }
  629. return bestIndex;
  630. }
  631. + (instancetype)sharedInstance {
  632. static dispatch_once_t DDTTYLoggerOnceToken;
  633. dispatch_once(&DDTTYLoggerOnceToken, ^{
  634. // Xcode does NOT natively support colors in the Xcode debugging console.
  635. // You'll need to install the XcodeColors plugin to see colors in the Xcode console.
  636. //
  637. // PS - Please read the header file before diving into the source code.
  638. char *xcode_colors = getenv("XcodeColors");
  639. char *term = getenv("TERM");
  640. if (xcode_colors && (strcmp(xcode_colors, "YES") == 0)) {
  641. isaXcodeColorTTY = YES;
  642. } else if (term) {
  643. if (strcasestr(term, "color") != NULL) {
  644. isaColorTTY = YES;
  645. isaColor256TTY = (strcasestr(term, "256") != NULL);
  646. if (isaColor256TTY) {
  647. [self initialize_colors_256];
  648. } else {
  649. [self initialize_colors_16];
  650. }
  651. }
  652. }
  653. NSLogInfo(@"DDTTYLogger: isaColorTTY = %@", (isaColorTTY ? @"YES" : @"NO"));
  654. NSLogInfo(@"DDTTYLogger: isaColor256TTY: %@", (isaColor256TTY ? @"YES" : @"NO"));
  655. NSLogInfo(@"DDTTYLogger: isaXcodeColorTTY: %@", (isaXcodeColorTTY ? @"YES" : @"NO"));
  656. sharedInstance = [[[self class] alloc] init];
  657. });
  658. return sharedInstance;
  659. }
  660. - (instancetype)init {
  661. if (sharedInstance != nil) {
  662. return nil;
  663. }
  664. if ((self = [super init])) {
  665. // Initialze 'app' variable (char *)
  666. _appName = [[NSProcessInfo processInfo] processName];
  667. _appLen = [_appName lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  668. if (_appLen == 0) {
  669. _appName = @"<UnnamedApp>";
  670. _appLen = [_appName lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  671. }
  672. _app = (char *)malloc(_appLen + 1);
  673. if (_app == NULL) {
  674. return nil;
  675. }
  676. BOOL processedAppName = [_appName getCString:_app maxLength:(_appLen + 1) encoding:NSUTF8StringEncoding];
  677. if (NO == processedAppName) {
  678. free(_app);
  679. return nil;
  680. }
  681. // Initialize 'pid' variable (char *)
  682. _processID = [NSString stringWithFormat:@"%i", (int)getpid()];
  683. _pidLen = [_processID lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  684. _pid = (char *)malloc(_pidLen + 1);
  685. if (_pid == NULL) {
  686. free(_app);
  687. return nil;
  688. }
  689. BOOL processedID = [_processID getCString:_pid maxLength:(_pidLen + 1) encoding:NSUTF8StringEncoding];
  690. if (NO == processedID) {
  691. free(_app);
  692. free(_pid);
  693. return nil;
  694. }
  695. // Initialize color stuff
  696. _colorsEnabled = NO;
  697. _colorProfilesArray = [[NSMutableArray alloc] initWithCapacity:8];
  698. _colorProfilesDict = [[NSMutableDictionary alloc] initWithCapacity:8];
  699. _automaticallyAppendNewlineForCustomFormatters = YES;
  700. }
  701. return self;
  702. }
  703. - (void)loadDefaultColorProfiles {
  704. [self setForegroundColor:DDMakeColor(214, 57, 30) backgroundColor:nil forFlag:DDLogFlagError];
  705. [self setForegroundColor:DDMakeColor(204, 121, 32) backgroundColor:nil forFlag:DDLogFlagWarning];
  706. }
  707. - (BOOL)colorsEnabled {
  708. // The design of this method is taken from the DDAbstractLogger implementation.
  709. // For extensive documentation please refer to the DDAbstractLogger implementation.
  710. // Note: The internal implementation MUST access the colorsEnabled variable directly,
  711. // This method is designed explicitly for external access.
  712. //
  713. // Using "self." syntax to go through this method will cause immediate deadlock.
  714. // This is the intended result. Fix it by accessing the ivar directly.
  715. // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster.
  716. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  717. NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax.");
  718. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  719. __block BOOL result;
  720. dispatch_sync(globalLoggingQueue, ^{
  721. dispatch_sync(self.loggerQueue, ^{
  722. result = self->_colorsEnabled;
  723. });
  724. });
  725. return result;
  726. }
  727. - (void)setColorsEnabled:(BOOL)newColorsEnabled {
  728. dispatch_block_t block = ^{
  729. @autoreleasepool {
  730. self->_colorsEnabled = newColorsEnabled;
  731. if ([self->_colorProfilesArray count] == 0) {
  732. [self loadDefaultColorProfiles];
  733. }
  734. }
  735. };
  736. // The design of this method is taken from the DDAbstractLogger implementation.
  737. // For extensive documentation please refer to the DDAbstractLogger implementation.
  738. // Note: The internal implementation MUST access the colorsEnabled variable directly,
  739. // This method is designed explicitly for external access.
  740. //
  741. // Using "self." syntax to go through this method will cause immediate deadlock.
  742. // This is the intended result. Fix it by accessing the ivar directly.
  743. // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster.
  744. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  745. NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax.");
  746. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  747. dispatch_async(globalLoggingQueue, ^{
  748. dispatch_async(self.loggerQueue, block);
  749. });
  750. }
  751. - (void)setForegroundColor:(DDColor *)txtColor backgroundColor:(DDColor *)bgColor forFlag:(DDLogFlag)mask {
  752. [self setForegroundColor:txtColor backgroundColor:bgColor forFlag:mask context:LOG_CONTEXT_ALL];
  753. }
  754. - (void)setForegroundColor:(DDColor *)txtColor backgroundColor:(DDColor *)bgColor forFlag:(DDLogFlag)mask context:(NSInteger)ctxt {
  755. dispatch_block_t block = ^{
  756. @autoreleasepool {
  757. DDTTYLoggerColorProfile *newColorProfile =
  758. [[DDTTYLoggerColorProfile alloc] initWithForegroundColor:txtColor
  759. backgroundColor:bgColor
  760. flag:mask
  761. context:ctxt];
  762. NSLogInfo(@"DDTTYLogger: newColorProfile: %@", newColorProfile);
  763. NSUInteger i = 0;
  764. for (DDTTYLoggerColorProfile *colorProfile in self->_colorProfilesArray) {
  765. if ((colorProfile->mask == mask) && (colorProfile->context == ctxt)) {
  766. break;
  767. }
  768. i++;
  769. }
  770. if (i < [self->_colorProfilesArray count]) {
  771. self->_colorProfilesArray[i] = newColorProfile;
  772. } else {
  773. [self->_colorProfilesArray addObject:newColorProfile];
  774. }
  775. }
  776. };
  777. // The design of the setter logic below is taken from the DDAbstractLogger implementation.
  778. // For documentation please refer to the DDAbstractLogger implementation.
  779. if ([self isOnInternalLoggerQueue]) {
  780. block();
  781. } else {
  782. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  783. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  784. dispatch_async(globalLoggingQueue, ^{
  785. dispatch_async(self.loggerQueue, block);
  786. });
  787. }
  788. }
  789. - (void)setForegroundColor:(DDColor *)txtColor backgroundColor:(DDColor *)bgColor forTag:(id <NSCopying>)tag {
  790. NSAssert([(id < NSObject >) tag conformsToProtocol: @protocol(NSCopying)], @"Invalid tag");
  791. dispatch_block_t block = ^{
  792. @autoreleasepool {
  793. DDTTYLoggerColorProfile *newColorProfile =
  794. [[DDTTYLoggerColorProfile alloc] initWithForegroundColor:txtColor
  795. backgroundColor:bgColor
  796. flag:(DDLogFlag)0
  797. context:0];
  798. NSLogInfo(@"DDTTYLogger: newColorProfile: %@", newColorProfile);
  799. self->_colorProfilesDict[tag] = newColorProfile;
  800. }
  801. };
  802. // The design of the setter logic below is taken from the DDAbstractLogger implementation.
  803. // For documentation please refer to the DDAbstractLogger implementation.
  804. if ([self isOnInternalLoggerQueue]) {
  805. block();
  806. } else {
  807. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  808. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  809. dispatch_async(globalLoggingQueue, ^{
  810. dispatch_async(self.loggerQueue, block);
  811. });
  812. }
  813. }
  814. - (void)clearColorsForFlag:(DDLogFlag)mask {
  815. [self clearColorsForFlag:mask context:0];
  816. }
  817. - (void)clearColorsForFlag:(DDLogFlag)mask context:(NSInteger)context {
  818. dispatch_block_t block = ^{
  819. @autoreleasepool {
  820. NSUInteger i = 0;
  821. for (DDTTYLoggerColorProfile *colorProfile in self->_colorProfilesArray) {
  822. if ((colorProfile->mask == mask) && (colorProfile->context == context)) {
  823. break;
  824. }
  825. i++;
  826. }
  827. if (i < [self->_colorProfilesArray count]) {
  828. [self->_colorProfilesArray removeObjectAtIndex:i];
  829. }
  830. }
  831. };
  832. // The design of the setter logic below is taken from the DDAbstractLogger implementation.
  833. // For documentation please refer to the DDAbstractLogger implementation.
  834. if ([self isOnInternalLoggerQueue]) {
  835. block();
  836. } else {
  837. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  838. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  839. dispatch_async(globalLoggingQueue, ^{
  840. dispatch_async(self.loggerQueue, block);
  841. });
  842. }
  843. }
  844. - (void)clearColorsForTag:(id <NSCopying>)tag {
  845. NSAssert([(id < NSObject >) tag conformsToProtocol: @protocol(NSCopying)], @"Invalid tag");
  846. dispatch_block_t block = ^{
  847. @autoreleasepool {
  848. [self->_colorProfilesDict removeObjectForKey:tag];
  849. }
  850. };
  851. // The design of the setter logic below is taken from the DDAbstractLogger implementation.
  852. // For documentation please refer to the DDAbstractLogger implementation.
  853. if ([self isOnInternalLoggerQueue]) {
  854. block();
  855. } else {
  856. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  857. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  858. dispatch_async(globalLoggingQueue, ^{
  859. dispatch_async(self.loggerQueue, block);
  860. });
  861. }
  862. }
  863. - (void)clearColorsForAllFlags {
  864. dispatch_block_t block = ^{
  865. @autoreleasepool {
  866. [self->_colorProfilesArray removeAllObjects];
  867. }
  868. };
  869. // The design of the setter logic below is taken from the DDAbstractLogger implementation.
  870. // For documentation please refer to the DDAbstractLogger implementation.
  871. if ([self isOnInternalLoggerQueue]) {
  872. block();
  873. } else {
  874. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  875. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  876. dispatch_async(globalLoggingQueue, ^{
  877. dispatch_async(self.loggerQueue, block);
  878. });
  879. }
  880. }
  881. - (void)clearColorsForAllTags {
  882. dispatch_block_t block = ^{
  883. @autoreleasepool {
  884. [self->_colorProfilesDict removeAllObjects];
  885. }
  886. };
  887. // The design of the setter logic below is taken from the DDAbstractLogger implementation.
  888. // For documentation please refer to the DDAbstractLogger implementation.
  889. if ([self isOnInternalLoggerQueue]) {
  890. block();
  891. } else {
  892. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  893. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  894. dispatch_async(globalLoggingQueue, ^{
  895. dispatch_async(self.loggerQueue, block);
  896. });
  897. }
  898. }
  899. - (void)clearAllColors {
  900. dispatch_block_t block = ^{
  901. @autoreleasepool {
  902. [self->_colorProfilesArray removeAllObjects];
  903. [self->_colorProfilesDict removeAllObjects];
  904. }
  905. };
  906. // The design of the setter logic below is taken from the DDAbstractLogger implementation.
  907. // For documentation please refer to the DDAbstractLogger implementation.
  908. if ([self isOnInternalLoggerQueue]) {
  909. block();
  910. } else {
  911. dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue];
  912. NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure");
  913. dispatch_async(globalLoggingQueue, ^{
  914. dispatch_async(self.loggerQueue, block);
  915. });
  916. }
  917. }
  918. - (void)logMessage:(DDLogMessage *)logMessage {
  919. NSString *logMsg = logMessage->_message;
  920. BOOL isFormatted = NO;
  921. if (_logFormatter) {
  922. logMsg = [_logFormatter formatLogMessage:logMessage];
  923. isFormatted = logMsg != logMessage->_message;
  924. }
  925. if (logMsg) {
  926. // Search for a color profile associated with the log message
  927. DDTTYLoggerColorProfile *colorProfile = nil;
  928. if (_colorsEnabled) {
  929. if (logMessage->_tag) {
  930. colorProfile = _colorProfilesDict[logMessage->_tag];
  931. }
  932. if (colorProfile == nil) {
  933. for (DDTTYLoggerColorProfile *cp in _colorProfilesArray) {
  934. if (logMessage->_flag & cp->mask) {
  935. // Color profile set for this context?
  936. if (logMessage->_context == cp->context) {
  937. colorProfile = cp;
  938. // Stop searching
  939. break;
  940. }
  941. // Check if LOG_CONTEXT_ALL was specified as a default color for this flag
  942. if (cp->context == LOG_CONTEXT_ALL) {
  943. colorProfile = cp;
  944. // We don't break to keep searching for more specific color profiles for the context
  945. }
  946. }
  947. }
  948. }
  949. }
  950. // Convert log message to C string.
  951. //
  952. // We use the stack instead of the heap for speed if possible.
  953. // But we're extra cautious to avoid a stack overflow.
  954. NSUInteger msgLen = [logMsg lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  955. const BOOL useStack = msgLen < (1024 * 4);
  956. char msgStack[useStack ? (msgLen + 1) : 1]; // Analyzer doesn't like zero-size array, hence the 1
  957. char *msg = useStack ? msgStack : (char *)malloc(msgLen + 1);
  958. if (msg == NULL) {
  959. return;
  960. }
  961. BOOL logMsgEnc = [logMsg getCString:msg maxLength:(msgLen + 1) encoding:NSUTF8StringEncoding];
  962. if (!logMsgEnc) {
  963. if (!useStack && msg != NULL) {
  964. free(msg);
  965. }
  966. return;
  967. }
  968. // Write the log message to STDERR
  969. if (isFormatted) {
  970. // The log message has already been formatted.
  971. int iovec_len = (_automaticallyAppendNewlineForCustomFormatters) ? 5 : 4;
  972. struct iovec v[iovec_len];
  973. if (colorProfile) {
  974. v[0].iov_base = colorProfile->fgCode;
  975. v[0].iov_len = colorProfile->fgCodeLen;
  976. v[1].iov_base = colorProfile->bgCode;
  977. v[1].iov_len = colorProfile->bgCodeLen;
  978. v[iovec_len - 1].iov_base = colorProfile->resetCode;
  979. v[iovec_len - 1].iov_len = colorProfile->resetCodeLen;
  980. } else {
  981. v[0].iov_base = "";
  982. v[0].iov_len = 0;
  983. v[1].iov_base = "";
  984. v[1].iov_len = 0;
  985. v[iovec_len - 1].iov_base = "";
  986. v[iovec_len - 1].iov_len = 0;
  987. }
  988. v[2].iov_base = (char *)msg;
  989. v[2].iov_len = msgLen;
  990. if (iovec_len == 5) {
  991. v[3].iov_base = "\n";
  992. v[3].iov_len = (msg[msgLen] == '\n') ? 0 : 1;
  993. }
  994. writev(STDERR_FILENO, v, iovec_len);
  995. } else {
  996. // The log message is unformatted, so apply standard NSLog style formatting.
  997. int len;
  998. char ts[24] = "";
  999. size_t tsLen = 0;
  1000. // Calculate timestamp.
  1001. // The technique below is faster than using NSDateFormatter.
  1002. if (logMessage->_timestamp) {
  1003. NSTimeInterval epoch = [logMessage->_timestamp timeIntervalSince1970];
  1004. struct tm tm;
  1005. time_t time = (time_t)epoch;
  1006. (void)localtime_r(&time, &tm);
  1007. int milliseconds = (int)((epoch - floor(epoch)) * 1000.0);
  1008. len = snprintf(ts, 24, "%04d-%02d-%02d %02d:%02d:%02d:%03d", // yyyy-MM-dd HH:mm:ss:SSS
  1009. tm.tm_year + 1900,
  1010. tm.tm_mon + 1,
  1011. tm.tm_mday,
  1012. tm.tm_hour,
  1013. tm.tm_min,
  1014. tm.tm_sec, milliseconds);
  1015. tsLen = (NSUInteger)MAX(MIN(24 - 1, len), 0);
  1016. }
  1017. // Calculate thread ID
  1018. //
  1019. // How many characters do we need for the thread id?
  1020. // logMessage->machThreadID is of type mach_port_t, which is an unsigned int.
  1021. //
  1022. // 1 hex char = 4 bits
  1023. // 8 hex chars for 32 bit, plus ending '\0' = 9
  1024. char tid[9];
  1025. len = snprintf(tid, 9, "%s", [logMessage->_threadID cStringUsingEncoding:NSUTF8StringEncoding]);
  1026. size_t tidLen = (NSUInteger)MAX(MIN(9 - 1, len), 0);
  1027. // Here is our format: "%s %s[%i:%s] %s", timestamp, appName, processID, threadID, logMsg
  1028. struct iovec v[13];
  1029. if (colorProfile) {
  1030. v[0].iov_base = colorProfile->fgCode;
  1031. v[0].iov_len = colorProfile->fgCodeLen;
  1032. v[1].iov_base = colorProfile->bgCode;
  1033. v[1].iov_len = colorProfile->bgCodeLen;
  1034. v[12].iov_base = colorProfile->resetCode;
  1035. v[12].iov_len = colorProfile->resetCodeLen;
  1036. } else {
  1037. v[0].iov_base = "";
  1038. v[0].iov_len = 0;
  1039. v[1].iov_base = "";
  1040. v[1].iov_len = 0;
  1041. v[12].iov_base = "";
  1042. v[12].iov_len = 0;
  1043. }
  1044. v[2].iov_base = ts;
  1045. v[2].iov_len = tsLen;
  1046. v[3].iov_base = " ";
  1047. v[3].iov_len = 1;
  1048. v[4].iov_base = _app;
  1049. v[4].iov_len = _appLen;
  1050. v[5].iov_base = "[";
  1051. v[5].iov_len = 1;
  1052. v[6].iov_base = _pid;
  1053. v[6].iov_len = _pidLen;
  1054. v[7].iov_base = ":";
  1055. v[7].iov_len = 1;
  1056. v[8].iov_base = tid;
  1057. v[8].iov_len = MIN((size_t)8, tidLen); // snprintf doesn't return what you might think
  1058. v[9].iov_base = "] ";
  1059. v[9].iov_len = 2;
  1060. v[10].iov_base = (char *)msg;
  1061. v[10].iov_len = msgLen;
  1062. v[11].iov_base = "\n";
  1063. v[11].iov_len = (msg[msgLen] == '\n') ? 0 : 1;
  1064. writev(STDERR_FILENO, v, 13);
  1065. }
  1066. if (!useStack) {
  1067. free(msg);
  1068. }
  1069. }
  1070. }
  1071. - (NSString *)loggerName {
  1072. return @"cocoa.lumberjack.ttyLogger";
  1073. }
  1074. @end
  1075. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1076. @implementation DDTTYLoggerColorProfile
  1077. - (instancetype)initWithForegroundColor:(DDColor *)fgColor backgroundColor:(DDColor *)bgColor flag:(DDLogFlag)aMask context:(NSInteger)ctxt {
  1078. if ((self = [super init])) {
  1079. mask = aMask;
  1080. context = ctxt;
  1081. CGFloat r, g, b;
  1082. if (fgColor) {
  1083. [DDTTYLogger getRed:&r green:&g blue:&b fromColor:fgColor];
  1084. fg_r = (uint8_t)(r * 255.0f);
  1085. fg_g = (uint8_t)(g * 255.0f);
  1086. fg_b = (uint8_t)(b * 255.0f);
  1087. }
  1088. if (bgColor) {
  1089. [DDTTYLogger getRed:&r green:&g blue:&b fromColor:bgColor];
  1090. bg_r = (uint8_t)(r * 255.0f);
  1091. bg_g = (uint8_t)(g * 255.0f);
  1092. bg_b = (uint8_t)(b * 255.0f);
  1093. }
  1094. if (fgColor && isaColorTTY) {
  1095. // Map foreground color to closest available shell color
  1096. fgCodeIndex = [DDTTYLogger codeIndexForColor:fgColor];
  1097. fgCodeRaw = codes_fg[fgCodeIndex];
  1098. NSString *escapeSeq = @"\033[";
  1099. NSUInteger len1 = [escapeSeq lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  1100. NSUInteger len2 = [fgCodeRaw lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  1101. BOOL escapeSeqEnc = [escapeSeq getCString:(fgCode) maxLength:(len1 + 1) encoding:NSUTF8StringEncoding];
  1102. BOOL fgCodeRawEsc = [fgCodeRaw getCString:(fgCode + len1) maxLength:(len2 + 1) encoding:NSUTF8StringEncoding];
  1103. if (!escapeSeqEnc || !fgCodeRawEsc) {
  1104. return nil;
  1105. }
  1106. fgCodeLen = len1 + len2;
  1107. } else if (fgColor && isaXcodeColorTTY) {
  1108. // Convert foreground color to color code sequence
  1109. const char *escapeSeq = XCODE_COLORS_ESCAPE_SEQ;
  1110. int result = snprintf(fgCode, 24, "%sfg%u,%u,%u;", escapeSeq, fg_r, fg_g, fg_b);
  1111. fgCodeLen = (NSUInteger)MAX(MIN(result, (24 - 1)), 0);
  1112. } else {
  1113. // No foreground color or no color support
  1114. fgCode[0] = '\0';
  1115. fgCodeLen = 0;
  1116. }
  1117. if (bgColor && isaColorTTY) {
  1118. // Map background color to closest available shell color
  1119. bgCodeIndex = [DDTTYLogger codeIndexForColor:bgColor];
  1120. bgCodeRaw = codes_bg[bgCodeIndex];
  1121. NSString *escapeSeq = @"\033[";
  1122. NSUInteger len1 = [escapeSeq lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  1123. NSUInteger len2 = [bgCodeRaw lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  1124. BOOL escapeSeqEnc = [escapeSeq getCString:(bgCode) maxLength:(len1 + 1) encoding:NSUTF8StringEncoding];
  1125. BOOL bgCodeRawEsc = [bgCodeRaw getCString:(bgCode + len1) maxLength:(len2 + 1) encoding:NSUTF8StringEncoding];
  1126. if (!escapeSeqEnc || !bgCodeRawEsc) {
  1127. return nil;
  1128. }
  1129. bgCodeLen = len1 + len2;
  1130. } else if (bgColor && isaXcodeColorTTY) {
  1131. // Convert background color to color code sequence
  1132. const char *escapeSeq = XCODE_COLORS_ESCAPE_SEQ;
  1133. int result = snprintf(bgCode, 24, "%sbg%u,%u,%u;", escapeSeq, bg_r, bg_g, bg_b);
  1134. bgCodeLen = (NSUInteger)MAX(MIN(result, (24 - 1)), 0);
  1135. } else {
  1136. // No background color or no color support
  1137. bgCode[0] = '\0';
  1138. bgCodeLen = 0;
  1139. }
  1140. if (isaColorTTY) {
  1141. resetCodeLen = (NSUInteger)MAX(snprintf(resetCode, 8, "\033[0m"), 0);
  1142. } else if (isaXcodeColorTTY) {
  1143. resetCodeLen = (NSUInteger)MAX(snprintf(resetCode, 8, XCODE_COLORS_RESET), 0);
  1144. } else {
  1145. resetCode[0] = '\0';
  1146. resetCodeLen = 0;
  1147. }
  1148. }
  1149. return self;
  1150. }
  1151. - (NSString *)description {
  1152. return [NSString stringWithFormat:
  1153. @"<DDTTYLoggerColorProfile: %p mask:%i ctxt:%ld fg:%u,%u,%u bg:%u,%u,%u fgCode:%@ bgCode:%@>",
  1154. self, (int)mask, (long)context, fg_r, fg_g, fg_b, bg_r, bg_g, bg_b, fgCodeRaw, bgCodeRaw];
  1155. }
  1156. @end