Merge master branch.
[dcpomatic.git] / src / lib / log.cc
1 /*
2     Copyright (C) 2012 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 /** @file src/log.cc
21  *  @brief A very simple logging class.
22  */
23
24 #include <fstream>
25 #include <time.h>
26 #include "log.h"
27
28 using namespace std;
29
30 Log::Log ()
31         : _level (STANDARD)
32 {
33
34 }
35
36 /** @param n String to log */
37 void
38 Log::log (string m, Level l)
39 {
40         boost::mutex::scoped_lock lm (_mutex);
41
42         if (l > _level) {
43                 return;
44         }
45
46         time_t t;
47         time (&t);
48         string a = ctime (&t);
49
50         stringstream s;
51         s << a.substr (0, a.length() - 1) << ": " << m;
52         do_log (s.str ());
53 }
54
55 void
56 Log::microsecond_log (string m, Level l)
57 {
58         boost::mutex::scoped_lock lm (_mutex);
59
60         if (l > _level) {
61                 return;
62         }
63
64         struct timeval tv;
65         gettimeofday (&tv, 0);
66
67         stringstream s;
68         s << tv.tv_sec << ":" << tv.tv_usec << " " << m;
69         do_log (s.str ());
70 }       
71
72 void
73 Log::set_level (Level l)
74 {
75         boost::mutex::scoped_lock lm (_mutex);
76         _level = l;
77 }
78
79 void
80 Log::set_level (string l)
81 {
82         if (l == "verbose") {
83                 set_level (VERBOSE);
84                 return;
85         } else if (l == "timing") {
86                 set_level (TIMING);
87                 return;
88         }
89
90         set_level (STANDARD);
91 }
92
93 /** @param file Filename to write log to */
94 FileLog::FileLog (string file)
95         : _file (file)
96 {
97
98 }
99
100 void
101 FileLog::do_log (string m)
102 {
103         ofstream f (_file.c_str(), fstream::app);
104         f << m << "\n";
105 }
106