view logging.c @ 223:7875436125dd

Variable names clarification and cleanup
author Daniele Nicolodi <daniele.nicolodi@obspm.fr>
date Thu, 18 Sep 2014 18:03:27 +0200
parents 111610d871af
children 28a56e4c06a4
line wrap: on
line source

#include <ansi_c.h>
#include <inifile.h>
#include <lowlvlio.h>

#include "config.h"
#include "logging.h"

/* this refers to the event time defined as a global variable in the main program */
extern double utc;
/* main panel id */
extern unsigned int MainPanel;


int __logger_init(struct logger *l, void(*onerror)(int, const char *))
{
	int rv, panel;
	char path[MAX_PATHNAME_LEN], *filename;
	
	l->onerror = onerror;
	l->fd = -1;
	
	panel = LoadPanel(0, "FXAnalyse.uir", LOGGING);
	if (panel < 0)
		return -1;
	l->panel = panel;
	
	/* configuration file path */
	GetIniFilePath(path); 

	/* load configuration file */ 
	IniText configuration = Ini_New(TRUE);
	Ini_ReadFromFile(configuration, path);

	/* logging file name */
	rv = Ini_GetStringCopy(configuration, "logging", "filename", &filename);
	if (rv > 0)
		l->fd = open(filename, O_CREAT|O_WRONLY|O_APPEND, 00744);
		
	free(filename);
	Ini_Dispose(configuration);
	
	return 0;
}


void __logmessage(struct logger *l, enum loglevel level, const char *frmt, ...)
{
	static const char *levels[] = {
		"DEBUG",
		"INFO",
		"WARNING",
		"ERROR",
	};

	char msg[1024];
	int len = 0;
	
	/* timestamp */
	len += sprintf(msg, "%014.3f ", utc);
	time_t now = time(NULL);
	struct tm *t = localtime(&now);
	len += strftime(msg + len, sizeof(msg) - len, "%d-%m-%Y %H:%M:%S ", t);
	
	/* level */
	len += snprintf(msg + len, sizeof(msg) - len, "%s: ", levels[level]);
	
	/* message */
	va_list args;
	va_start(args, frmt);
	len += vsnprintf(msg + len, sizeof(msg) - len, frmt, args);
	va_end(args);
	
	/* newline */
	len = MIN(len, sizeof(msg) - 3);
	msg[len++] = '\r';
	msg[len++] = '\n';
	
	/* string terminator */
	msg[len] = '\0';
	
	/* display message */
	SetCtrlVal(l->panel, LOGGING_LOGGING, msg);
	
	/* report error */
	if (level == ERROR)
		l->onerror(level, msg);

	/* write to log file */
	if (l->fd >= 0)
		write(l->fd, msg, len);
}