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