-
Notifications
You must be signed in to change notification settings - Fork 14
/
DlepLogger.cpp
100 lines (89 loc) · 1.88 KB
/
DlepLogger.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
* Dynamic Link Exchange Protocol (DLEP)
*
* Copyright (C) 2013, 2018, 2019 Massachusetts Institute of Technology
*/
#include "DlepLogger.h"
#include <time.h>
#include <ctype.h>
using namespace std;
using namespace LLDLEP::internal;
DlepLogger::DlepLogger(const std::string & filename, unsigned int level)
{
set_log_level(level);
logfile.open(filename);
if (logfile.fail())
{
throw std::invalid_argument("could not open log file " + filename);
}
}
DlepLogger::~DlepLogger()
{
if (logfile.is_open())
{
logfile.close();
}
}
void
DlepLogger::log(unsigned int level, std::ostringstream & msg)
{
boost::mutex::scoped_lock lock(mutex);
level = clamp_log_level(level);
if (level >= log_level)
{
logfile << time_string_get() << level_name[level] << msg.str()
<< endl;
}
}
unsigned int
DlepLogger::clamp_log_level(unsigned int level)
{
if (level < DLEP_LOG_DEBUG)
{
return DLEP_LOG_DEBUG;
}
else if (level > DLEP_LOG_FATAL)
{
return DLEP_LOG_FATAL;
}
else
{
return level;
}
}
void
DlepLogger::set_log_level(unsigned int level)
{
boost::mutex::scoped_lock lock(mutex);
log_level = clamp_log_level(level);
}
void
DlepLogger::set_log_file(const std::string & filename)
{
boost::mutex::scoped_lock lock(mutex);
if (logfile.is_open())
{
logfile.close();
}
logfile.open(filename);
if (logfile.fail())
{
throw std::invalid_argument(filename);
}
}
string
DlepLogger::time_string_get()
{
char buf[128];
timeval tp;
gettimeofday(&tp, nullptr);
time_t tim = time(nullptr);
tm now;
localtime_r(&tim, &now);
snprintf(buf, sizeof(buf), "%02d:%02d:%02d.%03ld ",
now.tm_hour,
now.tm_min,
now.tm_sec,
tp.tv_usec / 1000L);
return string(buf);
}