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.MultivaluedMap;
37 import org.apache.commons.lang3.time.StopWatch;
38 import org.junit.jupiter.api.Assertions;
39 import org.junit.jupiter.api.BeforeAll;
40 import org.junit.jupiter.api.Disabled;
41 import org.junit.jupiter.api.Test;
42 import org.mockito.Mockito;
43 import org.onap.aai.babel.logging.LogHelper.MdcParameter;
44 import org.onap.aai.babel.logging.LogHelper.TriConsumer;
45 import org.onap.aai.cl.api.LogFields;
46 import org.onap.aai.cl.api.Logger;
47 import org.onap.aai.cl.mdc.MdcOverride;
50 * Simple test to log each of the validation messages in turn.
52 * This version tests only the error logger at INFO level.
55 @Disabled("Test consistently fails in centos and is not critical")
56 public class TestApplicationLogger {
59 public static void setupClass() {
60 System.setProperty("APP_HOME", ".");
64 * Check that each message can be logged and that (by implication of successful logging) there is a corresponding
65 * resource (message format).
68 * if the log files cannot be read
71 public void logAllMessages() throws IOException {
72 Logger logger = LogHelper.INSTANCE;
73 LogHelper.INSTANCE.clearContext();
74 LogReader errorReader = new LogReader(LogHelper.getLogDirectory(), "error");
75 LogReader debugReader = new LogReader(LogHelper.getLogDirectory(), "debug");
76 String[] args = {"1", "2", "3", "4"};
77 for (ApplicationMsgs msg : Arrays.asList(ApplicationMsgs.values())) {
78 if (msg.name().endsWith("ERROR")) {
79 logger.error(msg, args);
80 validateLoggedMessage(msg, errorReader, "ERROR");
82 logger.error(msg, new RuntimeException("fred"), args);
83 validateLoggedMessage(msg, errorReader, "fred");
85 logger.info(msg, args);
86 validateLoggedMessage(msg, debugReader, "INFO");
88 logger.warn(msg, args);
89 validateLoggedMessage(msg, errorReader, "WARN");
92 logger.debug(msg, args);
93 validateLoggedMessage(msg, debugReader, "DEBUG");
98 * Check that each message can be logged and that (by implication of successful logging) there is a corresponding
99 * resource (message format).
101 * @throws IOException
102 * if the log file cannot be read
105 public void logDebugMessages() throws IOException {
106 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "debug");
107 LogHelper.INSTANCE.debug("a message");
108 String str = reader.getNewLines();
109 assertThat(str, is(notNullValue()));
113 public void logTraceMessage() throws IOException {
114 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "debug");
115 EELFManager.getInstance().getDebugLogger().setLevel(Level.TRACE);
116 LogHelper.INSTANCE.trace(ApplicationMsgs.LOAD_PROPERTIES, "a message");
117 String str = reader.getNewLines();
118 assertThat(str, is(notNullValue()));
119 EELFManager.getInstance().getAuditLogger().setLevel(Level.INFO);
120 LogHelper.INSTANCE.trace(ApplicationMsgs.LOAD_PROPERTIES, "message not written");
124 * Call logAuditError() for code coverage stats.
127 public void logAuditError() {
128 assertDoesNotThrow(() -> {
129 LogHelper.INSTANCE.logAuditError(new Exception("test"));
130 EELFManager.getInstance().getAuditLogger().setLevel(Level.OFF);
131 LogHelper.INSTANCE.logAuditError(new Exception("test"));
132 EELFManager.getInstance().getAuditLogger().setLevel(Level.INFO);
137 * Check logAudit with HTTP headers.
139 * @throws IOException
140 * if the log file cannot be read
143 public void logAuditMessage() throws IOException {
144 final LogHelper logger = LogHelper.INSTANCE;
145 final LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit");
147 MultivaluedMap<String, String> headers = Mockito.mock(MultivaluedMap.class);
148 Mockito.when(headers.getFirst("X-ECOMP-RequestID")).thenReturn("ecomp-request-id");
149 Mockito.when(headers.getFirst("X-FromAppId")).thenReturn("app-id");
151 // Call logAudit without first calling startAudit
152 logger.logAuditSuccess("first call: bob");
153 String str = reader.getNewLines();
154 assertThat(str, is(notNullValue()));
155 assertThat("audit message log level", str, containsString("INFO"));
156 assertThat("audit message content", str, containsString("bob"));
158 // This time call the start method
159 logger.startAudit(headers, null);
160 logger.logAuditSuccess("second call: foo");
161 str = reader.getNewLines();
162 assertThat(str, is(notNullValue()));
163 assertThat("audit message log level", str, containsString("INFO"));
164 assertThat("audit message content", str, containsString("foo"));
165 assertThat("audit message content", str, containsString("ecomp-request-id"));
166 assertThat("audit message content", str, containsString("app-id"));
170 * Check logAudit with no HTTP headers.
172 * @throws IOException
173 * if the log file cannot be read
176 public void logAuditMessageWithoutHeaders() throws IOException {
177 LogHelper logger = LogHelper.INSTANCE;
178 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit");
179 logger.startAudit(null, null);
180 logger.logAuditSuccess("foo");
181 String str = reader.getNewLines();
182 assertThat(str, is(notNullValue()));
183 assertThat("audit message log level", str, containsString("INFO"));
184 assertThat("audit message content", str, containsString("foo"));
188 * Check logAudit with mocked Servlet request.
190 * @throws IOException
191 * if the log file cannot be read
194 public void logAuditMessageWithServletRequest() throws IOException {
195 ServletRequest servletRequest = Mockito.mock(ServletRequest.class);
196 LogHelper logger = LogHelper.INSTANCE;
197 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit");
198 logger.startAudit(null, servletRequest);
199 logger.logAuditSuccess("foo");
200 String str = reader.getNewLines();
201 assertThat(str, is(notNullValue()));
202 assertThat("audit message log level", str, containsString("INFO"));
203 assertThat("audit message content", str, containsString("foo"));
207 public void setDefaultContextValue() {
208 assertDoesNotThrow(() -> {
209 LogHelper logger = LogHelper.INSTANCE;
210 logger.setDefaultContextValue("key", "value");
211 logger.setDefaultContextValue(MdcParameter.USER, null);
218 * @throws IOException
219 * if the log file cannot be read
222 public void logMetricsMessage() throws IOException {
223 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "metrics");
224 LogHelper logger = LogHelper.INSTANCE;
225 logger.logMetrics("metrics: fred");
226 String str = reader.getNewLines();
227 assertThat(str, is(notNullValue()));
228 assertThat("metrics message log level", str, containsString("INFO"));
229 assertThat("metrics message content", str, containsString("fred"));
233 public void logMetricsMessageWithStopwatch() throws IOException {
234 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "metrics");
235 LogHelper logger = LogHelper.INSTANCE;
236 StopWatch stopWatch = new StopWatch();
238 logger.logMetrics(stopWatch, "joe", "bloggs");
239 String logLine = reader.getNewLines();
240 assertThat(logLine, is(notNullValue()));
241 assertThat("metrics message log level", logLine, containsString("INFO"));
242 assertThat("metrics message content", logLine, containsString("joe"));
246 public void callUnsupportedMethods() throws IOException {
247 LogHelper logger = LogHelper.INSTANCE;
248 ApplicationMsgs dummyMsg = ApplicationMsgs.LOAD_PROPERTIES;
249 callUnsupportedOperationMethod(logger::error, dummyMsg);
250 callUnsupportedOperationMethod(logger::info, dummyMsg);
251 callUnsupportedOperationMethod(logger::warn, dummyMsg);
252 callUnsupportedOperationMethod(logger::debug, dummyMsg);
253 callUnsupportedOperationMethod(logger::trace, dummyMsg);
255 logger.error(dummyMsg, new LogFields(), new RuntimeException("test"), "");
256 } catch (UnsupportedOperationException e) {
257 // Expected to reach here
260 logger.info(dummyMsg, new LogFields(), new MdcOverride(), "");
261 } catch (UnsupportedOperationException e) {
262 // Expected to reach here
265 logger.formatMsg(dummyMsg, "");
266 } catch (UnsupportedOperationException e) {
267 // Expected to reach here
272 * Call a logger method which is expected to throw an UnsupportedOperationException.
275 * the logger method to invoke
277 * any Application Message enumeration value
279 private void callUnsupportedOperationMethod(TriConsumer<Enum<?>, LogFields, String[]> logMethod,
280 ApplicationMsgs dummyMsg) {
281 logMethod.accept(dummyMsg, new LogFields(), new String[] {""});
282 Assertions.fail("method should have thrown execption"); // NOSONAR as code not reached
286 * Assert that a log message was logged to the expected log file at the expected severity.
289 * the Application Message enumeration value
291 * the log reader for the message
294 * @throws IOException
295 * if the log file cannot be read
297 private void validateLoggedMessage(ApplicationMsgs msg, LogReader reader, String severity) throws IOException {
298 String str = reader.getNewLines();
299 assertThat(str, is(notNullValue()));
300 // assertThat(msg.toString() + " log level", str, containsString("BABEL"));