default log level set to LOG_WARN
[psensor.git] / src / lib / log.c
1 /*
2     Copyright (C) 2010-2011 jeanfi@gmail.com
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17     02110-1301 USA
18 */
19
20 #include <locale.h>
21 #include <libintl.h>
22 #define _(str) gettext(str)
23
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <sys/time.h>
27
28 #include "log.h"
29
30 static FILE *file;
31 int log_level =  LOG_WARN;
32
33 void log_open(const char *path, int lvl)
34 {
35         file = fopen(path, "a");
36
37         if (file)
38                 log_puts(LOG_INFO, "Start logging");
39         else
40                 fprintf(stderr, _("Cannot open log file: %s\n"), path);
41 }
42
43 void log_puts(int lvl, const char *msg)
44 {
45         log_printf(lvl, msg);
46 }
47
48 void log_close()
49 {
50         if (!file)
51                 return ;
52
53         fclose(file);
54
55         file = NULL;
56 }
57
58 #define LOG_BUFFER 4096
59 void log_printf(int lvl, const char *fmt, ...)
60 {
61         struct timeval tv;
62         static char buffer[1 + LOG_BUFFER];
63         va_list ap;
64         char *lvl_str;
65
66         if (!file || lvl > log_level)
67                 return ;
68
69         va_start(ap, fmt);
70         vsnprintf(buffer, LOG_BUFFER, fmt, ap);
71         buffer[LOG_BUFFER] = '\0';
72         va_end(ap);
73
74         if (gettimeofday(&tv, NULL) != 0)
75                 timerclear(&tv);
76
77         switch (lvl) {
78         case LOG_WARN:
79                 lvl_str = "[WARN]";
80                 break;
81         case LOG_ERR:
82                 lvl_str = "[ERR]";
83                 break;
84         case LOG_DEBUG:
85                 lvl_str = "[DEBUG]";
86                 break;
87         case LOG_INFO:
88                 lvl_str = "[INFO]";
89                 break;
90         default:
91                 lvl_str = "[??]";
92         }
93
94         fprintf(file, "[%ld] %s %s\n", tv.tv_sec, lvl_str, buffer);
95         fflush(file);
96 }
97