Logging.cpp 5.3 KB
Newer Older
Z
zhangjinchao01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
/* Copyright (c) 2016 Baidu, Inc. All Rights Reserve.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

/*
 * Basically from tensorflow/core/platform/default/logging.cc
 * Used in embedded system where there is no glogs.
 */

#include "Logging.h"
#ifndef PADDLE_USE_GLOG
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <thread>
#include <mutex>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

namespace paddle {

namespace internal {

std::string join(const std::string& part1, const std::string& part2) {
  const char sep = '/';
  if (!part2.empty() && part2.front() == sep) {
    return part2;
  }
  std::string ret;
  ret.reserve(part1.size() + part2.size() + 1);
  ret = part1;
  if (!ret.empty() && ret.back() != sep) {
    ret += sep;
  }
  ret += part2;
  return ret;
}

static inline bool env2bool(const char* envName, bool defaultValue = false) {
  char* envValue = getenv(envName);
  if (envValue == nullptr) {
    return defaultValue;
  } else {
    return memchr("tTyY1\0", envValue[0], 6) != nullptr;
  }
}

static inline int env2int(const char* envName, int defaultValue = 0) {
  char* envValue = getenv(envName);
  if (envValue == nullptr) {
    return defaultValue;
  } else {
    int retValue = defaultValue;
    try {
      retValue = std::stoi(envValue);
    } catch (...) {
      // pass
    }
    return retValue;
  }
}

static inline int env2index(const char* envName,
                            const std::vector<std::string>& options,
                            int defaultValue) {
  char* envValue = getenv(envName);
  if (envValue == nullptr) {
    return defaultValue;
  } else {
    for (size_t i = 0; i < options.size(); ++i) {
      if (options[i] == envValue) {
        return static_cast<int>(i);
      }
    }
    return defaultValue;
  }
}

static bool gLogToStderr = env2bool("PLOG_LOGTOSTDERR", true);
static const std::vector<std::string> gLevelName = {"INFO", "WARNING", "ERROR",
                                                    "FATAL"};
static int gMinLogLevel =
    env2int("PLOG_MINLOGLEVEL", env2index("PLOG_MINLOGLEVEL", gLevelName, 0));

static std::vector<std::vector<int>> gLogFds;
static std::vector<int> gLogFileFds;
static bool gLogInited = false;
static void freeLogFileFds() {
  for (auto fd : gLogFileFds) {
    close(fd);
  }
}

static void initializeLogFds(char* argv0) {
  gLogFds.resize(NUM_SEVERITIES);

  for (int i = gMinLogLevel; i < NUM_SEVERITIES && gLogToStderr;
       ++i) {  // Add stderr
    std::vector<int>& fds = gLogFds[i];
    fds.push_back(STDERR_FILENO);
  }

  char* logDir = getenv("PLOG_LOGDIR");

  for (int i = gMinLogLevel; i < NUM_SEVERITIES && logDir != nullptr; ++i) {
    std::string filename =
        join(logDir, std::string(argv0) + "." + gLevelName[i]);
    int fd = open(filename.c_str(), O_CREAT | O_WRONLY, 0644);
    if (fd == -1) {
      fprintf(stderr, "Open log file error!");
      exit(1);
    }
    gLogFileFds.push_back(fd);

    std::vector<int>& curFds = gLogFds[i];
    curFds.insert(curFds.end(), gLogFileFds.begin(), gLogFileFds.end());
  }

  atexit(freeLogFileFds);
  gLogInited = true;
}

Y
Yu Yang 已提交
137
static void (*gFailureFunctionPtr)() ATTR_NORETURN = abort;
Z
zhangjinchao01 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173

LogMessage::LogMessage(const char* fname, int line, int severity)
    : fname_(fname), line_(line), severity_(severity) {}

LogMessage::~LogMessage() { this->generateLogMessage(); }

void LogMessage::generateLogMessage() {
  if (!gLogInited) {
    fprintf(stderr, "%c %s:%d] %s\n", "IWEF"[severity_], fname_, line_,
            str().c_str());
  } else {
    for (auto& fd : gLogFds[this->severity_]) {
      dprintf(fd, "%c %s:%d] %s\n", "IWEF"[severity_], fname_, line_,
              str().c_str());
    }
  }
}

LogMessageFatal::LogMessageFatal(const char* file, int line)
    : LogMessage(file, line, FATAL) {}

LogMessageFatal::~LogMessageFatal() {
  generateLogMessage();
  gFailureFunctionPtr();
}
}  // namespace internal

void initializeLogging(int argc, char** argv) {
  internal::initializeLogFds(argv[0]);
}

namespace logging {
void setMinLogLevel(int level) {
  paddle::internal::gMinLogLevel = level;
}

Y
Yu Yang 已提交
174
void installFailureFunction(void (*callback)() ATTR_NORETURN) {
Z
zhangjinchao01 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
  paddle::internal::gFailureFunctionPtr = callback;
}

}  // namespace logging

}  // namespace paddle

#else
namespace paddle {
void initializeLogging(int argc, char** argv) {
  (void)(argc);
  if (!getenv("GLOG_logtostderr")) {
    google::LogToStderr();
  }
  google::InstallFailureSignalHandler();
  google::InitGoogleLogging(argv[0]);
}

namespace logging {
void setMinLogLevel(int level) {
  FLAGS_minloglevel = level;
}
void installFailureFunction(void (*callback)()) {
  google::InstallFailureFunction(callback);
}
void installFailureWriter(void(*callback)(const char*, int)) {
  google::InstallFailureWriter(callback);
}
}  // namespace logging
}  // namespace paddle
#endif