2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (c) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Copyright (c) 2017-2019 European Software Marketing Ltd.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.aai.babel.logging;
24 import static org.hamcrest.CoreMatchers.containsString;
25 import static org.hamcrest.CoreMatchers.is;
26 import static org.hamcrest.CoreMatchers.notNullValue;
27 import static org.hamcrest.MatcherAssert.assertThat;
28 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
30 import com.att.eelf.configuration.EELFLogger.Level;
31 import com.att.eelf.configuration.EELFManager;
32 import java.io.IOException;
33 import java.util.Arrays;
34 import javax.servlet.ServletRequest;
35 import javax.ws.rs.core.HttpHeaders;
36 import org.apache.commons.lang3.time.StopWatch;
37 import org.junit.jupiter.api.Assertions;
38 import org.junit.jupiter.api.BeforeAll;
39 import org.junit.jupiter.api.Disabled;
40 import org.junit.jupiter.api.Test;
41 import org.mockito.Mockito;
42 import org.onap.aai.babel.logging.LogHelper.MdcParameter;
43 import org.onap.aai.babel.logging.LogHelper.TriConsumer;
44 import org.onap.aai.cl.api.LogFields;
45 import org.onap.aai.cl.api.Logger;
46 import org.onap.aai.cl.mdc.MdcOverride;
49 * Simple test to log each of the validation messages in turn.
51 * This version tests only the error logger at INFO level.
54 @Disabled("Test consistently fails in centos and is not critical")
55 public class TestApplicationLogger {
58 public static void setupClass() {
59 System.setProperty("APP_HOME", ".");
63 * Check that each message can be logged and that (by implication of successful logging) there is a corresponding
64 * resource (message format).
67 * if the log files cannot be read
70 public void logAllMessages() throws IOException {
71 Logger logger = LogHelper.INSTANCE;
72 LogHelper.INSTANCE.clearContext();
73 LogReader errorReader = new LogReader(LogHelper.getLogDirectory(), "error");
74 LogReader debugReader = new LogReader(LogHelper.getLogDirectory(), "debug");
75 String[] args = {"1", "2", "3", "4"};
76 for (ApplicationMsgs msg : Arrays.asList(ApplicationMsgs.values())) {
77 if (msg.name().endsWith("ERROR")) {
78 logger.error(msg, args);
79 validateLoggedMessage(msg, errorReader, "ERROR");
81 logger.error(msg, new RuntimeException("fred"), args);
82 validateLoggedMessage(msg, errorReader, "fred");
84 logger.info(msg, args);
85 validateLoggedMessage(msg, debugReader, "INFO");
87 logger.warn(msg, args);
88 validateLoggedMessage(msg, errorReader, "WARN");
91 logger.debug(msg, args);
92 validateLoggedMessage(msg, debugReader, "DEBUG");
97 * Check that each message can be logged and that (by implication of successful logging) there is a corresponding
98 * resource (message format).
100 * @throws IOException
101 * if the log file cannot be read
104 public void logDebugMessages() throws IOException {
105 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "debug");
106 LogHelper.INSTANCE.debug("a message");
107 String str = reader.getNewLines();
108 assertThat(str, is(notNullValue()));
112 public void logTraceMessage() throws IOException {
113 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "debug");
114 EELFManager.getInstance().getDebugLogger().setLevel(Level.TRACE);
115 LogHelper.INSTANCE.trace(ApplicationMsgs.LOAD_PROPERTIES, "a message");
116 String str = reader.getNewLines();
117 assertThat(str, is(notNullValue()));
118 EELFManager.getInstance().getAuditLogger().setLevel(Level.INFO);
119 LogHelper.INSTANCE.trace(ApplicationMsgs.LOAD_PROPERTIES, "message not written");
123 * Call logAuditError() for code coverage stats.
126 public void logAuditError() {
127 assertDoesNotThrow(() -> {
128 LogHelper.INSTANCE.logAuditError(new Exception("test"));
129 EELFManager.getInstance().getAuditLogger().setLevel(Level.OFF);
130 LogHelper.INSTANCE.logAuditError(new Exception("test"));
131 EELFManager.getInstance().getAuditLogger().setLevel(Level.INFO);
136 * Check logAudit with HTTP headers.
138 * @throws IOException
139 * if the log file cannot be read
142 public void logAuditMessage() throws IOException {
143 final LogHelper logger = LogHelper.INSTANCE;
144 final LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit");
146 HttpHeaders headers = Mockito.mock(HttpHeaders.class);
147 Mockito.when(headers.getHeaderString("X-ECOMP-RequestID")).thenReturn("ecomp-request-id");
148 Mockito.when(headers.getHeaderString("X-FromAppId")).thenReturn("app-id");
150 // Call logAudit without first calling startAudit
151 logger.logAuditSuccess("first call: bob");
152 String str = reader.getNewLines();
153 assertThat(str, is(notNullValue()));
154 assertThat("audit message log level", str, containsString("INFO"));
155 assertThat("audit message content", str, containsString("bob"));
157 // This time call the start method
158 logger.startAudit(headers, null);
159 logger.logAuditSuccess("second call: foo");
160 str = reader.getNewLines();
161 assertThat(str, is(notNullValue()));
162 assertThat("audit message log level", str, containsString("INFO"));
163 assertThat("audit message content", str, containsString("foo"));
164 assertThat("audit message content", str, containsString("ecomp-request-id"));
165 assertThat("audit message content", str, containsString("app-id"));
169 * Check logAudit with no HTTP headers.
171 * @throws IOException
172 * if the log file cannot be read
175 public void logAuditMessageWithoutHeaders() throws IOException {
176 LogHelper logger = LogHelper.INSTANCE;
177 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit");
178 logger.startAudit(null, null);
179 logger.logAuditSuccess("foo");
180 String str = reader.getNewLines();
181 assertThat(str, is(notNullValue()));
182 assertThat("audit message log level", str, containsString("INFO"));
183 assertThat("audit message content", str, containsString("foo"));
187 * Check logAudit with mocked Servlet request.
189 * @throws IOException
190 * if the log file cannot be read
193 public void logAuditMessageWithServletRequest() throws IOException {
194 ServletRequest servletRequest = Mockito.mock(ServletRequest.class);
195 LogHelper logger = LogHelper.INSTANCE;
196 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit");
197 logger.startAudit(null, servletRequest);
198 logger.logAuditSuccess("foo");
199 String str = reader.getNewLines();
200 assertThat(str, is(notNullValue()));
201 assertThat("audit message log level", str, containsString("INFO"));
202 assertThat("audit message content", str, containsString("foo"));
206 public void setDefaultContextValue() {
207 assertDoesNotThrow(() -> {
208 LogHelper logger = LogHelper.INSTANCE;
209 logger.setDefaultContextValue("key", "value");
210 logger.setDefaultContextValue(MdcParameter.USER, null);
217 * @throws IOException
218 * if the log file cannot be read
221 public void logMetricsMessage() throws IOException {
222 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "metrics");
223 LogHelper logger = LogHelper.INSTANCE;
224 logger.logMetrics("metrics: fred");
225 String str = reader.getNewLines();
226 assertThat(str, is(notNullValue()));
227 assertThat("metrics message log level", str, containsString("INFO"));
228 assertThat("metrics message content", str, containsString("fred"));
232 public void logMetricsMessageWithStopwatch() throws IOException {
233 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "metrics");
234 LogHelper logger = LogHelper.INSTANCE;
235 StopWatch stopWatch = new StopWatch();
237 logger.logMetrics(stopWatch, "joe", "bloggs");
238 String logLine = reader.getNewLines();
239 assertThat(logLine, is(notNullValue()));
240 assertThat("metrics message log level", logLine, containsString("INFO"));
241 assertThat("metrics message content", logLine, containsString("joe"));
245 public void callUnsupportedMethods() throws IOException {
246 LogHelper logger = LogHelper.INSTANCE;
247 ApplicationMsgs dummyMsg = ApplicationMsgs.LOAD_PROPERTIES;
248 callUnsupportedOperationMethod(logger::error, dummyMsg);
249 callUnsupportedOperationMethod(logger::info, dummyMsg);
250 callUnsupportedOperationMethod(logger::warn, dummyMsg);
251 callUnsupportedOperationMethod(logger::debug, dummyMsg);
252 callUnsupportedOperationMethod(logger::trace, dummyMsg);
254 logger.error(dummyMsg, new LogFields(), new RuntimeException("test"), "");
255 } catch (UnsupportedOperationException e) {
256 // Expected to reach here
259 logger.info(dummyMsg, new LogFields(), new MdcOverride(), "");
260 } catch (UnsupportedOperationException e) {
261 // Expected to reach here
264 logger.formatMsg(dummyMsg, "");
265 } catch (UnsupportedOperationException e) {
266 // Expected to reach here
271 * Call a logger method which is expected to throw an UnsupportedOperationException.
274 * the logger method to invoke
276 * any Application Message enumeration value
278 private void callUnsupportedOperationMethod(TriConsumer<Enum<?>, LogFields, String[]> logMethod,
279 ApplicationMsgs dummyMsg) {
280 logMethod.accept(dummyMsg, new LogFields(), new String[] {""});
281 Assertions.fail("method should have thrown execption"); // NOSONAR as code not reached
285 * Assert that a log message was logged to the expected log file at the expected severity.
288 * the Application Message enumeration value
290 * the log reader for the message
293 * @throws IOException
294 * if the log file cannot be read
296 private void validateLoggedMessage(ApplicationMsgs msg, LogReader reader, String severity) throws IOException {
297 String str = reader.getNewLines();
298 assertThat(str, is(notNullValue()));
299 // assertThat(msg.toString() + " log level", str, containsString("BABEL"));