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