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 {
 103     Logger* reply = reinterpret_cast<Logger*>(defaultLoggerMemory);
 104 
 105     if (!reply->appender) {
 106         // Memory leak by design. Not an issue at all as this is global
 107         // object. OS will do resources clean up anyways when application
 108         // terminates and the default log appender should live as long as
 109         // application lives.
 110         reply->appender = new (defaultLogAppenderMemory) StderrLogAppender();
 111     }
 112 
 113     if (Initializing == state) {
 114         // Recursive call to Logger::defaultLogger.
 115         moduleName[0] = TCHAR(0);
 116     } else if (NotInitialized == state) {
 117         state = Initializing;
 118 
 119         tstring mname = retrieveModuleName();
 120         mname.resize(_countof(moduleName) - 1);
 121         std::memcpy(moduleName, mname.c_str(), mname.size());
 122         moduleName[mname.size()] = TCHAR(0);
 123 
 124         // if JPACKAGE_DEBUG environment variable is NOT set to "true" disable 
 125         // logging.
 126         if (SysInfo::getEnvVariable(std::nothrow, 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 
 141 void Logger::setLogLevel(LogLevel logLevel)
 142 {
 143     level = logLevel;
 144 }
 145 
 146 Logger::~Logger()
 147 {
 148 }
 149 
 150 
 151 bool Logger::isLoggable(LogLevel logLevel) const
 152 {
 153     return logLevel >= level;
 154 }
 155 
 156 void Logger::log(LogLevel logLevel, LPCTSTR fileName, int lineNum, LPCTSTR funcName, const tstring& message) const
 157 {
 158     LogEvent logEvent;
 159 
 160     // [YYYY/MM/DD HH:MM:SS.ms, <module> (PID: processID, TID: threadID), fileName:lineNum (funcName)]
 161     // <tab>LEVEL: message
 162     GetLocalTime(&logEvent.ts);
 163 
 164     logEvent.pid = GetCurrentProcessId();
 165     logEvent.tid = GetCurrentThreadId();
 166     logEvent.moduleName = moduleName;
 167     logEvent.fileName = FileUtils::basename(fileName);
 168     logEvent.funcName = funcName;
 169     logEvent.logLevel = getLogLevelStr(logLevel);
 170     logEvent.lineNum = lineNum;
 171     logEvent.message = message;
 172 
 173     appender->append(logEvent);
 174 }
 175 
 176 
 177 void StderrLogAppender::append(const LogEvent& v)
 178 {
 179     const tstring out = tstrings::unsafe_format(format,
 180         unsigned(v.ts.wYear), unsigned(v.ts.wMonth), unsigned(v.ts.wDay),                       // date
 181         unsigned(v.ts.wHour), unsigned(v.ts.wMinute), unsigned(v.ts.wSecond), unsigned(v.ts.wMilliseconds), // time
 182         v.moduleName.c_str(), v.pid, v.tid,
 183         v.fileName.c_str(), v.lineNum, v.funcName.c_str(),
 184         v.logLevel.c_str(),
 185         v.message.c_str());
 186 
 187     std::cerr << tstrings::toUtf8(out);
 188 }
 189 
 190 
 191 // Logger::ScopeTracer
 192 Logger::ScopeTracer::ScopeTracer(Logger &logger, LogLevel logLevel, LPCTSTR fileName, int lineNum, LPCTSTR funcName, const tstring& scopeName)
 193     : log(logger), level(logLevel), file(fileName), line(lineNum), func(funcName), scope(scopeName), needLog(logger.isLoggable(logLevel))
 194 {
 195     if (needLog) {
 196         log.log(level, file.c_str(), line, func.c_str(), 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 " << FileUtils::basename(file) << ":" << line << ")");
 206     }
 207 }