1
0

log.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. #include "log.h"
  2. #include <chrono>
  3. #include <condition_variable>
  4. #include <cstdarg>
  5. #include <cstdio>
  6. #include <cstdlib>
  7. #include <cstring>
  8. #include <mutex>
  9. #include <sstream>
  10. #include <thread>
  11. #include <vector>
  12. #if defined(_WIN32)
  13. # include <io.h>
  14. # include <windows.h>
  15. # define isatty _isatty
  16. # define fileno _fileno
  17. #else
  18. # include <unistd.h>
  19. #endif // defined(_WIN32)
  20. int common_log_verbosity_thold = LOG_DEFAULT_LLAMA;
  21. void common_log_set_verbosity_thold(int verbosity) {
  22. common_log_verbosity_thold = verbosity;
  23. }
  24. // Auto-detect if colors should be enabled based on terminal and environment
  25. static bool common_log_should_use_colors_auto() {
  26. // Check NO_COLOR environment variable (https://no-color.org/)
  27. if (const char * no_color = std::getenv("NO_COLOR")) {
  28. if (no_color[0] != '\0') {
  29. return false;
  30. }
  31. }
  32. // Check TERM environment variable
  33. if (const char * term = std::getenv("TERM")) {
  34. if (std::strcmp(term, "dumb") == 0) {
  35. return false;
  36. }
  37. }
  38. // Check if stdout and stderr are connected to a terminal
  39. // We check both because log messages can go to either
  40. bool stdout_is_tty = isatty(fileno(stdout));
  41. bool stderr_is_tty = isatty(fileno(stderr));
  42. return stdout_is_tty || stderr_is_tty;
  43. }
  44. static int64_t t_us() {
  45. return std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  46. }
  47. // colors
  48. enum common_log_col : int {
  49. COMMON_LOG_COL_DEFAULT = 0,
  50. COMMON_LOG_COL_BOLD,
  51. COMMON_LOG_COL_RED,
  52. COMMON_LOG_COL_GREEN,
  53. COMMON_LOG_COL_YELLOW,
  54. COMMON_LOG_COL_BLUE,
  55. COMMON_LOG_COL_MAGENTA,
  56. COMMON_LOG_COL_CYAN,
  57. COMMON_LOG_COL_WHITE,
  58. };
  59. // disable colors by default
  60. static std::vector<const char *> g_col = {
  61. "",
  62. "",
  63. "",
  64. "",
  65. "",
  66. "",
  67. "",
  68. "",
  69. "",
  70. };
  71. struct common_log_entry {
  72. enum ggml_log_level level;
  73. bool prefix;
  74. int64_t timestamp;
  75. std::vector<char> msg;
  76. // signals the worker thread to stop
  77. bool is_end;
  78. void print(FILE * file = nullptr) const {
  79. FILE * fcur = file;
  80. if (!fcur) {
  81. // stderr displays DBG messages only when their verbosity level is not higher than the threshold
  82. // these messages will still be logged to a file
  83. if (level == GGML_LOG_LEVEL_DEBUG && common_log_verbosity_thold < LOG_DEFAULT_DEBUG) {
  84. return;
  85. }
  86. fcur = stdout;
  87. if (level != GGML_LOG_LEVEL_NONE) {
  88. fcur = stderr;
  89. }
  90. }
  91. if (level != GGML_LOG_LEVEL_NONE && level != GGML_LOG_LEVEL_CONT && prefix) {
  92. if (timestamp) {
  93. // [M.s.ms.us]
  94. fprintf(fcur, "%s%d.%02d.%03d.%03d%s ",
  95. g_col[COMMON_LOG_COL_BLUE],
  96. (int) (timestamp / 1000000 / 60),
  97. (int) (timestamp / 1000000 % 60),
  98. (int) (timestamp / 1000 % 1000),
  99. (int) (timestamp % 1000),
  100. g_col[COMMON_LOG_COL_DEFAULT]);
  101. }
  102. switch (level) {
  103. case GGML_LOG_LEVEL_INFO: fprintf(fcur, "%sI %s", g_col[COMMON_LOG_COL_GREEN], g_col[COMMON_LOG_COL_DEFAULT]); break;
  104. case GGML_LOG_LEVEL_WARN: fprintf(fcur, "%sW %s", g_col[COMMON_LOG_COL_MAGENTA], "" ); break;
  105. case GGML_LOG_LEVEL_ERROR: fprintf(fcur, "%sE %s", g_col[COMMON_LOG_COL_RED], "" ); break;
  106. case GGML_LOG_LEVEL_DEBUG: fprintf(fcur, "%sD %s", g_col[COMMON_LOG_COL_YELLOW], "" ); break;
  107. default:
  108. break;
  109. }
  110. }
  111. fprintf(fcur, "%s", msg.data());
  112. if (level == GGML_LOG_LEVEL_WARN || level == GGML_LOG_LEVEL_ERROR || level == GGML_LOG_LEVEL_DEBUG) {
  113. fprintf(fcur, "%s", g_col[COMMON_LOG_COL_DEFAULT]);
  114. }
  115. fflush(fcur);
  116. }
  117. };
  118. struct common_log {
  119. // default capacity - will be expanded if needed
  120. common_log() : common_log(256) {}
  121. common_log(size_t capacity) {
  122. file = nullptr;
  123. prefix = false;
  124. timestamps = false;
  125. running = false;
  126. t_start = t_us();
  127. // initial message size - will be expanded if longer messages arrive
  128. entries.resize(capacity);
  129. for (auto & entry : entries) {
  130. entry.msg.resize(256);
  131. }
  132. head = 0;
  133. tail = 0;
  134. resume();
  135. }
  136. ~common_log() {
  137. pause();
  138. if (file) {
  139. fclose(file);
  140. }
  141. }
  142. private:
  143. std::mutex mtx;
  144. std::thread thrd;
  145. std::condition_variable cv;
  146. FILE * file;
  147. bool prefix;
  148. bool timestamps;
  149. bool running;
  150. int64_t t_start;
  151. // ring buffer of entries
  152. std::vector<common_log_entry> entries;
  153. size_t head;
  154. size_t tail;
  155. // worker thread copies into this
  156. common_log_entry cur;
  157. public:
  158. void add(enum ggml_log_level level, const char * fmt, va_list args) {
  159. std::lock_guard<std::mutex> lock(mtx);
  160. if (!running) {
  161. // discard messages while the worker thread is paused
  162. return;
  163. }
  164. auto & entry = entries[tail];
  165. {
  166. // cannot use args twice, so make a copy in case we need to expand the buffer
  167. va_list args_copy;
  168. va_copy(args_copy, args);
  169. #if 1
  170. const size_t n = vsnprintf(entry.msg.data(), entry.msg.size(), fmt, args);
  171. if (n >= entry.msg.size()) {
  172. entry.msg.resize(n + 1);
  173. vsnprintf(entry.msg.data(), entry.msg.size(), fmt, args_copy);
  174. }
  175. #else
  176. // hack for bolding arguments
  177. std::stringstream ss;
  178. for (int i = 0; fmt[i] != 0; i++) {
  179. if (fmt[i] == '%') {
  180. ss << LOG_COL_BOLD;
  181. while (fmt[i] != ' ' && fmt[i] != ')' && fmt[i] != ']' && fmt[i] != 0) ss << fmt[i++];
  182. ss << LOG_COL_DEFAULT;
  183. if (fmt[i] == 0) break;
  184. }
  185. ss << fmt[i];
  186. }
  187. const size_t n = vsnprintf(entry.msg.data(), entry.msg.size(), ss.str().c_str(), args);
  188. if (n >= entry.msg.size()) {
  189. entry.msg.resize(n + 1);
  190. vsnprintf(entry.msg.data(), entry.msg.size(), ss.str().c_str(), args_copy);
  191. }
  192. #endif
  193. va_end(args_copy);
  194. }
  195. entry.level = level;
  196. entry.prefix = prefix;
  197. entry.timestamp = 0;
  198. if (timestamps) {
  199. entry.timestamp = t_us() - t_start;
  200. }
  201. entry.is_end = false;
  202. tail = (tail + 1) % entries.size();
  203. if (tail == head) {
  204. // expand the buffer
  205. std::vector<common_log_entry> new_entries(2*entries.size());
  206. size_t new_tail = 0;
  207. do {
  208. new_entries[new_tail] = std::move(entries[head]);
  209. head = (head + 1) % entries.size();
  210. new_tail = (new_tail + 1);
  211. } while (head != tail);
  212. head = 0;
  213. tail = new_tail;
  214. for (size_t i = tail; i < new_entries.size(); i++) {
  215. new_entries[i].msg.resize(256);
  216. }
  217. entries = std::move(new_entries);
  218. }
  219. cv.notify_one();
  220. }
  221. void resume() {
  222. std::lock_guard<std::mutex> lock(mtx);
  223. if (running) {
  224. return;
  225. }
  226. running = true;
  227. thrd = std::thread([this]() {
  228. while (true) {
  229. {
  230. std::unique_lock<std::mutex> lock(mtx);
  231. cv.wait(lock, [this]() { return head != tail; });
  232. cur = entries[head];
  233. head = (head + 1) % entries.size();
  234. }
  235. if (cur.is_end) {
  236. break;
  237. }
  238. cur.print(); // stdout and stderr
  239. if (file) {
  240. cur.print(file);
  241. }
  242. }
  243. });
  244. }
  245. void pause() {
  246. {
  247. std::lock_guard<std::mutex> lock(mtx);
  248. if (!running) {
  249. return;
  250. }
  251. running = false;
  252. // push an entry to signal the worker thread to stop
  253. {
  254. auto & entry = entries[tail];
  255. entry.is_end = true;
  256. tail = (tail + 1) % entries.size();
  257. }
  258. cv.notify_one();
  259. }
  260. thrd.join();
  261. }
  262. void set_file(const char * path) {
  263. pause();
  264. if (file) {
  265. fclose(file);
  266. }
  267. if (path) {
  268. file = fopen(path, "w");
  269. } else {
  270. file = nullptr;
  271. }
  272. resume();
  273. }
  274. void set_colors(bool colors) {
  275. pause();
  276. if (colors) {
  277. g_col[COMMON_LOG_COL_DEFAULT] = LOG_COL_DEFAULT;
  278. g_col[COMMON_LOG_COL_BOLD] = LOG_COL_BOLD;
  279. g_col[COMMON_LOG_COL_RED] = LOG_COL_RED;
  280. g_col[COMMON_LOG_COL_GREEN] = LOG_COL_GREEN;
  281. g_col[COMMON_LOG_COL_YELLOW] = LOG_COL_YELLOW;
  282. g_col[COMMON_LOG_COL_BLUE] = LOG_COL_BLUE;
  283. g_col[COMMON_LOG_COL_MAGENTA] = LOG_COL_MAGENTA;
  284. g_col[COMMON_LOG_COL_CYAN] = LOG_COL_CYAN;
  285. g_col[COMMON_LOG_COL_WHITE] = LOG_COL_WHITE;
  286. } else {
  287. for (size_t i = 0; i < g_col.size(); i++) {
  288. g_col[i] = "";
  289. }
  290. }
  291. resume();
  292. }
  293. void set_prefix(bool prefix) {
  294. std::lock_guard<std::mutex> lock(mtx);
  295. this->prefix = prefix;
  296. }
  297. void set_timestamps(bool timestamps) {
  298. std::lock_guard<std::mutex> lock(mtx);
  299. this->timestamps = timestamps;
  300. }
  301. };
  302. //
  303. // public API
  304. //
  305. struct common_log * common_log_init() {
  306. return new common_log;
  307. }
  308. struct common_log * common_log_main() {
  309. static struct common_log log;
  310. static std::once_flag init_flag;
  311. std::call_once(init_flag, [&]() {
  312. // Set default to auto-detect colors
  313. log.set_colors(common_log_should_use_colors_auto());
  314. });
  315. return &log;
  316. }
  317. void common_log_pause(struct common_log * log) {
  318. log->pause();
  319. }
  320. void common_log_resume(struct common_log * log) {
  321. log->resume();
  322. }
  323. void common_log_free(struct common_log * log) {
  324. delete log;
  325. }
  326. void common_log_add(struct common_log * log, enum ggml_log_level level, const char * fmt, ...) {
  327. va_list args;
  328. va_start(args, fmt);
  329. log->add(level, fmt, args);
  330. va_end(args);
  331. }
  332. void common_log_set_file(struct common_log * log, const char * file) {
  333. log->set_file(file);
  334. }
  335. void common_log_set_colors(struct common_log * log, log_colors colors) {
  336. if (colors == LOG_COLORS_AUTO) {
  337. log->set_colors(common_log_should_use_colors_auto());
  338. return;
  339. }
  340. if (colors == LOG_COLORS_DISABLED) {
  341. log->set_colors(false);
  342. return;
  343. }
  344. GGML_ASSERT(colors == LOG_COLORS_ENABLED);
  345. log->set_colors(true);
  346. }
  347. void common_log_set_prefix(struct common_log * log, bool prefix) {
  348. log->set_prefix(prefix);
  349. }
  350. void common_log_set_timestamps(struct common_log * log, bool timestamps) {
  351. log->set_timestamps(timestamps);
  352. }
  353. void common_log_default_callback(enum ggml_log_level level, const char * text, void * /*user_data*/) {
  354. if (LOG_DEFAULT_LLAMA <= common_log_verbosity_thold) {
  355. common_log_add(common_log_main(), level, "%s", text);
  356. }
  357. }