Logging.cpp 5.3 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

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 <mutex>
Y
Yu Yang 已提交
26 27
#include <thread>
#include <vector>
Z
zhangjinchao01 已提交
28 29

#include <fcntl.h>
Y
Yu Yang 已提交
30 31
#include <sys/stat.h>
#include <sys/types.h>
Z
zhangjinchao01 已提交
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
#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);
94 95
static const std::vector<std::string> gLevelName = {
    "INFO", "WARNING", "ERROR", "FATAL"};
Z
zhangjinchao01 已提交
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
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

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

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

void LogMessage::generateLogMessage() {
  if (!gLogInited) {
146 147 148 149 150
    fprintf(stderr,
            "%c %s:%d] %s\n",
            "IWEF"[severity_],
            fname_,
            line_,
Z
zhangjinchao01 已提交
151 152 153
            str().c_str());
  } else {
    for (auto& fd : gLogFds[this->severity_]) {
154 155 156 157 158
      dprintf(fd,
              "%c %s:%d] %s\n",
              "IWEF"[severity_],
              fname_,
              line_,
Z
zhangjinchao01 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
              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 {
178
void setMinLogLevel(int level) { paddle::internal::gMinLogLevel = level; }
Z
zhangjinchao01 已提交
179

Y
Yu Yang 已提交
180
void installFailureFunction(void (*callback)() ATTR_NORETURN) {
Z
zhangjinchao01 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
  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 {
200
void setMinLogLevel(int level) { FLAGS_minloglevel = level; }
Z
zhangjinchao01 已提交
201 202 203
void installFailureFunction(void (*callback)()) {
  google::InstallFailureFunction(callback);
}
204
void installFailureWriter(void (*callback)(const char*, int)) {
Z
zhangjinchao01 已提交
205 206 207 208 209
  google::InstallFailureWriter(callback);
}
}  // namespace logging
}  // namespace paddle
#endif