Merge "fixed sonar issue in MusicPolicyVoilationException"
[music.git] / src / main / java / org / onap / music / eelf / logging / EELFLoggerDelegate.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
4  * ===================================================================
5  *  Copyright (c) 2017 AT&T Intellectual Property
6  * ===================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  * 
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  * 
19  * ============LICENSE_END=============================================
20  * ====================================================================
21  */
22 package org.onap.music.eelf.logging;
23
24 import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
25 import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;
26 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
27 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
28 import java.net.InetAddress;
29 import java.text.MessageFormat;
30 import java.util.concurrent.ConcurrentHashMap;
31 import java.util.concurrent.ConcurrentMap;
32 import javax.servlet.http.HttpServletRequest;
33 import org.slf4j.MDC;
34 import com.att.eelf.configuration.EELFLogger;
35 import com.att.eelf.configuration.EELFManager;
36 import com.att.eelf.configuration.SLF4jWrapper;
37
38 public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger {
39
40     public static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger();
41     public static final EELFLogger applicationLogger =
42                     EELFManager.getInstance().getApplicationLogger();
43     public static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
44     public static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
45     public static final EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger();
46
47     private String className;
48     private static ConcurrentMap<String, EELFLoggerDelegate> classMap = new ConcurrentHashMap<>();
49
50     public EELFLoggerDelegate(final String className) {
51         super(className);
52         this.className = className;
53     }
54
55     /**
56      * Convenience method that gets a logger for the specified class.
57      * 
58      * @see #getLogger(String)
59      * 
60      * @param clazz
61      * @return Instance of EELFLoggerDelegate
62      */
63     public static EELFLoggerDelegate getLogger(Class<?> clazz) {
64         return getLogger(clazz.getName());
65     }
66
67     /**
68      * Gets a logger for the specified class name. If the logger does not already exist in the map,
69      * this creates a new logger.
70      * 
71      * @param className If null or empty, uses EELFLoggerDelegate as the class name.
72      * @return Instance of EELFLoggerDelegate
73      */
74     public static EELFLoggerDelegate getLogger(final String className) {
75         String classNameNeverNull = className == null || "".equals(className)
76                         ? EELFLoggerDelegate.class.getName()
77                         : className;
78         EELFLoggerDelegate delegate = classMap.get(classNameNeverNull);
79         if (delegate == null) {
80             delegate = new EELFLoggerDelegate(className);
81             classMap.put(className, delegate);
82         }
83         return delegate;
84     }
85
86     /**
87      * Logs a message at the lowest level: trace.
88      * 
89      * @param logger
90      * @param msg
91      */
92     public void trace(EELFLogger logger, String msg) {
93         if (logger.isTraceEnabled()) {
94             logger.trace(msg);
95         }
96     }
97
98     /**
99      * Logs a message with parameters at the lowest level: trace.
100      * 
101      * @param logger
102      * @param msg
103      * @param arguments
104      */
105     public void trace(EELFLogger logger, String msg, Object... arguments) {
106         if (logger.isTraceEnabled()) {
107             logger.trace(msg, arguments);
108         }
109     }
110
111     /**
112      * Logs a message and throwable at the lowest level: trace.
113      * 
114      * @param logger
115      * @param msg
116      * @param th
117      */
118     public void trace(EELFLogger logger, String msg, Throwable th) {
119         if (logger.isTraceEnabled()) {
120             logger.trace(msg, th);
121         }
122     }
123
124     /**
125      * Logs a message at the second-lowest level: debug.
126      * 
127      * @param logger
128      * @param msg
129      */
130     public void debug(EELFLogger logger, String msg) {
131         if (logger.isDebugEnabled()) {
132             logger.debug(msg);
133         }
134     }
135
136     /**
137      * Logs a message with parameters at the second-lowest level: debug.
138      * 
139      * @param logger
140      * @param msg
141      * @param arguments
142      */
143     public void debug(EELFLogger logger, String msg, Object... arguments) {
144         if (logger.isDebugEnabled()) {
145             logger.debug(msg, arguments);
146         }
147     }
148
149     /**
150      * Logs a message and throwable at the second-lowest level: debug.
151      * 
152      * @param logger
153      * @param msg
154      * @param th
155      */
156     public void debug(EELFLogger logger, String msg, Throwable th) {
157         if (logger.isDebugEnabled()) {
158             logger.debug(msg, th);
159         }
160     }
161
162     /**
163      * Logs a message at info level.
164      * 
165      * @param logger
166      * @param msg
167      */
168     public void info(EELFLogger logger, String msg) {
169         logger.info(className + " - "+msg);
170     }
171
172     /**
173      * Logs a message with parameters at info level.
174      *
175      * @param logger
176      * @param msg
177      * @param arguments
178      */
179     public void info(EELFLogger logger, String msg, Object... arguments) {
180         logger.info(msg, arguments);
181     }
182
183     /**
184      * Logs a message and throwable at info level.
185      * 
186      * @param logger
187      * @param msg
188      * @param th
189      */
190     public void info(EELFLogger logger, String msg, Throwable th) {
191         logger.info(msg, th);
192     }
193
194     /**
195      * Logs a message at warn level.
196      * 
197      * @param logger
198      * @param msg
199      */
200     public void warn(EELFLogger logger, String msg) {
201         logger.warn(msg);
202     }
203
204     /**
205      * Logs a message with parameters at warn level.
206      * 
207      * @param logger
208      * @param msg
209      * @param arguments
210      */
211     public void warn(EELFLogger logger, String msg, Object... arguments) {
212         logger.warn(msg, arguments);
213     }
214
215     /**
216      * Logs a message and throwable at warn level.
217      * 
218      * @param logger
219      * @param msg
220      * @param th
221      */
222     public void warn(EELFLogger logger, String msg, Throwable th) {
223         logger.warn(msg, th);
224     }
225
226     /**
227      * Logs a message at error level.
228      * 
229      * @param logger
230      * @param msg
231      * 
232      * @deprecated use {@link #error(EELF, Exception)} instead
233      */
234     @Deprecated
235     public void error(EELFLogger logger, String msg) {
236         logger.error(className+ " - " + msg);
237     }
238     
239     /**
240      * Logs a message at error level.
241      * 
242      * @param logger
243      * @param msg
244      */
245     public void error(EELFLogger logger, Exception e) {
246         logger.error(className+ " - ", e);
247     }
248
249     /**
250      * Logs a message with parameters at error level.
251      * 
252      * @param logger
253      * @param msg
254      * @param arguments
255      * 
256      * @deprecated use {@link #error(EELF, Exception, Object...)} instead
257      */
258     @Deprecated
259     public void error(EELFLogger logger, String msg, Object... arguments) {
260         logger.error(msg, arguments);
261     }
262     
263     /**
264      * Logs a message with parameters at error level.
265      * 
266      * @param logger
267      * @param msg
268      * @param arguments
269      */
270     public void error(EELFLogger logger, Exception e, Object... arguments) {
271         logger.error("Exception", e, arguments);
272     }
273
274     /**
275      * Logs a message and throwable at error level.
276      * 
277      * @param logger
278      * @param msg
279      * @param th
280      */
281     public void error(EELFLogger logger, String msg, Throwable th) {
282         logger.error(msg, th);
283     }
284
285     /**
286      * Logs a message with the associated alarm severity at error level.
287      * 
288      * @param logger
289      * @param msg
290      * @param severtiy
291      * @deprecated use {@link #error(EELF, Exception)} instead
292      */
293     @Deprecated
294     public void error(EELFLogger logger, String msg, Object /* AlarmSeverityEnum */ severtiy) {
295         logger.error(msg);
296     }
297
298     /**
299      * Initializes the logger context.
300      */
301     public void init() {
302         setGlobalLoggingContext();
303         final String msg =
304                         "############################ Logging is started. ############################";
305         // These loggers emit the current date-time without being told.
306         info(applicationLogger, msg);
307         error(errorLogger, msg);
308         debug(debugLogger, msg);
309         info(auditLogger, msg);
310         info(metricsLogger, msg);
311     }
312
313     /**
314      * Builds a message using a template string and the arguments.
315      * 
316      * @param message
317      * @param args
318      * @return
319      */
320     private String formatMessage(String message, Object... args) {
321         StringBuilder sbFormattedMessage = new StringBuilder();
322         if (args != null && args.length > 0 && message != null && message != "") {
323             MessageFormat mf = new MessageFormat(message);
324             sbFormattedMessage.append(mf.format(args));
325         } else {
326             sbFormattedMessage.append(message);
327         }
328
329         return sbFormattedMessage.toString();
330     }
331
332     /**
333      * Loads all the default logging fields into the MDC context.
334      */
335     private void setGlobalLoggingContext() {
336         MDC.put(MDC_SERVICE_INSTANCE_ID, "");
337         try {
338             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
339             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
340         } catch (Exception e) {
341             errorLogger.error("setGlobalLoggingContext failed", e);
342         }
343     }
344
345     public static void mdcPut(String key, String value) {
346         MDC.put(key, value);
347     }
348
349     public static String mdcGet(String key) {
350         return MDC.get(key);
351     }
352
353     public static void mdcRemove(String key) {
354         MDC.remove(key);
355     }
356
357     /**
358      * Loads the RequestId/TransactionId into the MDC which it should be receiving with an each
359      * incoming REST API request. Also, configures few other request based logging fields into the
360      * MDC context.
361      * 
362      * @param req
363      * @param appName
364      */
365     public void setRequestBasedDefaultsIntoGlobalLoggingContext(HttpServletRequest req,
366                     String appName) {
367         // Load the default fields
368         setGlobalLoggingContext();
369
370         // Load the request based fields
371         if (req != null) {
372             // Rest Path
373             MDC.put(MDC_SERVICE_NAME, req.getServletPath());
374
375             // Client IPAddress i.e. IPAddress of the remote host who is making
376             // this request.
377             String clientIPAddress = req.getHeader("X-FORWARDED-FOR");
378             if (clientIPAddress == null) {
379                 clientIPAddress = req.getRemoteAddr();
380             }
381         }
382     }
383 }