f2e01aceb543f458a43afe5dbaa6b8dad262542c
[platform/upstream/iotivity.git] / resource / oc_logger / include / oc_log_stream.hpp
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 #ifndef OC_LOG_STREAM_HPP_
22 #define OC_LOG_STREAM_HPP_
23
24 #include <iosfwd>
25 #include <memory>
26 #include <cassert>
27 #include <iostream>
28
29 #include <boost/config.hpp>
30 #include <boost/iostreams/stream.hpp>
31 #include <boost/iostreams/categories.hpp>
32 #include <boost/iostreams/detail/ios.hpp>
33
34 #include "oc_logger.h"
35
36 namespace OC {
37
38 class oc_log_stream : boost::iostreams::sink
39 {
40  std::shared_ptr<oc_log_ctx_t> m_log;
41
42  public:
43  typedef char                            char_type;
44  typedef boost::iostreams::sink_tag      category;
45
46  public:
47  template <class ContextCtor>
48  oc_log_stream(ContextCtor& c)
49   : m_log { c(), oc_log_destroy }
50  {}
51
52  template <class ContextCtor>
53  oc_log_stream(ContextCtor& c, void *world)
54   : m_log { c(world), oc_log_destroy }
55  {}
56
57  public:
58  inline void flush()                                    noexcept { return oc_log_flush(m_log.get()); }
59  inline void set_level(const oc_log_level new_level)    noexcept { return oc_log_set_level(m_log.get(), new_level); }
60  inline int  set_module(const std::string& module_name) noexcept { return oc_log_set_module(m_log.get(), module_name.c_str()); }
61
62  public:
63  std::streamsize write(const char_type *s, std::streamsize n)
64  {
65     /* It may seem strange to do this here, but it's a consequence of the
66     underlying library not supporting ptr+len style buffers at this time: */
67     std::string s2(s, n + s);
68
69     oc_log_write(m_log.get(), s2.c_str());
70
71     return n;
72  }
73
74  private:
75  oc_log_stream operator=(const oc_log_stream&)  = delete;
76 };
77
78 } // namespace OC
79
80 #endif