File: log.c

package info (click to toggle)
psensor 0.6.2.17-2
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 2,388 kB
  • sloc: ansic: 4,994; sh: 4,385; perl: 2,498; makefile: 245; sed: 16
file content (119 lines) | stat: -rw-r--r-- 2,340 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*
 * Copyright (C) 2010-2012 jeanfi@gmail.com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */
#include <locale.h>
#include <libintl.h>
#define _(str) gettext(str)

#include <stdarg.h>
#include <stdio.h>
#include <sys/time.h>

#include "log.h"

static FILE *file;
int log_level =  LOG_WARN;

void log_open(const char *path)
{
	file = fopen(path, "a");

	if (!file)
		log_printf(LOG_ERR, _("Cannot open log file: %s"), path);
}

void log_close()
{
	if (!file)
		return ;

	fclose(file);

	file = NULL;
}


#define LOG_BUFFER 4096
static void vlogf(int lvl, const char *fmt, va_list ap)
{
	struct timeval tv;
	char buffer[1 + LOG_BUFFER];
	char *lvl_str;
	FILE *stdf;

	if (lvl > LOG_INFO && (!file || lvl > log_level))
		return ;

	vsnprintf(buffer, LOG_BUFFER, fmt, ap);
	buffer[LOG_BUFFER] = '\0';

	if (gettimeofday(&tv, NULL) != 0)
		timerclear(&tv);

	switch (lvl) {
	case LOG_WARN:
		lvl_str = "[WARN]";
		break;
	case LOG_ERR:
		lvl_str = "[ERR]";
		break;
	case LOG_DEBUG:
		lvl_str = "[DEBUG]";
		break;
	case LOG_INFO:
		lvl_str = "[INFO]";
		break;
	default:
		lvl_str = "[??]";
	}

	if (file && lvl <= log_level) {
		fprintf(file, "[%ld] %s %s\n", tv.tv_sec, lvl_str, buffer);
		fflush(file);
	}

	if (lvl <= LOG_INFO) {
		if (lvl == LOG_WARN || lvl == LOG_ERR)
			stdf = stderr;
		else
			stdf = stdout;

		fprintf(stdf, "[%ld] %s %s\n", tv.tv_sec, lvl_str, buffer);
	}
}

void log_printf(int lvl, const char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	vlogf(lvl, fmt, ap);
	va_end(ap);
}

void log_debug(const char *fmt, ...)
{
	va_list ap;

	if (log_level < LOG_DEBUG)
		return ;

	va_start(ap, fmt);
	vlogf(LOG_DEBUG, fmt, ap);
	va_end(ap);
}