]> git.sesse.net Git - casparcg/blob - common/log.cpp
Fixed problem in core project file where some header files were not included.
[casparcg] / common / log.cpp
1 /*
2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>
3 *
4 * This file is part of CasparCG (www.casparcg.com).
5 *
6 * CasparCG is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * CasparCG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.
18 *
19 * Author: Robert Nagy, ronag89@gmail.com
20 */
21
22 #include "stdafx.h"
23
24 #include "log.h"
25
26 #include "except.h"
27 #include "utf.h"
28
29 #include <ios>
30 #include <iomanip>
31 #include <string>
32 #include <ostream>
33
34 #include <boost/shared_ptr.hpp>
35 #include <boost/make_shared.hpp>
36 #include <boost/filesystem/convenience.hpp>
37 #include <boost/date_time/posix_time/posix_time.hpp>
38 #include <boost/algorithm/string.hpp>
39
40 #include <boost/log/core.hpp>
41 #include <boost/log/trivial.hpp>
42 #include <boost/log/expressions.hpp>
43
44 #include <boost/log/sinks/text_file_backend.hpp>
45 #include <boost/log/sinks/text_ostream_backend.hpp>
46 #include <boost/log/sinks/sync_frontend.hpp>
47 #include <boost/log/sinks/async_frontend.hpp>
48 #include <boost/log/core/record.hpp>
49 #include <boost/log/attributes/attribute_value.hpp>
50 #include <boost/log/attributes/current_thread_id.hpp>
51 #include <boost/log/utility/setup/common_attributes.hpp>
52
53 #include <boost/core/null_deleter.hpp>
54 #include <boost/lambda/lambda.hpp>
55 #include <boost/bind.hpp>
56 #include <boost/lexical_cast.hpp>
57 #include <boost/property_tree/ptree.hpp>
58 #include <boost/thread/mutex.hpp>
59
60 #include <tbb/atomic.h>
61
62 namespace caspar { namespace log {
63
64 using namespace boost;
65
66 template<typename Stream>
67 void append_timestamp(Stream& stream)
68 {
69         auto timestamp = boost::posix_time::microsec_clock::local_time();
70         auto date = timestamp.date();
71         auto time = timestamp.time_of_day();
72         auto milliseconds = time.fractional_seconds() / 1000; // microseconds to milliseconds
73
74         std::wstringstream buffer;
75
76         buffer
77                 << std::setfill(L'0')
78                 << L"["
79                 << std::setw(4) << date.year() << L"-" << std::setw(2) << date.month().as_number() << "-" << std::setw(2) << date.day().as_number()
80                 << L" "
81                 << std::setw(2) << time.hours() << L":" << std::setw(2) << time.minutes() << L":" << std::setw(2) << time.seconds()
82                 << L"."
83                 << std::setw(3) << milliseconds
84                 << L"] ";
85
86         stream << buffer.str();
87 }
88
89 class column_writer
90 {
91         tbb::atomic<int> column_width_;
92 public:
93         column_writer(int initial_width = 0)
94         {
95                 column_width_ = initial_width;
96         }
97
98         template<typename Stream, typename Val>
99         void write(Stream& out, const Val& value)
100         {
101                 std::wstring to_string = boost::lexical_cast<std::wstring>(value);
102                 int length = static_cast<int>(to_string.size());
103                 int read_width;
104
105                 while ((read_width = column_width_) < length && column_width_.compare_and_swap(length, read_width) != read_width);
106                 read_width = column_width_;
107
108                 out << L"[" << to_string << L"] ";
109
110                 for (int n = 0; n < read_width - length; ++n)
111                         out << L" ";
112         }
113 };
114
115 template<typename Stream>
116 void my_formatter(bool print_all_characters, const boost::log::record_view& rec, Stream& strm)
117 {
118         static column_writer thread_id_column;
119         static column_writer severity_column(7);
120         namespace expr = boost::log::expressions;
121
122         std::wstringstream pre_message_stream;
123         append_timestamp(pre_message_stream);
124         thread_id_column.write(pre_message_stream, boost::log::extract<boost::log::attributes::current_thread_id::value_type>("ThreadID", rec).get().native_id());
125         severity_column.write(pre_message_stream, boost::log::extract<boost::log::trivial::severity_level>("Severity", rec));
126
127         auto pre_message = pre_message_stream.str();
128
129         strm << pre_message;
130
131         auto line_break_replacement = L"\n" + pre_message;
132
133         if (print_all_characters)
134         {
135                 strm << boost::replace_all_copy(rec[expr::message].get<std::wstring>(), "\n", line_break_replacement);
136         }
137         else
138         {
139                 strm << boost::replace_all_copy(replace_nonprintable_copy(rec[expr::message].get<std::wstring>(), L'?'), L"\n", line_break_replacement);
140         }
141 }
142
143 namespace internal{
144         
145 void init()
146 {       
147         boost::log::add_common_attributes();
148         typedef boost::log::sinks::asynchronous_sink<boost::log::sinks::wtext_ostream_backend> stream_sink_type;
149
150         auto stream_backend = boost::make_shared<boost::log::sinks::wtext_ostream_backend>();
151         stream_backend->add_stream(boost::shared_ptr<std::wostream>(&std::wcout, boost::null_deleter()));
152         stream_backend->auto_flush(true);
153
154         auto stream_sink = boost::make_shared<stream_sink_type>(stream_backend);
155         // Never log calltrace to console. The terminal is too slow, so the log queue will build up faster than consumed.
156         stream_sink->set_filter(category != log_category::calltrace);
157
158         bool print_all_characters = false;
159         stream_sink->set_formatter(boost::bind(&my_formatter<boost::log::wformatting_ostream>, print_all_characters, _1, _2));
160
161         boost::log::core::get()->add_sink(stream_sink);
162 }
163
164 }
165
166 void add_file_sink(const std::wstring& file, const boost::log::filter& filter)
167 {
168         typedef boost::log::sinks::synchronous_sink<boost::log::sinks::text_file_backend> file_sink_type;
169
170         try
171         {
172                 if (!boost::filesystem::is_directory(boost::filesystem::path(file).parent_path()))
173                         CASPAR_THROW_EXCEPTION(directory_not_found());
174
175                 auto file_sink = boost::make_shared<file_sink_type>(
176                         boost::log::keywords::file_name = (file + L"_%Y-%m-%d.log"),
177                         boost::log::keywords::time_based_rotation = boost::log::sinks::file::rotation_at_time_point(0, 0, 0),
178                         boost::log::keywords::auto_flush = true,
179                         boost::log::keywords::open_mode = std::ios::app
180                         );
181
182                 bool print_all_characters = true;
183
184                 file_sink->set_formatter(boost::bind(&my_formatter<boost::log::formatting_ostream>, print_all_characters, _1, _2));
185                 file_sink->set_filter(filter);
186                 boost::log::core::get()->add_sink(file_sink);
187         }
188         catch (...)
189         {
190                 std::wcerr << L"Failed to Setup File Logging Sink" << std::endl << std::endl;
191         }
192 }
193
194 std::shared_ptr<void> add_preformatted_line_sink(std::function<void(std::string line)> formatted_line_sink)
195 {
196         class sink_backend : public boost::log::sinks::basic_formatted_sink_backend<char>
197         {
198                 std::function<void(std::string line)> formatted_line_sink_;
199         public:
200                 sink_backend(std::function<void(std::string line)> formatted_line_sink)
201                         : formatted_line_sink_(std::move(formatted_line_sink))
202                 {
203                 }
204
205                 void consume(const boost::log::record_view& rec, const std::string& formatted_message)
206                 {
207                         try
208                         {
209                                 formatted_line_sink_(formatted_message);
210                         }
211                         catch (...)
212                         {
213                                 std::cerr << "[sink_backend] Error while consuming formatted message: " << formatted_message << std::endl << std::endl;
214                         }
215                 }
216         };
217
218         typedef boost::log::sinks::synchronous_sink<sink_backend> sink_type;
219
220         auto sink = boost::make_shared<sink_type>(std::move(formatted_line_sink));
221         bool print_all_characters = true;
222
223         sink->set_formatter(boost::bind(&my_formatter<boost::log::formatting_ostream>, print_all_characters, _1, _2));
224         sink->set_filter(category != log_category::calltrace);
225
226         boost::log::core::get()->add_sink(sink);
227
228         return std::shared_ptr<void>(nullptr, [=](void*)
229         {
230                 boost::log::core::get()->remove_sink(sink);
231         });
232 }
233
234 boost::mutex& get_filter_mutex()
235 {
236         static boost::mutex instance;
237
238         return instance;
239 }
240
241 boost::log::trivial::severity_level& get_level()
242 {
243         static boost::log::trivial::severity_level instance;
244
245         return instance;
246 }
247
248 log_category& get_disabled_categories()
249 {
250         static log_category instance = log_category::calltrace;
251
252         return instance;
253 }
254
255 void set_log_filter()
256 {
257         auto severity_filter            = boost::log::trivial::severity >= get_level();
258         auto disabled_categories        = get_disabled_categories();
259
260         boost::log::core::get()->set_filter([=](const boost::log::attribute_value_set& attributes)
261         {
262                 return severity_filter(attributes)
263                         && static_cast<int>(disabled_categories & attributes["Channel"].extract<log_category>().get()) == 0;
264         });
265 }
266
267 void set_log_level(const std::wstring& lvl)
268 {
269         boost::lock_guard<boost::mutex> lock(get_filter_mutex());
270
271         if (boost::iequals(lvl, L"trace"))
272                 get_level() = boost::log::trivial::trace;
273         else if (boost::iequals(lvl, L"debug"))
274                 get_level() = boost::log::trivial::debug;
275         else if (boost::iequals(lvl, L"info"))
276                 get_level() = boost::log::trivial::info;
277         else if (boost::iequals(lvl, L"warning"))
278                 get_level() = boost::log::trivial::warning;
279         else if (boost::iequals(lvl, L"error"))
280                 get_level() = boost::log::trivial::error;
281         else if (boost::iequals(lvl, L"fatal"))
282                 get_level() = boost::log::trivial::fatal;
283
284         set_log_filter();
285 }
286
287 void set_log_category(const std::wstring& cat, bool enabled)
288 {
289         log_category category_to_set;
290
291         if (boost::iequals(cat, L"calltrace"))
292                 category_to_set = log_category::calltrace;
293         else if (boost::iequals(cat, L"communication"))
294                 category_to_set = log_category::communication;
295         else
296                 return; // Ignore
297
298         boost::lock_guard<boost::mutex> lock(get_filter_mutex());
299         auto& disabled_categories = get_disabled_categories();
300
301         if (enabled)
302                 disabled_categories &= ~category_to_set;
303         else
304                 disabled_categories |= category_to_set;
305
306         set_log_filter();
307 }
308
309 void print_child(
310                 boost::log::trivial::severity_level level,
311                 const std::wstring& indent,
312                 const std::wstring& elem,
313                 const boost::property_tree::wptree& tree)
314 {
315         auto& data = tree.data();
316
317         if (!data.empty())
318                 BOOST_LOG_STREAM_WITH_PARAMS(log::logger::get(), (boost::log::keywords::severity = level)) << indent << elem << L" " << replace_nonprintable_copy(data, L'?');
319         else if (tree.size() == 0)
320                 BOOST_LOG_STREAM_WITH_PARAMS(log::logger::get(), (boost::log::keywords::severity = level)) << indent << elem;
321
322         for (auto& child : tree)
323                 print_child(level, indent + (elem.empty() ? L"" : elem + L"."), child.first, child.second);
324 }
325
326 }}