Imported Upstream version 1.7.0
[platform/core/ml/nnfw.git] / compiler / tflchef / log / src / Log.cpp
1 /*
2  * Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *    http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "Log.h"
18
19 #include <cassert>
20 #include <cstdlib>
21 #include <iostream>
22
23 // TODO Extract these lexical conversion routines as a library
24 namespace
25 {
26
27 /**
28  * @brief Convert C-string as a value of type T
29  *
30  * safecast(s, v) returns v if s is nullptr.
31  */
32 template <typename T> T safecast(const char *, const T &);
33
34 template <> bool safecast<bool>(const char *s, const bool &value)
35 {
36   return (s == nullptr) ? value : (std::stoi(s) != 0);
37 }
38
39 } // namespace
40
41 //
42 // Logger
43 //
44 namespace tflchef
45 {
46
47 Logger::Logger(hermes::Context *ctx) { activate(ctx->sources(), ctx->bus()); }
48 Logger::~Logger() { deactivate(); }
49
50 } // namespace tflchef
51
52 //
53 // LoggerConfig
54 //
55 namespace tflchef
56 {
57
58 LoggerConfig::LoggerConfig()
59 {
60   // Turn on logging if TFLCHEF_LOG is set as non-zero value
61   _enabled = safecast<bool>(std::getenv("TFLCHEF_LOG"), false);
62 }
63
64 void LoggerConfig::configure(const hermes::Source *source, hermes::Source::Setting &setting) const
65 {
66   // Let's ignore hermes::Sources if that is not a moco logger
67   if (auto logger = dynamic_cast<const Logger *>(source))
68   {
69     configure(logger, setting);
70   }
71 }
72
73 void LoggerConfig::configure(const Logger *, hermes::Source::Setting &setting) const
74 {
75   if (_enabled)
76   {
77     // Enable all catagories
78     setting.accept_all();
79   }
80   else
81   {
82     // Disable all catagories
83     setting.reject_all();
84   }
85 }
86
87 } // namespace tflchef