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.Test;
38 import org.mockito.Mockito;
39 import org.onap.aai.babel.logging.LogHelper.MdcParameter;
40 import org.onap.aai.babel.logging.LogHelper.TriConsumer;
41 import org.onap.aai.cl.api.LogFields;
42 import org.onap.aai.cl.api.Logger;
43 import org.onap.aai.cl.mdc.MdcOverride;
46 * Simple test to log each of the validation messages in turn.
48 * This version tests only the error logger at INFO level.
51 public class TestApplicationLogger {
54 public static void setupClass() {
55 System.setProperty("APP_HOME", ".");
59 * Check that each message can be logged and that (by implication of successful logging) there is a corresponding
60 * resource (message format).
63 * if the log files cannot be read
66 public void logAllMessages() throws IOException {
67 Logger logger = LogHelper.INSTANCE;
68 LogHelper.INSTANCE.clearContext();
69 LogReader errorReader = new LogReader(LogHelper.getLogDirectory(), "error");
70 LogReader debugReader = new LogReader(LogHelper.getLogDirectory(), "debug");
71 String[] args = {"1", "2", "3", "4"};
72 for (ApplicationMsgs msg : Arrays.asList(ApplicationMsgs.values())) {
73 if (msg.name().endsWith("ERROR")) {
74 logger.error(msg, args);
75 validateLoggedMessage(msg, errorReader, "ERROR");
77 logger.error(msg, new RuntimeException("fred"), args);
78 validateLoggedMessage(msg, errorReader, "fred");
80 logger.info(msg, args);
81 validateLoggedMessage(msg, debugReader, "INFO");
83 logger.warn(msg, args);
84 validateLoggedMessage(msg, errorReader, "WARN");
87 logger.debug(msg, args);
88 validateLoggedMessage(msg, debugReader, "DEBUG");
93 * Check that each message can be logged and that (by implication of successful logging) there is a corresponding
94 * resource (message format).
97 * if the log file cannot be read
100 public void logDebugMessages() throws IOException {
101 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "debug");
102 LogHelper.INSTANCE.debug("a message");
103 String str = reader.getNewLines();
104 assertThat(str, is(notNullValue()));
108 public void logTraceMessage() throws IOException {
109 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "debug");
110 EELFManager.getInstance().getDebugLogger().setLevel(Level.TRACE);
111 LogHelper.INSTANCE.trace(ApplicationMsgs.LOAD_PROPERTIES, "a message");
112 String str = reader.getNewLines();
113 assertThat(str, is(notNullValue()));
114 EELFManager.getInstance().getAuditLogger().setLevel(Level.INFO);
115 LogHelper.INSTANCE.trace(ApplicationMsgs.LOAD_PROPERTIES, "message not written");
119 * Call logAuditError() for code coverage stats.
122 public void logAuditError() {
123 LogHelper.INSTANCE.logAuditError(new Exception("test"));
124 EELFManager.getInstance().getAuditLogger().setLevel(Level.OFF);
125 LogHelper.INSTANCE.logAuditError(new Exception("test"));
126 EELFManager.getInstance().getAuditLogger().setLevel(Level.INFO);
130 * Check logAudit with HTTP headers.
132 * @throws IOException
133 * if the log file cannot be read
136 public void logAuditMessage() throws IOException {
137 final LogHelper logger = LogHelper.INSTANCE;
138 final LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit");
140 HttpHeaders headers = Mockito.mock(HttpHeaders.class);
141 Mockito.when(headers.getHeaderString("X-ECOMP-RequestID")).thenReturn("ecomp-request-id");
142 Mockito.when(headers.getHeaderString("X-FromAppId")).thenReturn("app-id");
144 // Call logAudit without first calling startAudit
145 logger.logAuditSuccess("first call: bob");
146 String str = reader.getNewLines();
147 assertThat(str, is(notNullValue()));
148 assertThat("audit message log level", str, containsString("INFO"));
149 assertThat("audit message content", str, containsString("bob"));
151 // This time call the start method
152 logger.startAudit(headers, null);
153 logger.logAuditSuccess("second call: foo");
154 str = reader.getNewLines();
155 assertThat(str, is(notNullValue()));
156 assertThat("audit message log level", str, containsString("INFO"));
157 assertThat("audit message content", str, containsString("foo"));
158 assertThat("audit message content", str, containsString("ecomp-request-id"));
159 assertThat("audit message content", str, containsString("app-id"));
163 * Check logAudit with no HTTP headers.
165 * @throws IOException
166 * if the log file cannot be read
169 public void logAuditMessageWithoutHeaders() throws IOException {
170 LogHelper logger = LogHelper.INSTANCE;
171 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit");
172 logger.startAudit(null, null);
173 logger.logAuditSuccess("foo");
174 String str = reader.getNewLines();
175 assertThat(str, is(notNullValue()));
176 assertThat("audit message log level", str, containsString("INFO"));
177 assertThat("audit message content", str, containsString("foo"));
181 * Check logAudit with mocked Servlet request.
183 * @throws IOException
184 * if the log file cannot be read
187 public void logAuditMessageWithServletRequest() throws IOException {
188 ServletRequest servletRequest = Mockito.mock(ServletRequest.class);
189 LogHelper logger = LogHelper.INSTANCE;
190 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit");
191 logger.startAudit(null, servletRequest);
192 logger.logAuditSuccess("foo");
193 String str = reader.getNewLines();
194 assertThat(str, is(notNullValue()));
195 assertThat("audit message log level", str, containsString("INFO"));
196 assertThat("audit message content", str, containsString("foo"));
200 public void setDefaultContextValue() {
201 LogHelper logger = LogHelper.INSTANCE;
202 logger.setDefaultContextValue("key", "value");
203 logger.setDefaultContextValue(MdcParameter.USER, null);
209 * @throws IOException
210 * if the log file cannot be read
213 public void logMetricsMessage() throws IOException {
214 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "metrics");
215 LogHelper logger = LogHelper.INSTANCE;
216 logger.logMetrics("metrics: fred");
217 String str = reader.getNewLines();
218 assertThat(str, is(notNullValue()));
219 assertThat("metrics message log level", str, containsString("INFO"));
220 assertThat("metrics message content", str, containsString("fred"));
224 public void logMetricsMessageWithStopwatch() throws IOException {
225 LogReader reader = new LogReader(LogHelper.getLogDirectory(), "metrics");
226 LogHelper logger = LogHelper.INSTANCE;
227 StopWatch stopWatch = new StopWatch();
229 logger.logMetrics(stopWatch, "joe", "bloggs");
230 String logLine = reader.getNewLines();
231 assertThat(logLine, is(notNullValue()));
232 assertThat("metrics message log level", logLine, containsString("INFO"));
233 assertThat("metrics message content", logLine, containsString("joe"));
237 public void callUnsupportedMethods() throws IOException {
238 LogHelper logger = LogHelper.INSTANCE;
239 ApplicationMsgs dummyMsg = ApplicationMsgs.LOAD_PROPERTIES;
240 callUnsupportedOperationMethod(logger::error, dummyMsg);
241 callUnsupportedOperationMethod(logger::info, dummyMsg);
242 callUnsupportedOperationMethod(logger::warn, dummyMsg);
243 callUnsupportedOperationMethod(logger::debug, dummyMsg);
244 callUnsupportedOperationMethod(logger::trace, dummyMsg);
246 logger.error(dummyMsg, new LogFields(), new RuntimeException("test"), "");
247 } catch (UnsupportedOperationException e) {
248 // Expected to reach here
251 logger.info(dummyMsg, new LogFields(), new MdcOverride(), "");
252 } catch (UnsupportedOperationException e) {
253 // Expected to reach here
256 logger.formatMsg(dummyMsg, "");
257 } catch (UnsupportedOperationException e) {
258 // Expected to reach here
263 * Call a logger method which is expected to throw an UnsupportedOperationException.
266 * the logger method to invoke
268 * any Application Message enumeration value
270 private void callUnsupportedOperationMethod(TriConsumer<Enum<?>, LogFields, String[]> logMethod,
271 ApplicationMsgs dummyMsg) {
273 logMethod.accept(dummyMsg, new LogFields(), new String[] {""});
274 org.junit.Assert.fail("method should have thrown execption"); // NOSONAR as code not reached
275 } catch (UnsupportedOperationException e) {
276 // Expected to reach here
281 * Assert that a log message was logged to the expected log file at the expected severity.
284 * the Application Message enumeration value
286 * the log reader for the message
289 * @throws IOException
290 * if the log file cannot be read
292 private void validateLoggedMessage(ApplicationMsgs msg, LogReader reader, String severity) throws IOException {
293 String str = reader.getNewLines();
294 assertThat(str, is(notNullValue()));
295 // assertThat(msg.toString() + " log level", str, containsString("BABEL"));