1 /*
   2  * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 #include "Log.h"
  27 #include "SysInfo.h"
  28 #include "FileUtils.h"
  29 
  30 
  31 namespace {
  32     //
  33     // IMPORTANT: Static objects with non-trivial constructors are NOT allowed
  34     // in logger module. Allocate buffers only and do lazy initialization of
  35     // globals in Logger::getDefault().
  36     //
  37     // Logging subsystem is used almost in every module, and logging API can be
  38     // called from constructors of static objects in various modules. As
  39     // ordering of static objects initialization between modules is undefined,
  40     // this means some module may call logging api before logging static
  41     // variables are initialized if any. This will result in AV. To avoid such
  42     // use cases keep logging module free from static variables that require
  43     // initialization with functions called by CRT.
  44     //
  45 
  46     // by default log everything
  47     const Logger::LogLevel defaultLogLevel = Logger::LOG_TRACE;
  48 
  49     char defaultLogAppenderMemory[sizeof(StderrLogAppender)] = {};
  50 
  51     char defaultLoggerMemory[sizeof(Logger)] = {};
  52 
  53     NopLogAppender nopLogApender;
  54 
  55     LPCTSTR getLogLevelStr(Logger::LogLevel level) {
  56         switch (level) {
  57         case Logger::LOG_TRACE:
  58             return _T("TRACE");
  59         case Logger::LOG_INFO:
  60             return _T("INFO");
  61         case Logger::LOG_WARNING:
  62             return _T("WARNING");
  63         case Logger::LOG_ERROR:
  64             return _T("ERROR");
  65         }
  66         return _T("UNKNOWN");
  67     }
  68 
  69     tstring retrieveModuleName() {
  70         try {
  71             return FileUtils::basename(SysInfo::getCurrentModulePath());
  72         } catch (const std::exception&) {
  73             return _T("Unknown");
  74         }
  75     }
  76 
  77     TCHAR moduleName[MAX_PATH] = { 'U', 'n', 'k', 'o', 'w', 'n', TCHAR(0) };
  78 
  79     const LPCTSTR format = _T("[%04u/%02u/%02u %02u:%02u:%02u.%03u, %s (PID: %u, TID: %u), %s:%u (%s)]\n\t%s: %s\n");
  80 
  81     enum State { NotInitialized, Initializing, Initialized };
  82     State state = NotInitialized;
  83 }
  84 
  85 
  86 LogEvent::LogEvent() {
  87     memset(this, 0, sizeof(*this));
  88     moduleName = tstring();
  89     logLevel = tstring();
  90     fileName = tstring();
  91     funcName = tstring();
  92     message = tstring();
  93 }
  94 
  95 
  96 StderrLogAppender::StderrLogAppender() {
  97 }
  98 
  99 
 100 /*static*/
 101 Logger& Logger::defaultLogger() {
 102     Logger* reply = reinterpret_cast<Logger*>(defaultLoggerMemory);
 103 
 104     if (!reply->appender) {
 105         // Memory leak by design. Not an issue at all as this is global
 106         // object. OS will do resources clean up anyways when application
 107         // terminates and the default log appender should live as long as
 108         // application lives.
 109         reply->appender = new (defaultLogAppenderMemory) StderrLogAppender();
 110     }
 111 
 112     if (Initializing == state) {
 113         // Recursive call to Logger::defaultLogger.
 114         moduleName[0] = TCHAR(0);
 115     } else if (NotInitialized == state) {
 116         state = Initializing;
 117 
 118         tstring mname = retrieveModuleName();
 119         mname.resize(_countof(moduleName) - 1);
 120         std::memcpy(moduleName, mname.c_str(), mname.size());
 121         moduleName[mname.size()] = TCHAR(0);
 122 
 123         // if JPACKAGE_DEBUG environment variable is NOT set to "true" disable
 124         // logging.
 125         if (SysInfo::getEnvVariable(std::nothrow,
 126                 L"JPACKAGE_DEBUG") != L"true") {
 127             reply->appender = &nopLogApender;
 128         }
 129 
 130         state = Initialized;
 131     }
 132 
 133     return *reply;
 134 }
 135 
 136 Logger::Logger(LogAppender& appender, LogLevel logLevel)
 137         : level(logLevel), appender(&appender) {
 138 }
 139 
 140 void Logger::setLogLevel(LogLevel logLevel) {
 141     level = logLevel;
 142 }
 143 
 144 Logger::~Logger() {
 145 }
 146 
 147 
 148 bool Logger::isLoggable(LogLevel logLevel) const {
 149     return logLevel >= level;
 150 }
 151 
 152 void Logger::log(LogLevel logLevel, LPCTSTR fileName, int lineNum,
 153         LPCTSTR funcName, const tstring& message) const {
 154     LogEvent logEvent;
 155 
 156     // [YYYY/MM/DD HH:MM:SS.ms, <module> (PID: processID, TID: threadID),
 157     // fileName:lineNum (funcName)] <tab>LEVEL: message
 158     GetLocalTime(&logEvent.ts);
 159 
 160     logEvent.pid = GetCurrentProcessId();
 161     logEvent.tid = GetCurrentThreadId();
 162     logEvent.moduleName = moduleName;
 163     logEvent.fileName = FileUtils::basename(fileName);
 164     logEvent.funcName = funcName;
 165     logEvent.logLevel = getLogLevelStr(logLevel);
 166     logEvent.lineNum = lineNum;
 167     logEvent.message = message;
 168 
 169     appender->append(logEvent);
 170 }
 171 
 172 
 173 void StderrLogAppender::append(const LogEvent& v)
 174 {
 175     const tstring out = tstrings::unsafe_format(format,
 176         unsigned(v.ts.wYear), unsigned(v.ts.wMonth), unsigned(v.ts.wDay),
 177         unsigned(v.ts.wHour), unsigned(v.ts.wMinute), unsigned(v.ts.wSecond),
 178                 unsigned(v.ts.wMilliseconds),
 179         v.moduleName.c_str(), v.pid, v.tid,
 180         v.fileName.c_str(), v.lineNum, v.funcName.c_str(),
 181         v.logLevel.c_str(),
 182         v.message.c_str());
 183 
 184     std::cerr << tstrings::toUtf8(out);
 185 }
 186 
 187 
 188 // Logger::ScopeTracer
 189 Logger::ScopeTracer::ScopeTracer(Logger &logger, LogLevel logLevel,
 190         LPCTSTR fileName, int lineNum, LPCTSTR funcName,
 191         const tstring& scopeName) : log(logger), level(logLevel),
 192         file(fileName), line(lineNum),
 193         func(funcName), scope(scopeName), needLog(logger.isLoggable(logLevel)) {
 194     if (needLog) {
 195         log.log(level, file.c_str(), line, func.c_str(),
 196                 tstrings::any() << "Entering " << scope);
 197     }
 198 }
 199 
 200 Logger::ScopeTracer::~ScopeTracer() {
 201     if (needLog) {
 202         // we don't know what line is end of scope at, so specify line 0
 203         // and add note about line when the scope begins
 204         log.log(level, file.c_str(), 0, func.c_str(),
 205                 tstrings::any() << "Exiting " << scope << " (entered at "
 206                 << FileUtils::basename(file) << ":" << line << ")");
 207     }
 208 }