Push variuos changes
[music.git] / jar / 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     public void error(EELFLogger logger, String msg) {
234         logger.error(className+ " - " + msg);
235     }
236
237     /**
238      * Logs a message with parameters at error level.
239      * 
240      * @param logger
241      * @param msg
242      * @param arguments
243      */
244     public void error(EELFLogger logger, String msg, Object... arguments) {
245         logger.warn(msg, arguments);
246     }
247
248     /**
249      * Logs a message and throwable at error level.
250      * 
251      * @param logger
252      * @param msg
253      * @param th
254      */
255     public void error(EELFLogger logger, String msg, Throwable th) {
256         logger.warn(msg, th);
257     }
258
259     /**
260      * Logs a message with the associated alarm severity at error level.
261      * 
262      * @param logger
263      * @param msg
264      * @param severtiy
265      */
266     public void error(EELFLogger logger, String msg, Object /* AlarmSeverityEnum */ severtiy) {
267         logger.error(msg);
268     }
269
270     /**
271      * Initializes the logger context.
272      */
273     public void init() {
274         setGlobalLoggingContext();
275         final String msg =
276                         "############################ Logging is started. ############################";
277         // These loggers emit the current date-time without being told.
278         info(applicationLogger, msg);
279         error(errorLogger, msg);
280         debug(debugLogger, msg);
281         info(auditLogger, msg);
282         info(metricsLogger, msg);
283     }
284
285     /**
286      * Builds a message using a template string and the arguments.
287      * 
288      * @param message
289      * @param args
290      * @return
291      */
292     private String formatMessage(String message, Object... args) {
293         StringBuilder sbFormattedMessage = new StringBuilder();
294         if (args != null && args.length > 0 && message != null && message != "") {
295             MessageFormat mf = new MessageFormat(message);
296             sbFormattedMessage.append(mf.format(args));
297         } else {
298             sbFormattedMessage.append(message);
299         }
300
301         return sbFormattedMessage.toString();
302     }
303
304     /**
305      * Loads all the default logging fields into the MDC context.
306      */
307     private void setGlobalLoggingContext() {
308         MDC.put(MDC_SERVICE_INSTANCE_ID, "");
309         try {
310             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
311             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
312         } catch (Exception e) {
313             errorLogger.error("setGlobalLoggingContext failed", e);
314         }
315     }
316
317     public static void mdcPut(String key, String value) {
318         MDC.put(key, value);
319     }
320
321     public static String mdcGet(String key) {
322         return MDC.get(key);
323     }
324
325     public static void mdcRemove(String key) {
326         MDC.remove(key);
327     }
328
329     /**
330      * Loads the RequestId/TransactionId into the MDC which it should be receiving with an each
331      * incoming REST API request. Also, configures few other request based logging fields into the
332      * MDC context.
333      * 
334      * @param req
335      * @param appName
336      */
337     public void setRequestBasedDefaultsIntoGlobalLoggingContext(HttpServletRequest req,
338                     String appName) {
339         // Load the default fields
340         setGlobalLoggingContext();
341
342         // Load the request based fields
343         if (req != null) {
344             // Rest Path
345             MDC.put(MDC_SERVICE_NAME, req.getServletPath());
346
347             // Client IPAddress i.e. IPAddress of the remote host who is making
348             // this request.
349             String clientIPAddress = req.getHeader("X-FORWARDED-FOR");
350             if (clientIPAddress == null) {
351                 clientIPAddress = req.getRemoteAddr();
352             }
353         }
354     }
355 }