1 /*
2  * Copyright (c) 2019, 2020, 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 "FileUtils.h"
28 
29 
30 namespace {
31     //
32     // IMPORTANT: Static objects with non-trivial constructors are NOT allowed
33     // in logger module. Allocate buffers only and do lazy initialization of
34     // globals in Logger::getDefault().
35     //
36     // Logging subsystem is used almost in every module, and logging API can be
37     // called from constructors of static objects in various modules. As
38     // ordering of static objects initialization between modules is undefined,
39     // this means some module may call logging api before logging static
40     // variables are initialized if any. This will result in AV. To avoid such
41     // use cases keep logging module free from static variables that require
42     // initialization with functions called by CRT.
43     //
44 
45     // by default log everything
46     const Logger::LogLevel defaultLogLevel = Logger::LOG_TRACE;
47 
48     char defaultLogAppenderMemory[sizeof(StreamLogAppender)] = {};
49 
50     char defaultLoggerMemory[sizeof(Logger)] = {};
51 
getLogLevelStr(Logger::LogLevel level)52     LPCTSTR getLogLevelStr(Logger::LogLevel level) {
53         switch (level) {
54         case Logger::LOG_TRACE:
55             return _T("TRACE");
56         case Logger::LOG_INFO:
57             return _T("INFO");
58         case Logger::LOG_WARNING:
59             return _T("WARNING");
60         case Logger::LOG_ERROR:
61             return _T("ERROR");
62         }
63         return _T("UNKNOWN");
64     }
65 
66     enum State { NotInitialized, Initializing, Initialized };
67     State state = NotInitialized;
68 }
69 
70 
LogEvent()71 LogEvent::LogEvent() {
72     logLevel = tstring();
73     fileName = tstring();
74     funcName = tstring();
75     message = tstring();
76 }
77 
78 
79 /*static*/
defaultLogger()80 Logger& Logger::defaultLogger() {
81     Logger* reply = reinterpret_cast<Logger*>(defaultLoggerMemory);
82 
83     if (!reply->appender) {
84         // Memory leak by design. Not an issue at all as this is global
85         // object. OS will do resources clean up anyways when application
86         // terminates and the default log appender should live as long as
87         // application lives.
88         reply->appender = new (defaultLogAppenderMemory) StreamLogAppender(
89                                                                     std::cout);
90     }
91 
92     if (Initializing == state) {
93         // Recursive call to Logger::defaultLogger.
94         initializingLogging();
95 
96     } else if (NotInitialized == state) {
97         state = Initializing;
98         initializeLogging();
99         state = Initialized;
100     }
101 
102     return *reply;
103 }
104 
Logger(LogAppender & appender,LogLevel logLevel)105 Logger::Logger(LogAppender& appender, LogLevel logLevel)
106         : level(logLevel), appender(&appender) {
107 }
108 
setLogLevel(LogLevel logLevel)109 void Logger::setLogLevel(LogLevel logLevel) {
110     level = logLevel;
111 }
112 
~Logger()113 Logger::~Logger() {
114 }
115 
116 
isLoggable(LogLevel logLevel) const117 bool Logger::isLoggable(LogLevel logLevel) const {
118     return logLevel >= level;
119 }
120 
log(LogLevel logLevel,LPCTSTR fileName,int lineNum,LPCTSTR funcName,const tstring & message) const121 void Logger::log(LogLevel logLevel, LPCTSTR fileName, int lineNum,
122         LPCTSTR funcName, const tstring& message) const {
123     LogEvent logEvent;
124     LogEvent::init(logEvent);
125 
126     logEvent.fileName = FileUtils::basename(fileName);
127     logEvent.funcName = funcName;
128     logEvent.logLevel = getLogLevelStr(logLevel);
129     logEvent.lineNum = lineNum;
130     logEvent.message = message;
131 
132     appender->append(logEvent);
133 }
134 
135 
append(const LogEvent & v)136 void StreamLogAppender::append(const LogEvent& v) {
137     tstring platformLogStr;
138     LogEvent::appendFormatted(v, platformLogStr);
139 
140     tostringstream printer;
141     printer << _T('[') << platformLogStr
142                 << v.fileName << _T(':') << v.lineNum
143                 << _T(" (") << v.funcName << _T(')')
144             << _T(']')
145             << _T('\n') << _T('\t')
146             << v.logLevel << _T(": ")
147             << v.message;
148 
149     *consumer << tstrings::toUtf8(printer.str()) << std::endl;
150 }
151 
152 
153 // Logger::ScopeTracer
ScopeTracer(Logger & logger,LogLevel logLevel,LPCTSTR fileName,int lineNum,LPCTSTR funcName,const tstring & scopeName)154 Logger::ScopeTracer::ScopeTracer(Logger &logger, LogLevel logLevel,
155         LPCTSTR fileName, int lineNum, LPCTSTR funcName,
156         const tstring& scopeName) : log(logger), level(logLevel),
157         file(fileName), line(lineNum),
158         func(funcName), scope(scopeName), needLog(logger.isLoggable(logLevel)) {
159     if (needLog) {
160         log.log(level, file.c_str(), line, func.c_str(),
161                 tstrings::any() << "Entering " << scope);
162     }
163 }
164 
~ScopeTracer()165 Logger::ScopeTracer::~ScopeTracer() {
166     if (needLog) {
167         // we don't know what line is end of scope at, so specify line 0
168         // and add note about line when the scope begins
169         log.log(level, file.c_str(), 0, func.c_str(),
170                 tstrings::any() << "Exiting " << scope << " (entered at "
171                 << FileUtils::basename(file) << ":" << line << ")");
172     }
173 }
174