Change log format 74/261274/4
authorJunghyun Yeon <jungh.yeon@samsung.com>
Wed, 14 Jul 2021 09:03:32 +0000 (18:03 +0900)
committerJunghyun Yeon <jungh.yeon@samsung.com>
Fri, 16 Jul 2021 00:48:10 +0000 (09:48 +0900)
Change-Id: Ib2039794e719cf1e4a06e38b7509d05be7186e0a
Signed-off-by: Junghyun Yeon <jungh.yeon@samsung.com>
36 files changed:
src/CMakeLists.txt
src/client/pkginfo_client.cc
src/common/ready_checker.cc
src/common/socket/abstract_socket.cc
src/common/socket/client_socket.cc
src/common/socket/server_socket.cc
src/logging.cc [deleted file]
src/logging.hh [deleted file]
src/manager/pkginfo_manager.cc
src/server/CMakeLists.txt
src/server/cynara_checker/cynara_checker.cc
src/server/database/abstract_db_handler.cc
src/server/database/appinfo_db_handler.cc
src/server/database/cert_get_db_handler.cc
src/server/database/create_db_handler.cc
src/server/database/db_handle_provider.cc
src/server/database/depinfo_db_handler.cc
src/server/database/pkg_get_db_handler.cc
src/server/database/pkg_set_db_handler.cc
src/server/database/query_handler.cc
src/server/pkg_request.cc
src/server/request_handler/command_request_handler.cc
src/server/request_handler/create_db_request_handler.cc
src/server/request_handler/get_appinfo_request_handler.cc
src/server/request_handler/get_cert_request_handler.cc
src/server/request_handler/get_depinfo_request_handler.cc
src/server/request_handler/get_pkginfo_request_handler.cc
src/server/request_handler/query_request_handler.cc
src/server/request_handler/request_handler_direct_access.cc
src/server/request_handler/set_cert_request_handler.cc
src/server/request_handler/set_pkginfo_request_handler.cc
src/server/runner.cc
src/server/worker_thread.cc
src/utils/logging.cc [new file with mode: 0644]
src/utils/logging.hh [new file with mode: 0644]
test/unit_tests/CMakeLists.txt

index 9f7dc0adace942025ea7d1e1f8f2408ce0edf383..2336b52616857dd408f6c6ee8cca0cef7affc99c 100644 (file)
@@ -5,6 +5,7 @@ AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR}/common COMMON_SRCS)
 AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR}/manager MANAGER_SRCS)
 AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR}/common/socket SOCKET_SRCS)
 AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR}/common/parcel PARCEL_SRCS)
+AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR}/utils UTIL_SRCS)
 
 ADD_LIBRARY(pkgmgr-info SHARED
   ${SRCS}
@@ -13,6 +14,7 @@ ADD_LIBRARY(pkgmgr-info SHARED
   ${SOCKET_SRCS}
   ${PARCEL_SRCS}
   ${MANAGER_SRCS}
+  ${UTIL_SRCS}
 )
 
 ## Compile flags
index 2322a5060e90b2cf24be3f1e4e48e44efbf6b654..adb200d32918820d16bfc9affa970dbc4db4954a 100644 (file)
@@ -14,6 +14,8 @@
 #include "parcelable_factory.hh"
 #include "system_locale.hh"
 #include "ready_checker.hh"
+#include "utils/logging.hh"
+
 #include "pkgmgrinfo_debug.h"
 #include "pkgmgrinfo_private.h"
 
@@ -39,7 +41,7 @@ PkgInfoClient::PkgInfoClient(
 bool PkgInfoClient::SendRequest() {
   static pkgmgr_common::ReadyChecker check_server(SERVER_READY);
   if (socket_ == nullptr) {
-    LOGE("Socket is not ready");
+    LOG(ERROR) << "Socket is not ready";
     return false;
   }
 
@@ -50,18 +52,18 @@ bool PkgInfoClient::SendRequest() {
   }
 
   if (!check_server.IsReady()) {
-    LOGW("Server is not ready, try to direct access");
+    LOG(WARNING) << "Server is not ready, try to direct access";
     is_offline_ = true;
     return RequestHandlerDirectAccess();
   }
   if (!socket_->Connect()) {
-    LOGE("Failed to connect client socket, try to direct access");
+    LOG(ERROR) << "Failed to connect client socket, try to direct access";
     is_offline_ = true;
     return RequestHandlerDirectAccess();
   }
 
   if (socket_->SendData(&req_type_, sizeof(req_type_)) != 0) {
-    LOGE("fail to send data");
+    LOG(ERROR) << "fail to send data";
     return false;
   }
 
@@ -71,12 +73,12 @@ bool PkgInfoClient::SendRequest() {
   int len = raw.size();
 
   if (socket_->SendData(&len, sizeof(len)) != 0) {
-    LOGE("fail to send data");
+    LOG(ERROR) << "fail to send data";
     return false;
   }
 
   if (socket_->SendData(&raw[0], len) != 0) {
-    LOGE("Fail to send data");
+    LOG(ERROR) << "Fail to send data";
     return false;
   }
 
@@ -89,23 +91,23 @@ PkgInfoClient::GetResultParcel() {
     return result_parcel_;
 
   if (socket_ == nullptr) {
-    LOGE("Socket is not ready");
+    LOG(ERROR) << "Socket is not ready";
     return nullptr;
   }
   int len = 0;
   if (socket_->ReceiveData(&len, sizeof(len)) != 0 || len <= 0) {
-    LOGE("Fail to receive data");
+    LOG(ERROR) << "Fail to receive data";
     return nullptr;
   }
 
   unsigned char* raw = new (std::nothrow) unsigned char[len];
   if (raw == nullptr) {
-    LOGE("Out of memory");
+    LOG(ERROR) << "Out of memory";
     return nullptr;
   }
 
   if (socket_->ReceiveData(raw, len) != 0) {
-    LOGE("Fail to receive data");
+    LOG(ERROR) << "Fail to receive data";
     delete[] raw;
     return nullptr;
   }
@@ -128,13 +130,15 @@ bool PkgInfoClient::RequestHandlerDirectAccess() {
   if (handle == nullptr) {
     handle = dlopen(LIBPKGMGR_INFO, RTLD_LOCAL | RTLD_LAZY);
     if (!handle) {
-      LOGE("Failed to open library: %s (%s)", LIBPKGMGR_INFO, dlerror());
+      LOG(ERROR) << "Failed to open library: " << LIBPKGMGR_INFO
+          << ", : " << dlerror();
       return false;
     }
     dl_func = reinterpret_cast<void* (*)(int, unsigned char*, int, const char *)>(
         dlsym(handle, DIRECT_ACCESS_FUNC));
     if (dl_func == nullptr) {
-      LOGE("cannot find %s symbol in (%s)", DIRECT_ACCESS_FUNC, LIBPKGMGR_INFO);
+      LOG(ERROR) << "cannot find " << DIRECT_ACCESS_FUNC << " symbol in "
+          << LIBPKGMGR_INFO;
       dlclose(handle);
       handle = nullptr;
       return false;
index 61d9f67a501eda075b516ea035403e150ebffcd8..b7da7a58b40c498228c3e8f10947872815de9819 100644 (file)
@@ -18,6 +18,8 @@
 
 #include <utility>
 
+#include "utils/logging.hh"
+
 #include "pkgmgrinfo_debug.h"
 
 #undef LOG_TAG
@@ -48,7 +50,7 @@ gboolean ReadyChecker::OnReceiveEvent(GIOChannel* channel, GIOCondition cond,
           ready_checker->ready_file_ != event->name)
         continue;
 
-      _LOGI("server is ready (%s)", ready_checker->ready_file_.c_str());
+      LOG(INFO) << "server is ready : " <<  ready_checker->ready_file_;
       ready_checker->ready_ = true;
       ready_checker->Dispose();
       return G_SOURCE_CONTINUE;
@@ -67,14 +69,14 @@ ReadyChecker::ReadyChecker(const std::string& ready_path) {
 
   auto it = ready_path.find_last_of("/");
   if (it == ready_path.npos) {
-    _LOGE("Invalid path %s", ready_path.c_str());
+    LOG(ERROR) << "Invalid path: " << ready_path;
     disposed_ = true;
     return;
   }
 
   fd_ = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
   if (fd_ == -1) {
-    _LOGE("Failed to inotify_init. errno(%d)", errno);
+    LOG(ERROR) << "Failed to inotify_init. errno: " << errno;
     disposed_ = true;
     return;
   }
@@ -83,21 +85,21 @@ ReadyChecker::ReadyChecker(const std::string& ready_path) {
   ready_file_ = ready_path.substr(it + 1);
   wd_ = inotify_add_watch(fd_, ready_path_.c_str(), IN_CREATE);
   if (wd_ == -1) {
-    _LOGE("Failed to inotify_add_watch. errno(%d)", errno);
+    LOG(ERROR) << "Failed to inotify_add_watch. errno: " << errno;
     Dispose();
     return;
   }
 
   channel_ = g_io_channel_unix_new(fd_);
   if (channel_ == nullptr) {
-    _LOGE("Failed to create GIO channel");
+    LOG(ERROR) << "Failed to create GIO channel";
     Dispose();
     return;
   }
 
   tag_ = g_io_add_watch(channel_, G_IO_IN, OnReceiveEvent, this);
   if (tag_ == 0) {
-    _LOGE("Failed to add watch");
+    LOG(ERROR) << "Failed to add watch";
     Dispose();
     return;
   }
index 244adc92dc57c43f83787863182fca2b2b92f978..9ceca3800ad1fc2d7d37cd36fe03c5331e6c90f0 100644 (file)
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include "abstract_socket.hh"
+
 #include <errno.h>
 #include <fcntl.h>
 #include <limits.h>
@@ -21,8 +23,9 @@
 #include <sys/types.h>
 #include <unistd.h>
 
+#include "utils/logging.hh"
+
 #include "pkgmgrinfo_debug.h"
-#include "abstract_socket.hh"
 
 namespace pkgmgr_common {
 namespace socket {
@@ -45,7 +48,7 @@ int AbstractSocket::SendData(const void* buf, unsigned int size) {
   while (left) {
     ssize_t send_byte = send(fd_, buffer, left, MSG_NOSIGNAL);
     if (send_byte < 0) {
-      LOGE("send() is failed. fd(%d), errno(%d)", fd_, errno);
+      LOG(ERROR) << "send() is failed. fd: " << fd_ << ", errno:" << errno;
       return -ECOMM;
     }
 
@@ -67,21 +70,22 @@ int AbstractSocket::ReceiveData(void* buf, unsigned int size) {
   while (left) {
     ssize_t recv_byte = recv(fd_, buffer, left, 0);
     if (recv_byte == 0) {
-      LOGW("Socket was disconnected. fd(%d), errno(%d)", fd_, errno);
+      LOG(WARNING) << "Socket was disconnected. fd: " << fd_
+          << ", errno: " << errno;
       return -errno;
     } else if (recv_byte < 0) {
       if (errno == EINTR) {
         continue;
       } else if (errno == EAGAIN) {
         if (is_blocking) {
-          LOGE("Timed out. fd(%d), errno(%d)", fd_, errno);
+          LOG(ERROR) << "Timed out. fd: " << fd_ << ", errno: " << errno;
           return -errno;
         }
 
         continue;
       }
 
-      LOGE("recv() is failed. fd(%d), errno(%d)", fd_, errno);
+      LOG(ERROR) << "recv() is failed. fd: " << fd_ << ", errno: " << errno;
       return -ECOMM;
     }
 
@@ -113,12 +117,15 @@ void AbstractSocket::SetOption() {
   int ret = setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size));
 
   if (ret < 0) {
-    LOGE("setsockopt() is failed. fd(%d), errno(%d)", fd_, errno);
+    LOG(ERROR) << "setsockopt() is failed. fd: " << fd_
+        << ", errno: " << errno;
     return;
   }
 
   ret = setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
-  if (ret < 0) LOGE("setsockopt() is failed. fd(%d), errno(%d)", fd_, errno);
+  if (ret < 0)
+    LOG(ERROR) << "setsockopt() is failed. fd: " << fd_
+        << ", errno: " << errno;
 }
 
 int AbstractSocket::Create() {
@@ -127,7 +134,7 @@ int AbstractSocket::Create() {
 
   fd_ = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
   if (fd_ < 0) {
-    LOGE("socket() is failed. errno(%d)", errno);
+    LOG(ERROR) << "socket() is failed. errno: " << errno;
     return fd_;
   }
 
@@ -145,7 +152,7 @@ void AbstractSocket::GetFdInfo() {
 
   r = getsockopt(fd_, SOL_SOCKET, SO_PEERCRED, &cred, &len);
   if (r < 0) {
-    LOGE("getsockopt has failed, errno[%d]", errno);
+    LOG(ERROR) << "getsockopt has failed, errno: " << errno;
     return;
   }
 
index 231173fb559bd4fd4534fa7905441d525d0b14af..5c1f21801826ead23855896305859c8f632dd681 100644 (file)
@@ -22,6 +22,8 @@
 #include <unistd.h>
 
 #include "client_socket.hh"
+#include "utils/logging.hh"
+
 #include "pkgmgrinfo_debug.h"
 
 namespace pkgmgr_common {
@@ -35,7 +37,7 @@ void ClientSocket::SetTimeout(int timeout_msec) {
     timeout_msec = 5000;
 
   if (timeout_msec < 0) {
-    LOGE("Invalid timeout_msec parameter");
+    LOG(ERROR) << "Invalid timeout_msec parameter";
     return;
   }
 
@@ -46,7 +48,8 @@ void ClientSocket::SetTimeout(int timeout_msec) {
   int ret = setsockopt(fd_, SOL_SOCKET, SO_RCVTIMEO, &timeout,
       sizeof(timeout));
   if (ret < 0)
-    LOGE("setsockopt() is failed. fd(%d), errno(%d)", fd_, errno);
+    LOG(ERROR) << "setsockopt() is failed. fd: " << fd_
+        << ", errno: " << errno;
 }
 
 bool ClientSocket::Connect() {
@@ -62,8 +65,8 @@ bool ClientSocket::Connect() {
     if (ret == 0) {
       break;
     } else if (ret < -1) {
-      LOGE("Maybe peer not launched or peer dead. path(%s), fd(%d)",
-           GetPath().c_str(), GetFd());
+      LOG(ERROR) << "Maybe peer not launched or peer dead. path: " << GetPath()
+          << ", fd: " << GetFd();
       if (getuid() == 0) {
         // If requester is root, don't wait
         return false;
@@ -71,8 +74,8 @@ bool ClientSocket::Connect() {
       usleep(100 * 1000);
       --retry_cnt;
     } else if (ret < 0) {
-      LOGE("Failed to connect to socket(%s), fd(%d)", GetPath().c_str(),
-           GetFd());
+      LOG(ERROR) << "Failed to connect to socket: " << GetPath()
+          << ", fd: " << GetFd();
       return false;
     }
   } while (retry_cnt > 0);
@@ -84,16 +87,16 @@ int ClientSocket::TryConnection() {
   int flags = fcntl(fd_, F_GETFL, 0);
 
   if (fcntl(fd_, F_SETFL, flags | O_NONBLOCK) != 0) {
-    LOGE("Failed to set flags(%d) on fd(%d), errno(%d)",
-        flags | O_NONBLOCK, fd_, errno);
+    LOG(ERROR) << "Failed to set flags: " << (flags | O_NONBLOCK) << " on fd: "
+        << fd_ << ", errno: " << errno;
     return -1;
   }
 
   int ret =
       connect(fd_, reinterpret_cast<struct sockaddr*>(&addr_), sizeof(addr_));
   if (fcntl(fd_, F_SETFL, flags) != 0) {
-    LOGE("Failed to set flags(%d) on fd(%d), errno(%d)",
-        flags, fd_, errno);
+    LOG(ERROR) << "Failed to set flags: " << flags << " on fd: " << fd_
+        << ", errno: " <<  errno;
     return -1;
   }
   if (ret < 0) {
index 3b7a5dfe3970540dfe2174ea3bcf728e8b237ec7..9763fa2111d6f60f3f30e5ffe2943af1251b3c29 100644 (file)
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include "server_socket.hh"
+
 #include <fcntl.h>
 #include <string.h>
 #include <systemd/sd-daemon.h>
@@ -22,8 +24,9 @@
 #include <sys/un.h>
 #include <unistd.h>
 
+#include "utils/logging.hh"
+
 #include "pkgmgrinfo_debug.h"
-#include "server_socket.hh"
 
 namespace pkgmgr_common {
 namespace socket {
@@ -40,30 +43,30 @@ ServerSocket::ServerSocket(std::string path) : AbstractSocket(std::move(path)) {
 
   if (fd_ == -1) {
     if (Create() < 0) {
-      LOGE("Fail to create server socket. errno(%d)", errno);
+      LOG(ERROR) << "Fail to create server socket. errno: " << errno;
       return;
     }
 
     addr_.sun_family = AF_UNIX;
     snprintf(addr_.sun_path, sizeof(addr_.sun_path), "%s", path_.c_str());
     if (access(path_.c_str(), F_OK) == 0) {
-      LOGW("socket(%s) is already used", path_.c_str());
+      LOG(WARNING) << "socket is already used : " << path_;
       unlink(path_.c_str());
     }
 
     if (Bind() < 0) {
-      LOGE("Fail to Bind server socket. errno(%d)", errno);
+      LOG(ERROR) << "Fail to Bind server socket. errno: " <<  errno;
       return;
     }
     if (Listen() < 0) {
-      LOGE("Fail to Listen server socket. errno(%d)", errno);
+      LOG(ERROR) << "Fail to Listen server socket. errno: " <<  errno;
       return;
     }
   }
 
   int flag = fcntl(fd_, F_GETFL, 0);
   fcntl(fd_, F_SETFL, flag | O_NONBLOCK);
-  LOGD("Server socket is created(%s)", path_.c_str());
+  LOG(DEBUG) << "Server socket is created: " << path_;
 }
 
 int ServerSocket::Bind() {
diff --git a/src/logging.cc b/src/logging.cc
deleted file mode 100644 (file)
index 5e2a5d6..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright (c) 2021 Samsung Electronics Co., Ltd All Rights Reserved
-// Use of this source code is governed by a apache 2.0 license that can be
-// found in the LICENSE file.
-
-#include "logging.hh"
-
-namespace utils {
-
-log_priority LogLevelToPriority(LogLevel level) {
-  switch (level) {
-    case LogLevel::LOG_ERROR:
-      return log_priority::DLOG_ERROR;
-    case LogLevel::LOG_WARNING:
-      return log_priority::DLOG_WARN;
-    case LogLevel::LOG_INFO:
-      return log_priority::DLOG_INFO;
-    case LogLevel::LOG_DEBUG:
-      return log_priority::DLOG_DEBUG;
-    default:
-      return log_priority::DLOG_UNKNOWN;
-  }
-}
-
-}  // namespace utils
diff --git a/src/logging.hh b/src/logging.hh
deleted file mode 100644 (file)
index 318c2d8..0000000
+++ /dev/null
@@ -1,180 +0,0 @@
-// Copyright (c) 2021 Samsung Electronics Co., Ltd All Rights Reserved
-// Use of this source code is governed by a apache 2.0 license that can be
-// found in the LICENSE file.
-
-#ifndef LOGGING_HH_
-#define LOGGING_HH_
-
-#include <dlog.h>
-
-#ifndef PROJECT_TAG
-#define PROJECT_TAG "PKGMGR_INFO"
-#endif
-
-#ifdef LOG
-#undef LOG
-#endif
-
-#include <cassert>
-#include <climits>
-#include <cstdio>
-#include <cstring>
-#include <iomanip>
-#include <iostream>
-#include <memory>
-#include <sstream>
-#include <string>
-#include <vector>
-
-#ifndef __FILENAME__
-#define __FILENAME__                                                           \
-    (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
-#endif
-
-namespace utils {
-
-enum class LogLevel {
-  LOG_ERROR,
-  LOG_WARNING,
-  LOG_INFO,
-  LOG_DEBUG,
-};
-
-log_priority LogLevelToPriority(LogLevel level);
-
-template<LogLevel> struct LogTag;
-template<> struct LogTag<LogLevel::LOG_ERROR> {
-  static constexpr const char* value = "\033[1;31m| ERROR   |\033[0m";
-};
-template<> struct LogTag<LogLevel::LOG_WARNING> {
-  static constexpr const char* value = "\033[1;33m| WARNING |\033[0m";
-};
-template<> struct LogTag<LogLevel::LOG_INFO>  {
-  static constexpr const char* value = "\033[1;32m| INFO    |\033[0m";
-};
-template<> struct LogTag<LogLevel::LOG_DEBUG> {
-  static constexpr const char* value = "\033[0m| DEBUG   |\033[0m";
-};
-
-template <class charT, class traits = std::char_traits<charT>>
-class StringStream : private std::basic_ostringstream<charT, traits> {
- public:
-  using std::basic_ostringstream<charT, traits>::str;
-
-  template <class T>
-  StringStream&  operator<<(const T& value) {
-    static_cast<std::basic_ostringstream<charT, traits> &>(*this) << value;
-    return *this;
-  }
-};
-
-// Interface class for logging backends. The custom LogBackend which wants
-// log using LOG() macro should be implement following interface.
-class ILogBackend {
- public:
-  virtual void WriteLog(LogLevel level, const std::string& tag,
-      const std::string& logstr) = 0;
-};
-
-class DLogBackend : public ILogBackend {
- public:
-  void WriteLog(LogLevel level, const std::string& tag,
-      const std::string& logstr) override {
-    dlog_print(LogLevelToPriority(level), tag.c_str(), "%s",
-        Escape(logstr).c_str());
-  }
-
- private:
-  // Since LogCatcher passes input to dlog_print(), the input which contains
-  // format string(such as %d, %n) can cause unexpected result.
-  // This is simple function to escape '%'.
-  // NOTE: Is there any gorgeous way instead of this?
-  std::string Escape(const std::string& str) const {
-    std::string escaped = std::string(str);
-    size_t start_pos = 0;
-    std::string from = "%";
-    std::string to = "%%";
-    while ((start_pos = escaped.find(from, start_pos)) != std::string::npos) {
-      escaped.replace(start_pos, from.length(), to);
-      start_pos += to.length();
-    }
-    return escaped;
-  }
-};
-
-class LogCore {
- public:
-  // Do not call this function at destructor of global object
-  static LogCore& GetCore() {
-    static LogCore core;
-    return core;
-  }
-
-  void AddLogBackend(std::shared_ptr<ILogBackend> backend) {
-    backend_list_.emplace_back(backend);
-  }
-
-  void Log(LogLevel level, const std::string& tag, const std::string& log) {
-    for (auto& backend : backend_list_)
-      backend->WriteLog(level, tag, log);
-  }
-
- private:
-  LogCore() {
-    // add default dlog backend
-    AddLogBackend(std::shared_ptr<ILogBackend>(new DLogBackend()));
-  }
-  ~LogCore() = default;
-  LogCore(const LogCore&) = delete;
-  LogCore& operator=(const LogCore&) = delete;
-
-  std::vector<std::shared_ptr<ILogBackend>> backend_list_;
-};
-
-class LogCatcher {
- public:
-  LogCatcher(LogLevel level, const char* tag)
-    : level_(level), tag_(tag) { }
-
-  void operator&(const StringStream<char>& str) const {
-    LogCore::GetCore().Log(level_, tag_, str.str());
-  }
-
- private:
-  LogLevel level_;
-  std::string tag_;
-};
-
-}  // namespace utils
-
-
-inline static const constexpr char* __tag_for_logging() {
-  return "";
-}
-
-inline static const constexpr char* __tag_for_project() {
-  return PROJECT_TAG;
-}
-
-// To be defined in class namespace if user want different log tag for given
-// scope
-#define SCOPE_LOG_TAG(TAG)                                                     \
-  inline static const constexpr char* __tag_for_logging() {                    \
-    return #TAG;                                                               \
-  }                                                                            \
-
-// Simple logging macro of following usage:
-//   LOG(LEVEL) << object_1 << object_2 << object_n;
-//     where:
-//       LEVEL = ERROR | WARNING | INFO | DEBUG
-#define LOG(LEVEL)                                                             \
-    ::utils::LogCatcher(                                                       \
-      ::utils::LogLevel::LOG_ ## LEVEL, __tag_for_project())                   \
-      & ::utils::StringStream<char>()                                          \
-      << std::string(::utils::LogTag<::utils::LogLevel::LOG_ ## LEVEL>::value) \
-      << " " << std::setw(25) << std::left << __tag_for_logging()              \
-      << " : " << std::setw(36)                                                \
-      << (std::string(__FILENAME__) + ":" + std::to_string(__LINE__)).c_str()  \
-      << std::setw(0) << " : "                                                 \
-
-#endif  // LOGGING_HH_
index 1d3d1202b13019d729d7f315ecccbd32fa400925..72b37fac8374f33c799ea5081249e13f72408125 100644 (file)
@@ -41,7 +41,7 @@
 #include "common/parcel/pkginfo_parcelable.hh"
 #include "common/parcel/query_parcelable.hh"
 #include "common/parcel/result_parcelable.hh"
-#include "logging.hh"
+#include "utils/logging.hh"
 
 #include "pkg_write_type.hh"
 #include "db_type.hh"
index 2bbe7447e5d16ecd1619d152d5914cc99253b5b5..e2c9a9dec2d411cfb75e62cb6b6567d841443653 100644 (file)
@@ -5,12 +5,14 @@ AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} SERVER_SRCS)
 AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR}/cynara_checker CYNARA_CHECKER_SRCS)
 AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR}/database DATABASE_SRCS)
 AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR}/request_handler REQUEST_HANDLER_SRCS)
+AUX_SOURCE_DIRECTORY(${CMAKE_SOURCE_DIR}/src/utils/ UTIL_SRCS)
 
 ADD_LIBRARY(pkgmgr-info-server SHARED
   ${CYNARA_CHECKER_SRCS}
   ${SERVER_SRCS}
   ${DATABASE_SRCS}
   ${REQUEST_HANDLER_SRCS}
+  ${UTIL_SRCS}
 )
 
 ADD_DEFINITIONS("-DSYSCONFDIR=\"${SYSCONFDIR}\"")
index aeb3c4c2ccecc9728dffe5d38b80a1aa53689024..660aea8c6c05eadaa6603ab62bc7085b8c208e91 100644 (file)
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include "cynara_checker.hh"
+
 #include <cynara-creds-socket.h>
 #include <cynara-session.h>
 #include <dlog.h>
@@ -23,7 +25,8 @@
 #include <memory>
 #include <mutex>
 
-#include "cynara_checker.hh"
+#include "utils/logging.hh"
+
 #include "pkgmgrinfo_private.h"
 
 namespace pkgmgr_server {
@@ -54,10 +57,10 @@ void CynaraChecker::ReplyCb(cynara_check_id id, cynara_async_call_cause cause,
     if (resp == CYNARA_API_ACCESS_ALLOWED) {
       auto it = inst.cynara_id_map_.find(id);
       if (it == inst.cynara_id_map_.end()) {
-        LOGE("Invalid request");
+        LOG(ERROR) << "Invalid request";
         break;
       }
-      LOGD("Allowed request");
+      LOG(DEBUG) << "Allowed request";
       runner->QueueRequest(it->second);
       inst.cynara_id_map_.erase(it);
     }
@@ -66,7 +69,7 @@ void CynaraChecker::ReplyCb(cynara_check_id id, cynara_async_call_cause cause,
   case CYNARA_CALL_CAUSE_FINISH:
   case CYNARA_CALL_CAUSE_SERVICE_NOT_AVAILABLE:
   default:
-    LOGE("Cynara: resp: not answer");
+    LOG(ERROR) << "Cynara: resp: not answer";
     break;
   }
 }
@@ -80,7 +83,7 @@ gboolean CynaraChecker::ProcessCb(gint fd, GIOCondition cond, gpointer data) {
 
   int ret = cynara_async_process(inst.cynara_);
   if (ret != CYNARA_API_SUCCESS)
-    LOGE("process error %d", ret);
+    LOG(ERROR) << "process error " << ret;
 
   return G_SOURCE_CONTINUE;
 }
@@ -108,7 +111,7 @@ void CynaraChecker::CheckPrivilege(Runner* runner,
     const std::shared_ptr<PkgRequest>& req,
     const std::vector<std::string>& privileges) {
   if (privileges.empty() || req->GetSenderUID() < REGULAR_USER) {
-    LOGD("Allowed request");
+    LOG(DEBUG) << "Allowed request";
     runner->QueueRequest(req);
     return;
   }
@@ -117,7 +120,7 @@ void CynaraChecker::CheckPrivilege(Runner* runner,
   if (cynara_ == nullptr) {
     ret = cynara_async_initialize(&cynara_, nullptr, StatusCb, nullptr);
     if (ret != CYNARA_API_SUCCESS) {
-      LOGE("Failed to initialize cynara_");
+      LOG(ERROR) << "Failed to initialize cynara_";
       return;
     }
   }
@@ -125,13 +128,14 @@ void CynaraChecker::CheckPrivilege(Runner* runner,
   ret = cynara_creds_socket_get_client(req->GetFd(), CLIENT_METHOD_SMACK,
       &smack_label);
   if (ret != CYNARA_API_SUCCESS) {
-    LOGE("Failed to get smack label");
+    LOG(ERROR) << "Failed to get smack label";
     return;
   }
   std::unique_ptr<char, decltype(std::free)*> lblPtr(smack_label, std::free);
   char* session = cynara_session_from_pid(req->GetSenderPID());
   if (session == nullptr) {
-    LOGE("Failed to get client session (pid:%d)", req->GetSenderPID());
+    LOG(ERROR) << "Failed to get client session for pid:"
+        << req->GetSenderPID();
     return;
   }
   std::unique_ptr<char, decltype(std::free)*> sessPtr(session, std::free);
index 771621c25de05d292a4ff60d850f8563164f0cf1..e53cfcb0e6ab05dcb2af93be62adeea3babc4493 100644 (file)
@@ -27,6 +27,8 @@
 #include <vector>
 
 #include "db_handle_provider.hh"
+#include "utils/logging.hh"
+
 #include "pkgmgr-info.h"
 #include "pkgmgrinfo_debug.h"
 #include "pkgmgrinfo_private.h"
@@ -58,8 +60,7 @@ int __open_read_db(const char *path, sqlite3 **db) {
 
   ret = sqlite3_busy_handler(*db, __readdb_busy_handler, NULL);
   if (ret != SQLITE_OK) {
-    _LOGE("failed to register busy handler: %s",
-        sqlite3_errmsg(*db));
+    LOG(ERROR) << "failed to register busy handler:" << sqlite3_errmsg(*db);
     sqlite3_close_v2(*db);
     return ret;
   }
@@ -98,16 +99,15 @@ int __open_write_db(uid_t uid, const char* path,
   ret = sqlite3_busy_handler(*db, __writedb_busy_handler,
       reinterpret_cast<void*>(const_cast<char*>(path)));
   if (ret != SQLITE_OK) {
-    _LOGE("failed to register busy handler: %s",
-        sqlite3_errmsg(*db));
+    LOG(ERROR) << "failed to register busy handler:" << sqlite3_errmsg(*db);
     sqlite3_close_v2(*db);
     return ret;
   }
 
   ret = sqlite3_exec(*db, "PRAGMA foreign_keys=ON", NULL, NULL, NULL);
   if (ret != SQLITE_OK) {
-    _LOGE("failed to enable foreign key support: %s",
-        sqlite3_errmsg(*db));
+    LOG(ERROR) << "failed to enable foreign key support:"
+        << sqlite3_errmsg(*db);
     sqlite3_close_v2(*db);
     return ret;
   }
@@ -129,8 +129,7 @@ int __open_create_db(uid_t uid, const char* path,
   ret = sqlite3_busy_handler(*db, __writedb_busy_handler,
       reinterpret_cast<void*>(const_cast<char*>(path)));
   if (ret != SQLITE_OK) {
-    _LOGE("failed to register busy handler: %s",
-        sqlite3_errmsg(*db));
+    LOG(ERROR) << "failed to register busy handler:" << sqlite3_errmsg(*db);
     sqlite3_close_v2(*db);
     return ret;
   }
@@ -173,7 +172,7 @@ std::vector<std::pair<std::string, uid_t>> AbstractDBHandler::GetDBPath() {
 bool AbstractDBHandler::Connect() {
   if (db_type_ == pkgmgr_common::DBType::DB_TYPE_NONE ||
       op_type_ == pkgmgr_common::DBOperationType::OPERATION_TYPE_NONE) {
-    _LOGE("Invalid parameter");
+    LOG(ERROR) << "Invalid parameter";
     return false;
   }
   auto dbpath_list = GetDBPath();
@@ -191,7 +190,7 @@ bool AbstractDBHandler::Connect() {
         continue;
 
       if (access(dbpath.first.c_str(), F_OK) != -1) {
-        _LOGE("Database for user %d is already exists", uid_);
+        LOG(ERROR) << "Database for user " << uid_ << " is already exists";
         return false;
       }
       ret = __open_create_db(uid_, dbpath.first.c_str(), &db);
index 26ce9d12e704d0b17c394e249af0c6c18f32ad4e..fafb2f10839879b450724acd44797fb24bac1a29 100644 (file)
@@ -19,6 +19,8 @@
 #include <vector>
 #include <shared_mutex>
 
+#include "utils/logging.hh"
+
 #include "pkgmgrinfo_basic.h"
 #include "pkgmgrinfo_debug.h"
 #include "pkgmgrinfo_internal.h"
@@ -72,7 +74,7 @@ int AppInfoDBHandler::Execute() {
     ret = appinfo_internal_filter_get_list(conn.first, filter_, conn.second,
         uid_, GetLocale().c_str(), list);
     if (ret == PMINFO_R_ERROR) {
-      _LOGD("Failed to appinfo_internal_filter_get_list (%d)", ret);
+      LOG(DEBUG) << "Failed to appinfo_internal_filter_get_list: " << ret;
       break;
     }
   }
index d6daecb2bf71da086e8874c9b1a5d85492286a61..2001bd13024670abab48b22fcfd34903cee5968d 100644 (file)
@@ -19,6 +19,8 @@
 #include <shared_mutex>
 #include <vector>
 
+#include "utils/logging.hh"
+
 #include "pkgmgrinfo_debug.h"
 #include "pkgmgrinfo_internal.h"
 
@@ -45,7 +47,7 @@ int CertGetDBHandler::Execute() {
   SetDBType(pkgmgr_common::DBType::DB_TYPE_FILE_CERTDB);
 
   if (!Connect()) {
-    _LOGE("Failed to connect database");
+    LOG(ERROR) << "Failed to connect database";
     return PMINFO_R_ERROR;
   }
 
index a123fb326093c06b1c7ab6c3b2a235e6fc98c603..da918fe24b69ced359b5f4357ca03f14cc031a86 100644 (file)
@@ -19,6 +19,7 @@
 #include <vector>
 
 #include "db_handle_provider.hh"
+#include "utils/logging.hh"
 
 #include "pkgmgrinfo_debug.h"
 #include "pkgmgrinfo_internal.h"
@@ -46,13 +47,13 @@ int CreateDBHandler::Execute() {
   std::unique_lock<std::shared_timed_mutex> u(lock_);
 
   if (CreateParserDB() < 0) {
-    LOGE("Failed to create parser db for uid [%d]", GetUID());
+    LOG(ERROR) << "Failed to create parser db for uid : " << GetUID();
     return PMINFO_R_ERROR;
   }
 
   if (GetUID() == GLOBAL_USER || GetUID() == OWNER_ROOT) {
     if (CreateCertDB() < 0) {
-      LOGE("Failed to create cert db for uid [%d]", GetUID());
+      LOG(ERROR) << "Failed to create cert db";
       return PMINFO_R_ERROR;
     }
   }
index 61663e0d19aa52e706d9d777b9731e6d10f01347..1210b4a02bf3ece066fc9fc8ae9ff2f8b93f9274 100644 (file)
@@ -25,6 +25,8 @@
 #include <string>
 #include <vector>
 
+#include "utils/logging.hh"
+
 #include "pkgmgrinfo_debug.h"
 #include "pkgmgr-info.h"
 
@@ -113,14 +115,14 @@ bool DBHandleProvider::IsCrashedWriteRequest() {
     return false;
 
   bool ret = true;
-  LOGD("Check process count : %zu", pid_list_.size());
+  LOG(DEBUG) << "Check process count : " << pid_list_.size();
   std::vector<pid_t> remove_pids;
   for (pid_t pid : pid_list_) {
     std::string status_path = "/proc/" + std::to_string(pid) + "/status";
 
     int fd = open(status_path.c_str(), O_RDONLY);
     if (fd < 0) {
-      LOGE("Process is crashed (%d)", pid);
+      LOG(ERROR) << "Process is crashed : " << pid;
       remove_pids.push_back(pid);
     } else {
       ret = false;
@@ -155,10 +157,10 @@ std::vector<std::pair<std::string, uid_t>> DBHandleProvider::GetParserDBPath(
   }
 
   if (db_path_list.size() == 1) {
-    LOGD("global db path : %s", db_path_list[0].first.c_str());
+    LOG(DEBUG) << "global db path : " << db_path_list[0].first;
   } else {
-    LOGD("local db path : %s", db_path_list[0].first.c_str());
-    LOGD("global db path : %s", db_path_list[1].first.c_str());
+    LOG(DEBUG) << "local db path : " << db_path_list[0].first;
+    LOG(DEBUG) << "global db path : " << db_path_list[1].first;
   }
 
   return db_path_list;
@@ -183,14 +185,14 @@ sqlite3* DBHandleProvider::GetMemoryDBHandle(const std::string& filedb_path,
   int ret = sqlite3_open_v2(memorydb_path.c_str(), &memorydb,
       SQLITE_OPEN_READONLY | SQLITE_OPEN_URI, nullptr);
   if (ret != SQLITE_OK) {
-    LOGE("Failed to open memory DB %d(%s)", ret, memorydb_path.c_str());
+    LOG(ERROR) << "Failed to open memory DB " << ret << ": " << memorydb_path;
     return nullptr;
   }
 
   ret = sqlite3_open_v2(filedb_path.c_str(), &filedb,
       SQLITE_OPEN_READONLY, nullptr);
   if (ret != SQLITE_OK) {
-    LOGE("Failed to open file DB %d(%s)", ret, filedb_path.c_str());
+    LOG(ERROR) << "Failed to open file DB " << ret << ": " << filedb_path;
     sqlite3_close_v2(memorydb);
     return nullptr;
   }
@@ -198,7 +200,7 @@ sqlite3* DBHandleProvider::GetMemoryDBHandle(const std::string& filedb_path,
   sqlite3_backup* backup = sqlite3_backup_init(memorydb, "main",
       filedb, "main");
   if (backup == nullptr) {
-    LOGE("Failed to backup for memory DB");
+    LOG(ERROR) << "Failed to backup for memory DB";
     sqlite3_close_v2(memorydb);
     sqlite3_close_v2(filedb);
     return nullptr;
@@ -236,7 +238,7 @@ void DBHandleProvider::SetMemoryMode(pid_t pid) {
 
   is_memory_ = true;
   is_memory_global_ = true;
-  LOGD("Set Memory mode : Memory");
+  LOG(DEBUG) << "Set Memory mode : Memory";
 }
 
 void DBHandleProvider::UnsetMemoryMode(pid_t pid) {
@@ -252,11 +254,11 @@ void DBHandleProvider::UnsetMemoryMode(pid_t pid) {
   if (it != pid_list_.end())
     pid_list_.erase(it);
   else
-    LOGE("Given pid is not exists in pid list : %d", pid);
+    LOG(ERROR) << "Given pid is not exists in pid list : " << pid;
 
   is_memory_ = false;
   is_memory_global_ = false;
-  LOGD("Set Memory mode : File");
+  LOG(DEBUG) << "Set Memory mode : File";
 }
 
 bool DBHandleProvider::IsMemoryDBActive(pid_t pid, bool write) {
index e2ef3f4192506c92c483c6c6a7918a7625bf0cd2..98d6b7eea4033df960897b5de96c24a165e4c78b 100644 (file)
@@ -19,6 +19,8 @@
 #include <shared_mutex>
 #include <vector>
 
+#include "utils/logging.hh"
+
 #include "pkgmgrinfo_debug.h"
 #include "pkgmgrinfo_internal.h"
 
@@ -44,7 +46,7 @@ int DepInfoGetDBHandler::Execute() {
   SetDBType(pkgmgr_common::DBType::DB_TYPE_FILE_PKGDB);
 
   if (!Connect()) {
-    _LOGE("Failed to connect database");
+    LOG(ERROR) << "Failed to connect database";
     return PMINFO_R_ERROR;
   }
   GList* list = nullptr;
index 0c80cd0e12440cedc40b0e98e37e525a79f9b553..dd8518b4bf105f5b57c319da541d3d9c69b10bb5 100644 (file)
@@ -19,6 +19,8 @@
 #include <shared_mutex>
 #include <vector>
 
+#include "utils/logging.hh"
+
 #include "pkgmgrinfo_debug.h"
 #include "pkgmgrinfo_internal.h"
 
@@ -60,7 +62,7 @@ int PkgGetDBHandler::Execute() {
   SetOpType(pkgmgr_common::DBOperationType::OPERATION_TYPE_READ);
   SetDBType(pkgmgr_common::DBType::DB_TYPE_FILE_PKGDB);
   if (!Connect()) {
-    _LOGE("Failed to connect database");
+    LOG(ERROR) << "Failed to connect database";
     return PMINFO_R_ERROR;
   }
 
@@ -72,7 +74,7 @@ int PkgGetDBHandler::Execute() {
     ret = pkginfo_internal_filter_get_list(conn.first, filter_, conn.second,
                                             GetLocale().c_str(), list);
     if (ret == PMINFO_R_ERROR) {
-      _LOGE("Failed to pkginfo_internal_filter_get_list (%d)", ret);
+      LOG(ERROR) << "Failed to pkginfo_internal_filter_get_list : " << ret;
       break;
     }
   }
index d4c46b1bef741f9ead7ee9e2407ed81c205ace2e..170a0f79cbae4246f92ebbeaf3e7240d8481c733 100644 (file)
@@ -19,6 +19,7 @@
 #include <vector>
 
 #include "db_handle_provider.hh"
+#include "utils/logging.hh"
 
 #include "pkgmgrinfo_debug.h"
 #include "pkgmgrinfo_internal.h"
@@ -66,7 +67,7 @@ int PkgSetDBHandler::Execute() {
   else if (write_type_ == pkgmgr_common::PkgWriteType::Delete)
     ret = pkgmgr_parser_delete_pkg_info(conn, package_->package, uid_);
   else
-    _LOGE("Unknown db write type");
+    LOG(ERROR) << "Unknown db write type";
 
   if (ret != PM_PARSER_R_OK)
     return ret;
index ef58fb411a213ed5d9dd8776f48b51866e4cb7c4..e1f90c588d599ac4fcfd89b85f927b6280357b74 100644 (file)
@@ -19,6 +19,8 @@
 #include <shared_mutex>
 #include <vector>
 
+#include "utils/logging.hh"
+
 #include "pkgmgrinfo_debug.h"
 #include "pkgmgrinfo_internal.h"
 #include "pkgmgr_query_index.h"
@@ -219,7 +221,7 @@ std::vector<pkgmgr_common::parcel::StrArgs> QueryHandler::GetResult() {
 int QueryHandler::Execute() {
   std::shared_lock<std::shared_timed_mutex> s(lock_);
   if (!Connect()) {
-    _LOGE("Failed to connect database");
+    LOG(ERROR) << "Failed to connect database";
     return PMINFO_R_ERROR;
   }
 
@@ -228,7 +230,7 @@ int QueryHandler::Execute() {
   for (auto& i : query_args_) {
     const char* query = __query_maker.GetQuery(i.first);
     if (query == nullptr) {
-      _LOGE("Failed to get query");
+      LOG(ERROR) << "Failed to get query";
       __free_query_list(queries, args_list);
       return PMINFO_R_ERROR;
     }
@@ -236,7 +238,7 @@ int QueryHandler::Execute() {
     queries = g_list_append(queries, (gpointer)query);
     query_args* arg = (query_args*)calloc(1, sizeof(query_args));
     if (arg == nullptr) {
-      _LOGE("Out of memory");
+      LOG(ERROR) << "Out of memory";
       __free_query_list(queries, args_list);
       return PMINFO_R_ERROR;
     }
@@ -262,7 +264,7 @@ int QueryHandler::Execute() {
         ret = get_query_result(conn.first, (const char *)queries->data,
             params->argument, &list, &row, &col);
         if (ret == PMINFO_R_ERROR) {
-          _LOGE("Failed to execute query");
+          LOG(ERROR) << "Failed to execute query";
           __free_query_list(queries, args_list);
           return ret;
         }
@@ -290,7 +292,7 @@ int QueryHandler::Execute() {
     for (auto& conn : conn_list) {
       ret = execute_write_queries(conn.first, queries, args_list);
       if (ret != PMINFO_R_OK) {
-        _LOGE("Failed to execute");
+        LOG(ERROR) << "Failed to execute";
         break;
       }
     }
index f4767dcfdd1cf97bea0a622a8b7cb28504102dcb..0da63003b7226f7d84dccc144f2f3d013f5322be 100644 (file)
@@ -15,6 +15,9 @@
  */
 
 #include "pkg_request.hh"
+
+#include "utils/logging.hh"
+
 #include "pkgmgrinfo_debug.h"
 
 namespace pkgmgr_server {
@@ -24,7 +27,7 @@ PkgRequest::PkgRequest(int fd)
   socket_ = std::unique_ptr<pkgmgr_common::socket::DataSocket>(
       new (std::nothrow) pkgmgr_common::socket::DataSocket(fd));
   if (socket_ == nullptr)
-    LOGE("Out of memory");
+    LOG(ERROR) << "Out of memory";
 }
 
 PkgRequest::~PkgRequest() {
@@ -59,30 +62,30 @@ pkgmgr_common::ReqType PkgRequest::GetRequestType() {
 bool PkgRequest::ReceiveData() {
   int ret = socket_->ReceiveData(&request_type_, sizeof(request_type_));
   if (ret < 0 || request_type_ == pkgmgr_common::REQ_TYPE_NONE) {
-    LOGE("Failed to ReceiveData");
+    LOG(ERROR) << "Failed to ReceiveData";
     return false;
   }
   ret = socket_->ReceiveData(&data_size_, sizeof(data_size_));
   if (ret < 0) {
-    LOGE("Failed to ReceiveData");
+    LOG(ERROR) << "Failed to ReceiveData";
     request_type_ = pkgmgr_common::REQ_TYPE_NONE;
     return false;
   }
   if (data_size_ <= 0) {
-    LOGE("Invalid data");
+    LOG(ERROR) << "Invalid data";
     request_type_ = pkgmgr_common::REQ_TYPE_NONE;
     return false;
   }
 
   data_ = new (std::nothrow) unsigned char[data_size_];
   if (data_ == nullptr) {
-    LOGE("Out of memory");
+    LOG(ERROR) << "Out of memory";
     request_type_ = pkgmgr_common::REQ_TYPE_NONE;
     return false;
   }
   ret = socket_->ReceiveData(reinterpret_cast<void*>(data_), data_size_);
   if (ret < 0) {
-    LOGE("Failed to ReceiveData");
+    LOG(ERROR) << "Failed to ReceiveData";
     delete[] data_;
     data_ = nullptr;
     request_type_ = pkgmgr_common::REQ_TYPE_NONE;
index 39da2e75cde57ef83c3e5834cd9dee87fedea9a6..e928b93cf00a5f3e56b8dd24fa2a2efef3ad7caa 100644 (file)
@@ -9,6 +9,7 @@
 #include "db_handle_provider.hh"
 #include "parcelable_factory.hh"
 #include "pkginfo_parcelable.hh"
+#include "utils/logging.hh"
 
 #include "pkgmgrinfo_debug.h"
 #include "pkgmgrinfo_type.h"
@@ -25,7 +26,7 @@ bool CommandRequestHandler::HandleRequest(unsigned char* data, int size,
 
   if (abstract_parcel == nullptr ||
       abstract_parcel->GetType() != pcp::ParcelableType::Command) {
-    _LOGE("Invalid parcel or type");
+    LOG(ERROR) << "Invalid parcel or type";
     result_ = std::make_shared<pcp::ResultParcelable>(
         PMINFO_R_ERROR, std::vector<pcp::StrArgs>{});
     return false;
@@ -33,7 +34,7 @@ bool CommandRequestHandler::HandleRequest(unsigned char* data, int size,
 
   auto* parcel = dynamic_cast<pcp::CommandParcelable*>(abstract_parcel.get());
   if (parcel == nullptr) {
-    _LOGE("Parcel is empty");
+    LOG(ERROR) << "Parcel is empty";
     result_ = std::make_shared<pcp::ResultParcelable>(
         PMINFO_R_ERROR, std::vector<pcp::StrArgs>{});
     return false;
index 7d86c62863520fd9a5a13c6d4b59332ed8d64f57..5cbd424bab3e4d27ec426f324ae62fb427e01ba3 100644 (file)
@@ -6,10 +6,11 @@
 
 #include <string>
 
-#include "parcelable_factory.hh"
 #include "create_db_parcelable.hh"
 #include "create_db_handler.hh"
 #include "db_type.hh"
+#include "parcelable_factory.hh"
+#include "utils/logging.hh"
 
 #include "pkgmgr_parser.h"
 
@@ -28,7 +29,7 @@ bool CreateDBRequestHandler::HandleRequest(unsigned char* data, int size,
 
   if (abstract_parcel == nullptr ||
       abstract_parcel->GetType() != pcp::ParcelableType::CreateDB) {
-    _LOGE("Invalid parcel or type");
+    LOG(ERROR) << "Invalid parcel or type";
     result_ = std::make_shared<pcp::ResultParcelable>(
         PM_PARSER_R_ERROR, std::vector<pcp::StrArgs>{});
     return false;
@@ -36,7 +37,7 @@ bool CreateDBRequestHandler::HandleRequest(unsigned char* data, int size,
 
   auto* parcel = dynamic_cast<pcp::CreateDBParcelable*>(abstract_parcel.get());
   if (parcel == nullptr) {
-    _LOGE("Parcel is empty");
+    LOG(ERROR) << "Parcel is empty";
     result_ = std::make_shared<pcp::ResultParcelable>(
         PM_PARSER_R_ERROR, std::vector<pcp::StrArgs>{});
     return false;
index 50f3c790a8d39f221bc84bf67ca2a90be3120199..73bf7947f873c28cded588086f40f96a43046a17 100644 (file)
@@ -6,9 +6,10 @@
 
 #include <string>
 
-#include "parcelable_factory.hh"
-#include "filter_parcelable.hh"
 #include "appinfo_db_handler.hh"
+#include "filter_parcelable.hh"
+#include "parcelable_factory.hh"
+#include "utils/logging.hh"
 
 #include "pkgmgrinfo_debug.h"
 
@@ -25,7 +26,7 @@ bool GetAppinfoRequestHandler::HandleRequest(unsigned char* data, int size,
 
   if (abstract_parcel == nullptr ||
       abstract_parcel->GetType() != pcp::ParcelableType::Filter) {
-    _LOGE("Invalid parcel or type");
+    LOG(ERROR) << "Invalid parcel or type";
     result_ = std::make_shared<pcp::AppInfoParcelable>(
         PMINFO_R_ERROR, std::vector<application_x*>{});
     return false;
@@ -33,7 +34,7 @@ bool GetAppinfoRequestHandler::HandleRequest(unsigned char* data, int size,
 
   auto* parcel = dynamic_cast<pcp::FilterParcelable*>(abstract_parcel.get());
   if (parcel == nullptr) {
-    _LOGE("Parcel is empty");
+    LOG(ERROR) << "Parcel is empty";
     result_ = std::make_shared<pcp::AppInfoParcelable>(
         PMINFO_R_ERROR, std::vector<application_x*>{});
     return false;
index 51a59038de4a47294b409fa31c72942e743cb946..cbad2c9ce38e11875eac26a8d8722b99ed58c41a 100644 (file)
@@ -8,6 +8,7 @@
 
 #include "database/cert_get_db_handler.hh"
 #include "parcelable_factory.hh"
+#include "utils/logging.hh"
 
 #include "pkgmgrinfo_debug.h"
 
@@ -24,7 +25,7 @@ bool GetCertRequestHandler::HandleRequest(unsigned char* data, int size,
 
   if (abstract_parcel == nullptr ||
       abstract_parcel->GetType() != pcp::ParcelableType::CertInfo) {
-    _LOGE("Invalid parcel or type");
+    LOG(ERROR) << "Invalid parcel or type";
     result_ = std::make_shared<pcp::CertInfoParcelable>(
         PMINFO_R_ERROR, nullptr);
     return false;
@@ -32,7 +33,7 @@ bool GetCertRequestHandler::HandleRequest(unsigned char* data, int size,
 
   auto* parcel = dynamic_cast<pcp::CertInfoParcelable*>(abstract_parcel.get());
   if (parcel == nullptr) {
-    _LOGE("Parcel is empty");
+    LOG(ERROR) << "Parcel is empty";
     result_ = std::make_shared<pcp::CertInfoParcelable>(
         PMINFO_R_ERROR, nullptr);
     return false;
index fbbc0381385ec6c5c502187de3b7b3940bac4d5f..be7480c40a9f073311e24d3bf4735af1a5687f5a 100644 (file)
@@ -9,6 +9,7 @@
 #include "depinfo_db_handler.hh"
 #include "depinfo_parcelable.hh"
 #include "parcelable_factory.hh"
+#include "utils/logging.hh"
 
 #include "pkgmgrinfo_debug.h"
 
@@ -25,7 +26,7 @@ bool GetDepinfoRequestHandler::HandleRequest(unsigned char* data, int size,
 
   if (abstract_parcel == nullptr ||
       abstract_parcel->GetType() != pcp::ParcelableType::DepInfo) {
-    _LOGE("Invalid parcel or type");
+    LOG(ERROR) << "Invalid parcel or type";
     result_ = std::make_shared<pcp::DepInfoParcelable>(
         PMINFO_R_ERROR, std::vector<dependency_x*>{});
     return false;
@@ -33,7 +34,7 @@ bool GetDepinfoRequestHandler::HandleRequest(unsigned char* data, int size,
 
   auto* parcel = dynamic_cast<pcp::DepInfoParcelable*>(abstract_parcel.get());
   if (parcel == nullptr) {
-    _LOGE("Parcel is empty");
+    LOG(ERROR) << "Parcel is empty";
     result_ = std::make_shared<pcp::DepInfoParcelable>(
         PMINFO_R_ERROR, std::vector<dependency_x*>{});
     return false;
index 413e3f5c250d56aa9d863a810772c19a855e53ae..f198912746278286814e2e9f20c3cf29c86b667c 100644 (file)
@@ -6,9 +6,10 @@
 
 #include <string>
 
+#include "filter_parcelable.hh"
 #include "parcelable_factory.hh"
 #include "pkg_get_db_handler.hh"
-#include "filter_parcelable.hh"
+#include "utils/logging.hh"
 
 #include "pkgmgrinfo_debug.h"
 
@@ -26,7 +27,7 @@ bool GetPkginfoRequestHandler::HandleRequest(unsigned char* data, int size,
 
   if (abstract_parcel == nullptr ||
       abstract_parcel->GetType() != pcp::ParcelableType::Filter) {
-    _LOGE("Invalid parcel or type");
+    LOG(ERROR) << "Invalid parcel or type";
     result_ = std::make_shared<pcp::PkgInfoParcelable>(
         PMINFO_R_ERROR, std::vector<package_x*>{});
     return false;
@@ -34,7 +35,7 @@ bool GetPkginfoRequestHandler::HandleRequest(unsigned char* data, int size,
 
   auto* parcel = dynamic_cast<pcp::FilterParcelable*>(abstract_parcel.get());
   if (parcel == nullptr) {
-    _LOGE("Parcel is empty");
+    LOG(ERROR) << "Parcel is empty";
     result_ = std::make_shared<pcp::PkgInfoParcelable>(
         PMINFO_R_ERROR, std::vector<package_x*>{});
     return false;
index f3da77a222df1b8444649282043e9e7364272dbd..f7dbc1926f3ad64af346261dbfd4d0457805ef7b 100644 (file)
@@ -9,6 +9,7 @@
 #include "parcelable_factory.hh"
 #include "query_handler.hh"
 #include "query_parcelable.hh"
+#include "utils/logging.hh"
 
 #include "pkgmgrinfo_debug.h"
 
@@ -25,7 +26,7 @@ bool QueryRequestHandler::HandleRequest(unsigned char* data, int size,
 
   if (abstract_parcel == nullptr ||
       abstract_parcel->GetType() != pcp::ParcelableType::Query) {
-    _LOGE("Invalid parcel or type");
+    LOG(ERROR) << "Invalid parcel or type";
     result_ = std::make_shared<pcp::ResultParcelable>(
         PMINFO_R_ERROR, std::vector<pcp::StrArgs>{});
     return false;
@@ -33,7 +34,7 @@ bool QueryRequestHandler::HandleRequest(unsigned char* data, int size,
 
   auto* parcel = dynamic_cast<pcp::QueryParcelable*>(abstract_parcel.get());
   if (parcel == nullptr) {
-    _LOGE("Parcel is empty");
+    LOG(ERROR) << "Parcel is empty";
     result_ = std::make_shared<pcp::ResultParcelable>(
         PMINFO_R_ERROR, std::vector<pcp::StrArgs>{});
     return false;
index 97cea929606f80df6eff2fd231953c4f3350445c..b7b8adc1cbfd325d345fab356373bccfcc135dc9 100644 (file)
@@ -28,6 +28,7 @@
 #include "query_request_handler.hh"
 #include "set_cert_request_handler.hh"
 #include "set_pkginfo_request_handler.hh"
+#include "utils/logging.hh"
 
 #ifdef EXPORT_API
 #undef EXPORT_API
@@ -78,17 +79,17 @@ extern "C" EXPORT_API void* _request_handler_direct_access(int req_type,
   }
 
   if (handler == nullptr) {
-    _LOGE("Can't reset handler with type[%d]", req_type);
+    LOG(ERROR) << "Can't reset handler with type : " << req_type;
     return nullptr;
   }
 
   if (!handler->HandleRequest(data, size, locale)) {
-    LOGE("Failed to handle request");
+    LOG(ERROR) << "Failed to handle request";
     return nullptr;
   }
   auto result = handler->ExtractResult();
   if (result.size() == 0) {
-    _LOGE("Fail to extract result");
+    LOG(ERROR) << "Fail to extract result";
     return nullptr;
   }
 
index b216e182b20ed1d494963bc2af7059c9a14ece9f..32c360a0de739aa9096fbb6468916cdf1372b2a0 100644 (file)
@@ -8,6 +8,7 @@
 
 #include "certinfo_parcelable.hh"
 #include "cert_set_db_handler.hh"
+#include "utils/logging.hh"
 #include "parcelable_factory.hh"
 
 #include "pkgmgrinfo_debug.h"
@@ -25,7 +26,7 @@ bool SetCertRequestHandler::HandleRequest(unsigned char* data, int size,
 
   if (abstract_parcel == nullptr ||
       abstract_parcel->GetType() != pcp::ParcelableType::CertInfo) {
-    _LOGE("Invalid parcel");
+    LOG(ERROR) << "Invalid parcel";
     result_ = std::make_shared<pcp::ResultParcelable>(
         PMINFO_R_ERROR, std::vector<pcp::StrArgs>{});
     return false;
@@ -33,7 +34,7 @@ bool SetCertRequestHandler::HandleRequest(unsigned char* data, int size,
 
   auto* parcel = dynamic_cast<pcp::CertInfoParcelable*>(abstract_parcel.get());
   if (parcel == nullptr) {
-    _LOGE("Parcel is empty");
+    LOG(ERROR) << "Parcel is empty";
     result_ = std::make_shared<pcp::ResultParcelable>(
         PMINFO_R_ERROR, std::vector<pcp::StrArgs>{});
     return false;
index ab94515e42c478182969e95aee5e296e5dbce213..d530b5dc232a24614ca74a427124fbc6c1ae828d 100644 (file)
@@ -9,6 +9,7 @@
 #include "parcelable_factory.hh"
 #include "pkginfo_parcelable.hh"
 #include "pkg_set_db_handler.hh"
+#include "utils/logging.hh"
 
 #include "pkgmgr_parser.h"
 
@@ -27,7 +28,7 @@ bool SetPkginfoRequestHandler::HandleRequest(unsigned char* data, int size,
 
   if (abstract_parcel == nullptr ||
       abstract_parcel->GetType() != pcp::ParcelableType::PkgInfo) {
-    _LOGE("Invalid parcel or type");
+    LOG(ERROR) << "Invalid parcel or type";
     result_ = std::make_shared<pcp::ResultParcelable>(
         PM_PARSER_R_ERROR, std::vector<pcp::StrArgs>{});
     return false;
@@ -35,7 +36,7 @@ bool SetPkginfoRequestHandler::HandleRequest(unsigned char* data, int size,
 
   auto* parcel = dynamic_cast<pcp::PkgInfoParcelable*>(abstract_parcel.get());
   if (parcel == nullptr) {
-    _LOGE("Parcel is empty");
+    LOG(ERROR) << "Parcel is empty";
     result_ = std::make_shared<pcp::ResultParcelable>(
         PM_PARSER_R_ERROR, std::vector<pcp::StrArgs>{});
     return false;
@@ -51,7 +52,7 @@ bool SetPkginfoRequestHandler::HandleRequest(unsigned char* data, int size,
     db.SetPkgInfo(i);
     ret = db.Execute();
     if (ret != PM_PARSER_R_OK) {
-      _LOGE("Failed to set pkginfo");
+      LOG(ERROR) << "Failed to set pkginfo";
       break;
     }
   }
index c80bbc3be121c3744c5b4efc0d184d0643c4bc14..8d7184c22d05e08f95c487d745521e3cbe76f5de 100644 (file)
@@ -27,6 +27,8 @@
 #include "cynara_checker.hh"
 #include "pkg_request.hh"
 #include "runner.hh"
+#include "utils/logging.hh"
+
 #include "pkgmgrinfo_debug.h"
 #include "pkgmgrinfo_private.h"
 
@@ -75,7 +77,8 @@ Runner::~Runner() {
 
 int Runner::OnReceiveRequest(int fd, GIOCondition cond, void* user_data) {
   if (static_cast<int>(cond) & (G_IO_ERR | G_IO_HUP | G_IO_NVAL)) {
-    LOGE("Invalid condition fd(%d) condition(%d)", fd, static_cast<int>(cond));
+    LOG(ERROR) << "Invalid condition fd:" << fd
+        << ", condition:" << static_cast<int>(cond);
     abort();
     return G_SOURCE_REMOVE;
   }
@@ -83,7 +86,7 @@ int Runner::OnReceiveRequest(int fd, GIOCondition cond, void* user_data) {
   auto runner = static_cast<Runner*>(user_data);
   int client_fd = runner->server_->Accept();
   if (client_fd < 0) {
-    LOGE("Failed to Accept. errno(%d)", errno);
+    LOG(ERROR) << "Failed to Accept. errno:" << errno;
     return G_SOURCE_CONTINUE;
   }
 
index 983b4f4136cdb21df185beee65d0dc76a1ff52e8..5ec23501fd49e5ac30d06b27a8279fb778ce60fc 100644 (file)
  * limitations under the License.
  */
 
+#include "worker_thread.hh"
+
 #include <sqlite3.h>
 #include <malloc.h>
 
-#include "worker_thread.hh"
+#include "abstract_parcelable.hh"
+#include "command_request_handler.hh"
+#include "create_db_request_handler.hh"
 #include "db_handle_provider.hh"
-
-#include "pkgmgrinfo_debug.h"
 #include "get_appinfo_request_handler.hh"
 #include "get_cert_request_handler.hh"
-#include "get_pkginfo_request_handler.hh"
 #include "get_depinfo_request_handler.hh"
-#include "create_db_request_handler.hh"
+#include "get_pkginfo_request_handler.hh"
 #include "query_request_handler.hh"
 #include "set_cert_request_handler.hh"
 #include "set_pkginfo_request_handler.hh"
-#include "abstract_parcelable.hh"
-#include "command_request_handler.hh"
+#include "utils/logging.hh"
+
+#include "pkgmgrinfo_debug.h"
 
 #ifdef LOG_TAG
 #undef LOG_TAG
@@ -48,7 +50,7 @@ WorkerThread::WorkerThread(unsigned int num) : stop_all_(false) {
   for (unsigned int i = 0; i < num; ++i)
     threads_.emplace_back([this]() -> void { this->Run(); });
 
-  LOGD("%d Worker threads are created", num);
+  LOG(DEBUG) << num << " Worker threads are created";
 }
 
 WorkerThread::~WorkerThread() {
@@ -90,7 +92,7 @@ void WorkerThread::Run() {
   handler[pkgmgr_common::ReqType::CREATE_DB].reset(
       new request_handler::CreateDBRequestHandler());
 
-  LOGD("Initialize request handlers");
+  LOG(DEBUG) << "Initialize request handlers";
   while (true) {
     std::shared_ptr<PkgRequest> req;
     {
@@ -102,12 +104,12 @@ void WorkerThread::Run() {
     }
 
     pkgmgr_common::ReqType type = req->GetRequestType();
-    LOGW("Request type(%s), pid(%d)",
-        pkgmgr_common::ReqTypeToString(type), req->GetSenderPID());
+    LOG(WARNING) << "Request type: " << pkgmgr_common::ReqTypeToString(type)
+        << " pid: " << req->GetSenderPID();
     if (type <= pkgmgr_common::ReqType::REQ_TYPE_NONE
             || type >= pkgmgr_common::ReqType::MAX) {
-      LOGE("Request type is invalid (%d) pid(%d)", static_cast<int>(type),
-          req->GetSenderPID());
+      LOG(ERROR) << "Request type is invalid: " << static_cast<int>(type)
+          << ",  pid:" << req->GetSenderPID();
 
       pkgmgr_common::parcel::AbstractParcelable parcelable(
           0, pkgmgr_common::parcel::ParcelableType::Unknown, PMINFO_R_ERROR);
@@ -122,9 +124,10 @@ void WorkerThread::Run() {
       handler[type]->SetPID(req->GetSenderPID());
       if (!handler[type]->HandleRequest(req->GetData(), req->GetSize(),
                                         locale_.GetObject()))
-        LOGE("Failed to handle request");
+        LOG(ERROR) << "Failed to handle request";
     } catch (const std::exception& err) {
-      LOGE("Exception occurred (%s) pid(%d)", err.what(), req->GetSenderPID());
+      LOG(ERROR) << "Exception occurred: " << err.what()
+          << ", pid: " << req->GetSenderPID();
       pkgmgr_common::parcel::AbstractParcelable parcelable(
           0, pkgmgr_common::parcel::ParcelableType::Unknown, PMINFO_R_ERROR);
       tizen_base::Parcel p;
@@ -133,7 +136,7 @@ void WorkerThread::Run() {
       req->SendData(&raw[0], raw.size());
       continue;
     } catch (...) {
-      LOGE("Exception occurred pid(%d)", req->GetSenderPID());
+      LOG(ERROR) << "Exception occurred pid: " << req->GetSenderPID();
       pkgmgr_common::parcel::AbstractParcelable parcelable(
           0, pkgmgr_common::parcel::ParcelableType::Unknown, PMINFO_R_ERROR);
       tizen_base::Parcel p;
@@ -145,10 +148,10 @@ void WorkerThread::Run() {
 
     std::vector<uint8_t> result_data = handler[type]->ExtractResult();
     if (req->SendData(result_data.data(), result_data.size()) == false) {
-      LOGE("Failed to send response pid(%d)", req->GetSenderPID());
+      LOG(ERROR) << "Failed to send response pid: " << req->GetSenderPID();
       continue;
     }
-    LOGW("Success response pid(%d)", req->GetSenderPID());
+    LOG(WARNING) << "Success response pid: " <<  req->GetSenderPID();
   }
 }
 
@@ -162,7 +165,7 @@ void WorkerThread::SetMemoryTrimTimer() {
 }
 
 gboolean WorkerThread::TrimMemory(void* data) {
-  LOGD("Trim memory");
+  LOG(DEBUG) << "Trim memory";
   guint* timer = static_cast<guint*>(data);
   sqlite3_release_memory(-1);
   malloc_trim(0);
@@ -183,8 +186,8 @@ std::shared_ptr<PkgRequest> WorkerThread::PopQueue() {
 }
 
 void WorkerThread::SetLocale(std::string locale) {
-  LOGD("Change locale (%s) -> (%s)", locale_.GetObject().c_str(),
-      locale.c_str());
+  LOG(DEBUG) << "Change locale : " << locale_.GetObject()
+      << " -> "  << locale;
   locale_.SetObject(std::move(locale));
 }
 
diff --git a/src/utils/logging.cc b/src/utils/logging.cc
new file mode 100644 (file)
index 0000000..5e2a5d6
--- /dev/null
@@ -0,0 +1,24 @@
+// Copyright (c) 2021 Samsung Electronics Co., Ltd All Rights Reserved
+// Use of this source code is governed by a apache 2.0 license that can be
+// found in the LICENSE file.
+
+#include "logging.hh"
+
+namespace utils {
+
+log_priority LogLevelToPriority(LogLevel level) {
+  switch (level) {
+    case LogLevel::LOG_ERROR:
+      return log_priority::DLOG_ERROR;
+    case LogLevel::LOG_WARNING:
+      return log_priority::DLOG_WARN;
+    case LogLevel::LOG_INFO:
+      return log_priority::DLOG_INFO;
+    case LogLevel::LOG_DEBUG:
+      return log_priority::DLOG_DEBUG;
+    default:
+      return log_priority::DLOG_UNKNOWN;
+  }
+}
+
+}  // namespace utils
diff --git a/src/utils/logging.hh b/src/utils/logging.hh
new file mode 100644 (file)
index 0000000..318c2d8
--- /dev/null
@@ -0,0 +1,180 @@
+// Copyright (c) 2021 Samsung Electronics Co., Ltd All Rights Reserved
+// Use of this source code is governed by a apache 2.0 license that can be
+// found in the LICENSE file.
+
+#ifndef LOGGING_HH_
+#define LOGGING_HH_
+
+#include <dlog.h>
+
+#ifndef PROJECT_TAG
+#define PROJECT_TAG "PKGMGR_INFO"
+#endif
+
+#ifdef LOG
+#undef LOG
+#endif
+
+#include <cassert>
+#include <climits>
+#include <cstdio>
+#include <cstring>
+#include <iomanip>
+#include <iostream>
+#include <memory>
+#include <sstream>
+#include <string>
+#include <vector>
+
+#ifndef __FILENAME__
+#define __FILENAME__                                                           \
+    (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
+#endif
+
+namespace utils {
+
+enum class LogLevel {
+  LOG_ERROR,
+  LOG_WARNING,
+  LOG_INFO,
+  LOG_DEBUG,
+};
+
+log_priority LogLevelToPriority(LogLevel level);
+
+template<LogLevel> struct LogTag;
+template<> struct LogTag<LogLevel::LOG_ERROR> {
+  static constexpr const char* value = "\033[1;31m| ERROR   |\033[0m";
+};
+template<> struct LogTag<LogLevel::LOG_WARNING> {
+  static constexpr const char* value = "\033[1;33m| WARNING |\033[0m";
+};
+template<> struct LogTag<LogLevel::LOG_INFO>  {
+  static constexpr const char* value = "\033[1;32m| INFO    |\033[0m";
+};
+template<> struct LogTag<LogLevel::LOG_DEBUG> {
+  static constexpr const char* value = "\033[0m| DEBUG   |\033[0m";
+};
+
+template <class charT, class traits = std::char_traits<charT>>
+class StringStream : private std::basic_ostringstream<charT, traits> {
+ public:
+  using std::basic_ostringstream<charT, traits>::str;
+
+  template <class T>
+  StringStream&  operator<<(const T& value) {
+    static_cast<std::basic_ostringstream<charT, traits> &>(*this) << value;
+    return *this;
+  }
+};
+
+// Interface class for logging backends. The custom LogBackend which wants
+// log using LOG() macro should be implement following interface.
+class ILogBackend {
+ public:
+  virtual void WriteLog(LogLevel level, const std::string& tag,
+      const std::string& logstr) = 0;
+};
+
+class DLogBackend : public ILogBackend {
+ public:
+  void WriteLog(LogLevel level, const std::string& tag,
+      const std::string& logstr) override {
+    dlog_print(LogLevelToPriority(level), tag.c_str(), "%s",
+        Escape(logstr).c_str());
+  }
+
+ private:
+  // Since LogCatcher passes input to dlog_print(), the input which contains
+  // format string(such as %d, %n) can cause unexpected result.
+  // This is simple function to escape '%'.
+  // NOTE: Is there any gorgeous way instead of this?
+  std::string Escape(const std::string& str) const {
+    std::string escaped = std::string(str);
+    size_t start_pos = 0;
+    std::string from = "%";
+    std::string to = "%%";
+    while ((start_pos = escaped.find(from, start_pos)) != std::string::npos) {
+      escaped.replace(start_pos, from.length(), to);
+      start_pos += to.length();
+    }
+    return escaped;
+  }
+};
+
+class LogCore {
+ public:
+  // Do not call this function at destructor of global object
+  static LogCore& GetCore() {
+    static LogCore core;
+    return core;
+  }
+
+  void AddLogBackend(std::shared_ptr<ILogBackend> backend) {
+    backend_list_.emplace_back(backend);
+  }
+
+  void Log(LogLevel level, const std::string& tag, const std::string& log) {
+    for (auto& backend : backend_list_)
+      backend->WriteLog(level, tag, log);
+  }
+
+ private:
+  LogCore() {
+    // add default dlog backend
+    AddLogBackend(std::shared_ptr<ILogBackend>(new DLogBackend()));
+  }
+  ~LogCore() = default;
+  LogCore(const LogCore&) = delete;
+  LogCore& operator=(const LogCore&) = delete;
+
+  std::vector<std::shared_ptr<ILogBackend>> backend_list_;
+};
+
+class LogCatcher {
+ public:
+  LogCatcher(LogLevel level, const char* tag)
+    : level_(level), tag_(tag) { }
+
+  void operator&(const StringStream<char>& str) const {
+    LogCore::GetCore().Log(level_, tag_, str.str());
+  }
+
+ private:
+  LogLevel level_;
+  std::string tag_;
+};
+
+}  // namespace utils
+
+
+inline static const constexpr char* __tag_for_logging() {
+  return "";
+}
+
+inline static const constexpr char* __tag_for_project() {
+  return PROJECT_TAG;
+}
+
+// To be defined in class namespace if user want different log tag for given
+// scope
+#define SCOPE_LOG_TAG(TAG)                                                     \
+  inline static const constexpr char* __tag_for_logging() {                    \
+    return #TAG;                                                               \
+  }                                                                            \
+
+// Simple logging macro of following usage:
+//   LOG(LEVEL) << object_1 << object_2 << object_n;
+//     where:
+//       LEVEL = ERROR | WARNING | INFO | DEBUG
+#define LOG(LEVEL)                                                             \
+    ::utils::LogCatcher(                                                       \
+      ::utils::LogLevel::LOG_ ## LEVEL, __tag_for_project())                   \
+      & ::utils::StringStream<char>()                                          \
+      << std::string(::utils::LogTag<::utils::LogLevel::LOG_ ## LEVEL>::value) \
+      << " " << std::setw(25) << std::left << __tag_for_logging()              \
+      << " : " << std::setw(36)                                                \
+      << (std::string(__FILENAME__) + ":" + std::to_string(__LINE__)).c_str()  \
+      << std::setw(0) << " : "                                                 \
+
+#endif  // LOGGING_HH_
index 73dbb7997aae6f4660f7e7b5f6460ef3dc0c7b80..9d72c25e5d02bafd87cbd6cabd6446b14852e5d7 100644 (file)
@@ -5,11 +5,13 @@ INCLUDE_DIRECTORIES(
 
 FILE(GLOB_RECURSE UNIT_TESTS_SRCS *.cc *.c)
 FILE(GLOB_RECURSE SERVER_SRCS ${CMAKE_SOURCE_DIR}/src/server/*.cc ${CMAKE_SOURCE_DIR}/src/server/*.c)
+FILE(GLOB_RECURSE UTIL_SRCS ${CMAKE_SOURCE_DIR}/src/utils/*)
 LIST(FILTER SERVER_SRCS EXCLUDE REGEX main.cc)
 
 ADD_EXECUTABLE(${TARGET_PKGMGR_INFO_UNIT_TEST}
   ${UNIT_TESTS_SRCS}
   ${SERVER_SRCS}
+  ${UTIL_SRCS}
 )
 
 ADD_DEFINITIONS("-DSYSCONFDIR=\"${SYSCONFDIR}\"")