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