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