File: log.c

package info (click to toggle)
snmptrapfmt 1.11
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 136 kB
  • ctags: 88
  • sloc: ansic: 1,330; sh: 90; makefile: 27
file content (92 lines) | stat: -rwxr-xr-x 1,816 bytes parent folder | download | duplicates (3)
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
/*
 * log.c
 *
 * Generic log module.
 *
 * Usage: loginit(ProcessName, NameOfLogFile, LogLevel, appendMode);
 *        logging(level, msg, ...);
 *
 */

/* --- 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);
}