-
Notifications
You must be signed in to change notification settings - Fork 2
/
prefine.cpp
executable file
·75 lines (69 loc) · 2.21 KB
/
prefine.cpp
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
/*
* prefine.cpp
*
* Created on: 2012-3-8
* Author: wyt
*/
#include "prefine.h"
static const char *levelname[] = {"BUG","INFO","WARN", "ERROR", "FATAL"};
FILE *GentLog::logfd = stdout;
string GentLog::logfile = "";
int GentLog::runLevel = GentLog::INFO;
bool GentLog::isServer = true;
void GentLog::setServer(bool s)
{
GentLog::isServer = s;
}
int GentLog::setfd(string &filename)
{
if(filename == "") return 1;
GentLog::logfile = filename;
if((logfd = fopen(filename.c_str(), "a+")) == NULL) {
return 0;
}
return 1;
}
void GentLog::setLevel(string &loglevel)
{
if(loglevel == "bug" || loglevel == "BUG"){
GentLog::runLevel = GentLog::BUG;
}else if(loglevel == "info" || loglevel == "INFO"){
GentLog::runLevel = GentLog::INFO;
}else if(loglevel == "warn" || loglevel == "WARN"){
GentLog::runLevel = GentLog::WARN;
}else if(loglevel == "error" || loglevel == "ERROR"){
GentLog::runLevel = GentLog::ERROR;
}else if(loglevel == "fatal" || loglevel == "FATAL"){
GentLog::runLevel = GentLog::FATAL;
}
}
void GentLog::write(int levels, const char *file, const int line, const char *func, const char *format, ...)
{
if(!GentLog::isServer) return;
if(levels < GentLog::runLevel) return;
char buf[LOGBUFSIZE];
va_list ap;
va_start(ap, format);
vsnprintf(buf, LOGBUFSIZE, format, ap);
va_end(ap);
time_t now;
struct tm *tm;
time(&now);
tm = localtime(&now);
char str[LINEBUFSIZE];
#ifdef _DARWIN
snprintf(str, LINEBUFSIZE, "%s [%d-%02d-%02d %02d:%02d:%02d] [%lu] %s", levelname[levels], tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec, pthread_self()->__sig, buf);
#else
snprintf(str, LINEBUFSIZE, "%s [%d-%02d-%02d %02d:%02d:%02d] [%lu] %s", levelname[levels], tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec, pthread_self(), buf);
#endif
if(GentLog::logfile != "" && access(GentLog::logfile.c_str(),0) == -1) {
fclose(logfd);
GentLog::setfd(GentLog::logfile);
}
fprintf(logfd, "%s\n", str);
fflush(logfd);
}
void GentLog::console(int level, const string &str)
{
cout << levelname[level] << " "<<str<<endl;
}