1
0

log.cpp 11 KB

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