]> git.stg.codes - stg.git/blob - stglibs/logger.lib/logger.cpp
Add declaration for operator<< for resetable
[stg.git] / stglibs / logger.lib / logger.cpp
1 #include <stdio.h>
2 #include <stdarg.h>
3 #include <syslog.h>
4
5 #include "stg/logger.h"
6
7 #ifdef STG_TIME
8 extern const volatile time_t stgTime;
9 #endif
10 //-----------------------------------------------------------------------------
11 STG_LOGGER & GetStgLogger()
12 {
13 static STG_LOGGER logger;
14 return logger;
15 }
16 //-----------------------------------------------------------------------------
17 STG_LOGGER::STG_LOGGER()
18     : fileName(),
19       mutex()
20 {
21 pthread_mutex_init(&mutex, NULL);
22 }
23 //-----------------------------------------------------------------------------
24 STG_LOGGER::~STG_LOGGER()
25 {
26 pthread_mutex_destroy(&mutex);
27 }
28 //-----------------------------------------------------------------------------
29 void STG_LOGGER::SetLogFileName(const std::string & fn)
30 {
31 STG_LOGGER_LOCKER lock(&mutex);
32 fileName = fn;
33 }
34 //-----------------------------------------------------------------------------
35 void STG_LOGGER::operator()(const char * fmt, ...)
36 {
37 STG_LOGGER_LOCKER lock(&mutex);
38
39 char buff[2048];
40
41 va_list vl;
42 va_start(vl, fmt);
43 vsnprintf(buff, sizeof(buff), fmt, vl);
44 va_end(vl);
45
46 FILE * f;
47 if (!fileName.empty())
48     {
49     f = fopen(fileName.c_str(), "at");
50     if (f)
51         {
52         #ifdef STG_TIME
53         fprintf(f, "%s", LogDate(stgTime));
54         #else
55         fprintf(f, "%s", LogDate(time(NULL)));
56         #endif
57         fprintf(f, " -- ");
58         fprintf(f, "%s", buff);
59         fprintf(f, "\n");
60         fclose(f);
61         }
62     else
63         {
64         openlog("stg", LOG_NDELAY, LOG_USER);
65         syslog(LOG_CRIT, "%s", buff);
66         closelog();
67         }
68     }
69 else
70     {
71     openlog("stg", LOG_NDELAY, LOG_USER);
72     syslog(LOG_CRIT, "%s", buff);
73     closelog();
74     }
75 }
76 //-----------------------------------------------------------------------------
77 const char * STG_LOGGER::LogDate(time_t t)
78 {
79 static char s[32];
80 if (t == 0)
81     t = time(NULL);
82
83 struct tm * tt = localtime(&t);
84
85 snprintf(s, 32, "%d-%s%d-%s%d %s%d:%s%d:%s%d",
86          tt->tm_year + 1900,
87          tt->tm_mon + 1 < 10 ? "0" : "", tt->tm_mon + 1,
88          tt->tm_mday    < 10 ? "0" : "", tt->tm_mday,
89          tt->tm_hour    < 10 ? "0" : "", tt->tm_hour,
90          tt->tm_min     < 10 ? "0" : "", tt->tm_min,
91          tt->tm_sec     < 10 ? "0" : "", tt->tm_sec);
92
93 return s;
94 }
95 //-----------------------------------------------------------------------------