/* log_sys.c	Ver.1.0
 *
 *  Jun Takahashi, Nov.,1998
 */

#include <syslog.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "log_sys.h"

extern int	debug;	/* 0:normal/!0:debug	*/
static char	noident[1] = {'\0'};
static char	*_ident = noident;

/*
 *  ログをオープンする
 */
void log_open(char *ident, int logopt, int facility)
{
  /* デバッグモードのときはidentを_identに保存しておく	*/
  if(debug){
    if(_ident != noident){
      free(_ident);
    }
    _ident = malloc(strlen(ident)+1);
    strcpy(_ident, ident);
  }

  /* デバッグモードでないときはopenlog	*/
  else {
    openlog(ident, logopt, facility);
  }
}

/*
 *  ログをクローズする
 */
void log_close(void)
{
  /* デバッグモードのときは_identを初期化	*/
  if(debug){
    if(_ident != noident){
      free(_ident);
    }
    _ident = noident;
  }

  /* デバッグモードでないときはcloselog	*/
  else {
    closelog();
  }
}

/*
 *  ログをとる
 */
void log_sys(int priority, char *logstring, ...)
{
  va_list	ap;

  /* 引数リストの使用開始	*/
  va_start(ap, logstring);

  /* デバッグモードのときはstderrにメッセージを出力	*/
  if(debug){
    fprintf(stderr, "%s(%d): ", _ident, priority);
    vfprintf(stderr, logstring, ap);
    fprintf(stderr, "\n");
  }

  /* デバッグモードでないときはsyslog	*/
  else {
    vsyslog(priority, logstring, ap);
  }

  /* 引数リストの使用終了	*/
  va_end(ap);
}
