website/index.html: Extend Feedback section (codeberg.org)
[a2jmidid.git] / log.c
blob4c7c51d2c39d56364de2051cbfac708c9dfc8d1b
1 /* -*- Mode: C ; c-basic-offset: 2 -*- */
2 /*
3 * ALSA SEQ < - > JACK MIDI bridge
5 * Copyright (c) 2008,2009,2010 Nedko Arnaudov <nedko@arnaudov.name>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; version 2 of the License.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include <stdbool.h>
22 #include <stdarg.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <stdlib.h>
27 #include <time.h>
28 #include <sys/stat.h>
30 #include "log.h"
31 #include "paths.h"
33 static ino_t g_log_file_ino;
34 static FILE * g_logfile = NULL;
36 static bool a2j_log_open(void)
38 struct stat st;
39 int ret;
40 int retry;
42 if (g_logfile != NULL)
44 ret = stat(g_a2j_log_path, &st);
45 if (ret != 0 || g_log_file_ino != st.st_ino)
47 fclose(g_logfile);
49 else
51 return true;
55 for (retry = 0; retry < 10; retry++)
57 g_logfile = fopen(g_a2j_log_path, "a");
58 if (g_logfile == NULL)
60 fprintf(stderr, "Cannot open a2jmidid log file \"%s\": %d (%s)\n", g_a2j_log_path, errno, strerror(errno));
61 return false;
64 ret = stat(g_a2j_log_path, &st);
65 if (ret == 0)
67 g_log_file_ino = st.st_ino;
68 return true;
71 fclose(g_logfile);
72 g_logfile = NULL;
75 fprintf(stderr, "Cannot stat just opened a2jmidid log file \"%s\": %d (%s). %d retries\n", g_a2j_log_path, errno, strerror(errno), retry);
76 return false;
79 bool a2j_log_init(bool use_logfile)
81 if (use_logfile)
83 return a2j_log_open();
86 return true;
89 void a2j_log_uninit(void)
91 if (g_logfile != NULL)
93 fclose(g_logfile);
97 void
98 a2j_log(
99 unsigned int level,
100 const char * format,
101 ...)
103 va_list ap;
104 FILE * stream;
105 time_t timestamp;
106 char timestamp_str[26];
108 if (g_logfile != NULL && a2j_log_open())
110 stream = g_logfile;
112 else
114 switch (level)
116 case A2J_LOG_LEVEL_DEBUG:
117 case A2J_LOG_LEVEL_INFO:
118 stream = stdout;
119 break;
120 case A2J_LOG_LEVEL_ERROR:
121 default:
122 stream = stderr;
126 if (g_logfile != NULL)
128 time(&timestamp);
129 ctime_r(&timestamp, timestamp_str);
130 timestamp_str[24] = 0;
132 fprintf(stream, "%s: ", timestamp_str);
135 va_start(ap, format);
136 vfprintf(stream, format, ap);
137 fflush(stream);
138 va_end(ap);