

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <errno.h>
#include <syslog.h>


#include "errormsg.h"

char *logfilename = NULL;
int logmode = 2;
int loglevel = 1;

void setlogfile(char *fname)
  {
  if (fname==NULL) return;
  if (logfilename!=NULL) free(logfilename);
  logfilename=strdup(fname);
  return;
  }

void setlogmode(int lmode)
  {
  logmode=lmode;
  return;
  }

void setloglevel(int level)
  {
  loglevel=level;
  return;
  }


void logprint(int level, char *format_str, ...)
{
if (level>loglevel) return;
va_list ap;
FILE *lfh;
char buf[28];
time_t ttime;
struct tm *ptm;
  
if (logmode&1) {  
    ttime=time(NULL);
    ptm=localtime(&ttime);
    strftime(buf,sizeof(buf),"%Y-%m-%d %H:%M:%S ",ptm);
    lfh=stderr;
    if (logfilename==NULL)
      {
      if (NULL == (lfh=fopen("/var/log/video2mem.log","a+")))
        {
        fprintf(stderr,"Error:  <%i> %s (%s)",errno,strerror(errno),"/var/log/video2mem.log");
        lfh=stderr;
        }
      }
      else
      {
      if (NULL == (lfh=fopen(logfilename,"a+")))
        {
        fprintf(stderr,"Error:  <%i> %s (%s)",errno,strerror(errno),logfilename);
        lfh=stderr;
        }
      }
    va_start(ap,format_str);
    fprintf(lfh,"%s",buf);
    (void)vfprintf(lfh,format_str,ap);
    fprintf(lfh,"\n");
    va_end(ap);
    if (lfh!=stderr) fclose(lfh); else fprintf(stderr,"\r");
    }
  if (logmode&2)
    {
    if (logfilename==NULL) openlog("video2mem",LOG_PID,LOG_DAEMON); else openlog(logfilename,LOG_PID,LOG_MAIL);
    va_start(ap,format_str);
    vsyslog(LOG_ERR,format_str,ap);
    va_end(ap);
    closelog();
    }
  if (logmode&4)
    {
    va_start(ap,format_str);
    (void)vfprintf(stderr,format_str,ap);
    va_end(ap);
    closelog();
    }
  return;
  }
