/*
 * log.c
 *
 * Generic log module.
 *
 * Usage: loginit(ProcessName, NameOfLogFile, LogLevel, appendMode);
 *        logging(level, msg, ...);
 *
 *  Copyright (C) 2001 Uwe Maier <Uwe.Maier@nice.de>
 *  Copyright (C) 2001 - 2005 Bernd Schumacher Hewlett Packard Consulting
 *                            <bernd.schumacher@hp.com>
 *  Copyright (C) 2005 - 2009 Jochen Friedrich <jochen@scram.de>
 *
 *  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 3 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 in the COPYING file at the
 *  root directory of this project for more details.
 *
 */

/* --- include section --- */
#include "log.h"

#include <stdarg.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

/* --- private variables --- */
static char    *fp_pname;
static char    *fp_fname;
static int      fp_level;
static int      fp_appmode;
static FILE    *fp_log = NULL;

/* --- public functions --- */

void
loginit (char *pname, char *fname, int loglevel, int appendMode)
{
  fp_pname = pname;
  fp_fname = fname;
  fp_level = loglevel;
  fp_appmode = appendMode;
}

void
logging (int level, char *fmt, ...)
{
  va_list         ap;
  char            tbuf[24];
  time_t          curtime;
  int             fp_fd;


  /* level of current message too high ? */
  if (level > fp_level)
  {
    return;
  }

  /* open the log file, if necessary */
  if (!fp_log)
  {
    fp_fd = open (fp_fname, O_CREAT|O_EXCL|O_WRONLY, S_IREAD|S_IWRITE);
    if (fp_fd < 0)
    {
      fprintf (stderr,
               "Cannot open log file '%s' [%s]\n", fp_fname,
               strerror (errno));
      exit (1);
    }

    fp_log = fdopen (fp_fd, "w");

    if (fp_log == NULL)
    {
      fprintf (stderr,
               "Cannot open log file '%s' [%s]\n", fp_fname,
               strerror (errno));
      exit (1);
    }
  }

  /* construct the log entry */
  time (&curtime);
  strftime (tbuf, sizeof (tbuf), "%Y%m%d.%H%M%S", localtime (&curtime));
  fprintf (fp_log, "%s (%s-%d): ", tbuf, fp_pname, getpid ());

  va_start (ap, fmt);
  vfprintf (fp_log, fmt, ap);
  va_end (ap);

  fprintf (fp_log, "\n");
  fflush (fp_log);
}
