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;
29 import com.att.eelf.configuration.EELFLogger.Level;
30 import com.att.eelf.configuration.EELFManager;
31 import java.io.IOException;
32 import java.util.Arrays;
33 import javax.servlet.ServletRequest;
34 import javax.ws.rs.core.HttpHeaders;
35 import org.apache.commons.lang3.time.StopWatch;
36 import org.junit.BeforeClass;
37 import org.junit.Ignore;
38 import org.junit.Test;
39 import org.mockito.Mockito;
40 import org.onap.aai.babel.logging.LogHelper.MdcParameter;
41 import org.onap.aai.babel.logging.LogHelper.TriConsumer;
42 import org.onap.aai.cl.api.LogFields;
43 import org.onap.aai.cl.api.Logger;
44 import org.onap.aai.cl.mdc.MdcOverride;
47 * Simple test to log each of the validation messages in turn.
49 * This version tests only the error logger at INFO level.
52 @Ignore("Test consistently fails in centos and is not critical")
53 public class TestApplicationLogger {
56 public static void setupClass() {
57 System.setProperty("APP_HOME", ".");
61 * Check that each message can be logged and that (by implication of successful logging) there is a corresponding
62 * resource (message format).
65 * if the log files cannot be read
68 public void logAllMessages() throws IOException {
69 Logger logger = LogHelper.INSTANCE;
70 LogHelper.INSTANCE.clearContext();
71 LogReader errorReader = new LogReader(LogHelper.getLogDirectory(), "error");
72 LogReader debugReader = new LogReader(LogHelper.getLogDirectory(), "debug");
73 String[] args = {"1", "2", "3", "4"};
74 for (ApplicationMsgs msg : Arrays.asList(ApplicationMsgs.values())) {
75 if (msg.name().endsWith("ERROR")) {
76 logger.error(msg, args);
77 validateLoggedMessage(msg, errorReader, "ERROR");
79 logger.error(msg, new RuntimeException("fred"), args);
80 validateLoggedMessage(msg, errorReader, "fred");
82 logger.info(msg, args);
83 validateLoggedMessage(msg, debugReader, "INFO");
85 logger.warn(msg, args);
86 validateLoggedMessage(msg, errorReader, "WARN");
89 logger.debug(msg, args);
90 validateLoggedMessage(msg, debugReader, "DEBUG");
95 * Check that each message can be logged and that (by implication of successful logging) there is a corresponding
96 * resource (message format).
99 * if the log file cannot be read
102 public void logDebugMessages() throws IOException {
103 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "debug");
104 LogHelper.INSTANCE.debug("a message");
105 String str = reader.getNewLines();
106 assertThat(str, is(notNullValue()));
110 public void logTraceMessage() throws IOException {
111 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "debug");
112 EELFManager.getInstance().getDebugLogger().setLevel(Level.TRACE);
113 LogHelper.INSTANCE.trace(ApplicationMsgs.LOAD_PROPERTIES, "a message");
114 String str = reader.getNewLines();
115 assertThat(str, is(notNullValue()));
116 EELFManager.getInstance().getAuditLogger().setLevel(Level.INFO);
117 LogHelper.INSTANCE.trace(ApplicationMsgs.LOAD_PROPERTIES, "message not written");
121 * Call logAuditError() for code coverage stats.
123 @Test(expected = Test.None.class /* no exception expected */)
124 public void logAuditError() {
125 LogHelper.INSTANCE.logAuditError(new Exception("test"));
126 EELFManager.getInstance().getAuditLogger().setLevel(Level.OFF);
127 LogHelper.INSTANCE.logAuditError(new Exception("test"));
128 EELFManager.getInstance().getAuditLogger().setLevel(Level.INFO);
132 * Check logAudit with HTTP headers.
134 * @throws IOException
135 * if the log file cannot be read
138 public void logAuditMessage() throws IOException {
139 final LogHelper logger = LogHelper.INSTANCE;
140 final LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit");
142 HttpHeaders headers = Mockito.mock(HttpHeaders.class);
143 Mockito.when(headers.getHeaderString("X-ECOMP-RequestID")).thenReturn("ecomp-request-id");
144 Mockito.when(headers.getHeaderString("X-FromAppId")).thenReturn("app-id");
146 // Call logAudit without first calling startAudit
147 logger.logAuditSuccess("first call: bob");
148 String str = reader.getNewLines();
149 assertThat(str, is(notNullValue()));
150 assertThat("audit message log level", str, containsString("INFO"));
151 assertThat("audit message content", str, containsString("bob"));
153 // This time call the start method
154 logger.startAudit(headers, null);
155 logger.logAuditSuccess("second call: foo");
156 str = reader.getNewLines();
157 assertThat(str, is(notNullValue()));
158 assertThat("audit message log level", str, containsString("INFO"));
159 assertThat("audit message content", str, containsString("foo"));
160 assertThat("audit message content", str, containsString("ecomp-request-id"));
161 assertThat("audit message content", str, containsString("app-id"));
165 * Check logAudit with no HTTP headers.
167 * @throws IOException
168 * if the log file cannot be read
171 public void logAuditMessageWithoutHeaders() throws IOException {
172 LogHelper logger = LogHelper.INSTANCE;
173 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit");
174 logger.startAudit(null, null);
175 logger.logAuditSuccess("foo");
176 String str = reader.getNewLines();
177 assertThat(str, is(notNullValue()));
178 assertThat("audit message log level", str, containsString("INFO"));
179 assertThat("audit message content", str, containsString("foo"));
183 * Check logAudit with mocked Servlet request.
185 * @throws IOException
186 * if the log file cannot be read
189 public void logAuditMessageWithServletRequest() throws IOException {
190 ServletRequest servletRequest = Mockito.mock(ServletRequest.class);
191 LogHelper logger = LogHelper.INSTANCE;
192 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit");
193 logger.startAudit(null, servletRequest);
194 logger.logAuditSuccess("foo");
195 String str = reader.getNewLines();
196 assertThat(str, is(notNullValue()));
197 assertThat("audit message log level", str, containsString("INFO"));
198 assertThat("audit message content", str, containsString("foo"));
201 @Test(expected = Test.None.class /* no exception expected */)
202 public void setDefaultContextValue() {
203 LogHelper logger = LogHelper.INSTANCE;
204 logger.setDefaultContextValue("key", "value");
205 logger.setDefaultContextValue(MdcParameter.USER, null);
211 * @throws IOException
212 * if the log file cannot be read
215 public void logMetricsMessage() throws IOException {
216 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "metrics");
217 LogHelper logger = LogHelper.INSTANCE;
218 logger.logMetrics("metrics: fred");
219 String str = reader.getNewLines();
220 assertThat(str, is(notNullValue()));
221 assertThat("metrics message log level", str, containsString("INFO"));
222 assertThat("metrics message content", str, containsString("fred"));
226 public void logMetricsMessageWithStopwatch() throws IOException {
227 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "metrics");
228 LogHelper logger = LogHelper.INSTANCE;
229 StopWatch stopWatch = new StopWatch();
231 logger.logMetrics(stopWatch, "joe", "bloggs");
232 String logLine = reader.getNewLines();
233 assertThat(logLine, is(notNullValue()));
234 assertThat("metrics message log level", logLine, containsString("INFO"));
235 assertThat("metrics message content", logLine, containsString("joe"));
239 public void callUnsupportedMethods() throws IOException {
240 LogHelper logger = LogHelper.INSTANCE;
241 ApplicationMsgs dummyMsg = ApplicationMsgs.LOAD_PROPERTIES;
242 callUnsupportedOperationMethod(logger::error, dummyMsg);
243 callUnsupportedOperationMethod(logger::info, dummyMsg);
244 callUnsupportedOperationMethod(logger::warn, dummyMsg);
245 callUnsupportedOperationMethod(logger::debug, dummyMsg);
246 callUnsupportedOperationMethod(logger::trace, dummyMsg);
248 logger.error(dummyMsg, new LogFields(), new RuntimeException("test"), "");
249 } catch (UnsupportedOperationException e) {
250 // Expected to reach here
253 logger.info(dummyMsg, new LogFields(), new MdcOverride(), "");
254 } catch (UnsupportedOperationException e) {
255 // Expected to reach here
258 logger.formatMsg(dummyMsg, "");
259 } catch (UnsupportedOperationException e) {
260 // Expected to reach here
265 * Call a logger method which is expected to throw an UnsupportedOperationException.
268 * the logger method to invoke
270 * any Application Message enumeration value
272 private void callUnsupportedOperationMethod(TriConsumer<Enum<?>, LogFields, String[]> logMethod,
273 ApplicationMsgs dummyMsg) {
274 logMethod.accept(dummyMsg, new LogFields(), new String[] {""});
275 org.junit.Assert.fail("method should have thrown execption"); // NOSONAR as code not reached
279 * Assert that a log message was logged to the expected log file at the expected severity.
282 * the Application Message enumeration value
284 * the log reader for the message
287 * @throws IOException
288 * if the log file cannot be read
290 private void validateLoggedMessage(ApplicationMsgs msg, LogReader reader, String severity) throws IOException {
291 String str = reader.getNewLines();
292 assertThat(str, is(notNullValue()));
293 // assertThat(msg.toString() + " log level", str, containsString("BABEL"));