2121#endif // defined(_WIN32)
2222
2323int common_log_verbosity_thold = LOG_DEFAULT_LLAMA;
24+ static ggml_log_callback g_external_log_callback = nullptr ;
25+ static void * g_external_log_user_data = nullptr ;
26+ static bool g_stdout_enabled = true ;
2427
2528void common_log_set_verbosity_thold (int verbosity) {
2629 common_log_verbosity_thold = verbosity;
@@ -101,14 +104,18 @@ struct common_log_entry {
101104 return ;
102105 }
103106
104- fcur = stdout;
107+ if (g_stdout_enabled) {
108+ fcur = stdout;
105109
106- if (level != GGML_LOG_LEVEL_NONE) {
107- fcur = stderr;
110+ if (level != GGML_LOG_LEVEL_NONE) {
111+ fcur = stderr;
112+ }
113+ } else {
114+ fcur = nullptr ; // suppress stdio prints
108115 }
109116 }
110117
111- if (level != GGML_LOG_LEVEL_NONE && level != GGML_LOG_LEVEL_CONT && prefix) {
118+ if (fcur && level != GGML_LOG_LEVEL_NONE && level != GGML_LOG_LEVEL_CONT && prefix) {
112119 if (timestamp) {
113120 // [M.s.ms.us]
114121 fprintf (fcur, " %s%d.%02d.%03d.%03d%s " ,
@@ -130,13 +137,22 @@ struct common_log_entry {
130137 }
131138 }
132139
133- fprintf (fcur, " %s" , msg.data ());
140+ if (fcur) {
141+ fprintf (fcur, " %s" , msg.data ());
142+ }
134143
135- if (level == GGML_LOG_LEVEL_WARN || level == GGML_LOG_LEVEL_ERROR || level == GGML_LOG_LEVEL_DEBUG) {
144+ if (fcur && ( level == GGML_LOG_LEVEL_WARN || level == GGML_LOG_LEVEL_ERROR || level == GGML_LOG_LEVEL_DEBUG) ) {
136145 fprintf (fcur, " %s" , g_col[COMMON_LOG_COL_DEFAULT]);
137146 }
138147
139- fflush (fcur);
148+ if (fcur) {
149+ fflush (fcur);
150+ }
151+
152+ // forward to external callback only once per entry (when not printing to the file sink)
153+ if (!file && g_external_log_callback) {
154+ g_external_log_callback (level, msg.data (), g_external_log_user_data);
155+ }
140156 }
141157};
142158
@@ -442,3 +458,12 @@ void common_log_set_prefix(struct common_log * log, bool prefix) {
442458void common_log_set_timestamps (struct common_log * log, bool timestamps) {
443459 log->set_timestamps (timestamps);
444460}
461+
462+ void common_log_set_callback (ggml_log_callback log_callback, void * user_data) {
463+ g_external_log_callback = log_callback;
464+ g_external_log_user_data = user_data;
465+ }
466+
467+ void common_log_set_stdout_enabled (bool enabled) {
468+ g_stdout_enabled = enabled;
469+ }
0 commit comments