1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21 #include "oc_logger.hpp"
22 #include "targets/oc_ostream_logger.h"
34 struct oc_ostream_logger_ctx
41 oc_ostream_logger_ctx(std::ostream *here)
49 /* Courtesy-function: */
50 oc_log_ctx_t *oc_make_ostream_logger()
52 return oc_log_make_ctx(
56 oc_ostream_log_destroy,
58 oc_ostream_log_set_level,
60 oc_ostream_log_set_module
64 int oc_ostream_log_init(oc_log_ctx_t *ctx, void *world)
67 auto *target = reinterpret_cast<std::ostream *>(world);
72 oc_ostream_logger_ctx *my_ctx = new oc_ostream_logger_ctx(target);
74 ctx->ctx = static_cast<void *>(my_ctx);
83 void oc_ostream_log_destroy(oc_log_ctx_t *ctx)
86 static std::mutex dtor_mtx;
88 oc_ostream_logger_ctx *lctx = static_cast<oc_ostream_logger_ctx *>(ctx->ctx);
91 std::unique_lock<std::mutex> ul(dtor_mtx);
93 lctx->os << std::flush;
102 void oc_ostream_log_flush(oc_log_ctx_t *ctx)
105 oc_ostream_logger_ctx *lctx = static_cast<oc_ostream_logger_ctx *>(ctx->ctx);
107 std::lock_guard<std::mutex> lg(lctx->mutex);
109 lctx->os << std::flush;
115 void oc_ostream_log_set_level(oc_log_ctx_t *ctx, const int level)
118 /* We don't have any special thing we need to do when a log level changes. */
125 size_t oc_ostream_log_write(oc_log_ctx_t *ctx, const int level, const char *msg)
128 oc_ostream_logger_ctx *lctx = static_cast<oc_ostream_logger_ctx *>(ctx->ctx);
130 std::lock_guard<std::mutex> lg(lctx->mutex);
132 std::ostringstream os;
136 if(nullptr != ctx->module_name)
137 os << '[' << ctx->module_name << "] ";
141 lctx->os << os.str().c_str();
143 return 1 + os.str().length();
150 int oc_ostream_log_set_module(oc_log_ctx_t *ctx, const char *module_name)
153 // Nothing special needs to happen for a module name change:
161 int oc_ostream_log_lock(oc_log_ctx_t *ctx)
164 oc_ostream_logger_ctx *lctx = static_cast<oc_ostream_logger_ctx *>(ctx->ctx);
175 int oc_ostream_log_unlock(oc_log_ctx_t *ctx)
178 oc_ostream_logger_ctx *lctx = static_cast<oc_ostream_logger_ctx *>(ctx->ctx);
180 lctx->mutex.unlock();
189 int oc_ostream_log_try_lock(oc_log_ctx_t *ctx)
192 oc_ostream_logger_ctx *lctx = static_cast<oc_ostream_logger_ctx *>(ctx->ctx);
194 return lctx->mutex.try_lock();