001/*
002 * To change this template, choose Tools | Templates
003 * and open the template in the editor.
004 */
005
006package armyc2.c5isr.renderer.utilities;
007
008//import java.io.*;
009import java.text.SimpleDateFormat;
010import java.util.ArrayList;
011import java.util.Date;
012import java.util.Iterator;
013import java.util.Map;
014import java.util.logging.*;
015
016import android.util.Log;
017
018/**
019 * Error Logging class for Renderer
020*
021 */
022public class ErrorLogger {
023
024   // private static ErrorLogger _el = null;
025    public static final String LoggerName = "C5ISR Renderer ErrorLogger";
026    //private static Logger _Logger = null;//
027    //private static final Logger _Logger = Logger.getLogger(LoggerName);
028    private static Level _level = Level.INFO;
029    //private static java.util.logging.FileHandler fh = null;
030    private static Boolean _LoggingEnabled = false;
031    //private static String _LoggingPath = System.getProperty("user.dir");
032    //fate format: Nov 19, 2012 11:41:40 AM
033    private static SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss aa ");
034    
035    /*
036    private ErrorLogger()
037    {
038        Init();
039    }
040
041    
042    private static synchronized ErrorLogger getInstance()
043    {
044        
045        //if(_Logger == null)
046        if(_el == null)
047        {
048            try
049            {
050                _el = new ErrorLogger();
051                
052            }
053            catch(Exception exc)
054            {
055                System.err.println(exc.getMessage());
056                //JOptionPane.showMessageDialog(null, ioe.getMessage(), "Message", JOptionPane.PLAIN_MESSAGE);
057            }
058        }
059        
060        return _el;
061    }
062    
063    private void Init()
064    {
065        try
066        {
067            if(_Logger != null)
068                _Logger.setLevel(Level.INFO);
069        }
070        catch(Exception exc)
071        {
072            System.err.println(exc.getMessage());
073            //JOptionPane.showMessageDialog(null, ioe.getMessage(), "Message", JOptionPane.PLAIN_MESSAGE);
074        }
075    }//*/
076
077    /**
078     * True if logging is enabled
079     * @return
080     */
081    public static Boolean getLoggingStatus()
082    {
083        return _LoggingEnabled;
084    }
085
086    /**
087     * Takes a throwable and puts it's stacktrace into a string.
088     * @param thrown
089     * @return
090     */
091    public static String getStackTrace(Throwable thrown)
092    {
093        try
094        {
095            /*
096            Writer writer = new StringWriter();
097            PrintWriter printWriter = new PrintWriter(writer);
098            thrown.printStackTrace(printWriter);
099            return writer.toString();*/
100            String eol = System.getProperty("line.separator");
101            StringBuilder sb = new StringBuilder();
102            sb.append(thrown.toString());
103            sb.append(eol);
104            for(StackTraceElement element : thrown.getStackTrace())
105            {
106                sb.append("        at ");
107                sb.append(element);
108                sb.append(eol);
109            }
110            return sb.toString();
111        }
112        catch(Exception exc)
113        {
114                Log.e("ErrorLogger.getStackTrace", exc.getMessage());
115            
116            return "Error - couldn't retrieve stack trace";
117        }
118    }
119
120    /**
121     * TRUE: Creates a file handler that will log message to a file.
122     * FALSE: logging just goes to console.
123     * @param enable 
124     */
125    public static void EnableLogging(Boolean enable)
126    {
127
128        _LoggingEnabled = enable;
129    }
130
131    /**
132     * Folder location to store the log file.
133     * Defaults to "System.getProperty("user.dir")"
134     * @param path
135     */
136    public static void setLoggingPath(String path)
137    {
138    }
139
140    /**
141     * clears log files that are beyond a passed number of days old
142     * @param DaysOld
143     */
144    public static void CleanupOldFiles(int DaysOld)
145    {/*
146        
147        Calendar Cal = new GregorianCalendar();
148        Calendar CalLastModified = new GregorianCalendar();
149        Cal.add(Calendar.DAY_OF_MONTH, -DaysOld);//remove anything this many days old
150        
151        String path = _LoggingPath;//System.getProperty("user.dir");
152        File lookup = new File(path);
153        File[] results = lookup.listFiles();
154        for(File foo : results)
155        {
156            if(foo.getName().startsWith("TBCRendererLog"))
157            {
158                long age = foo.lastModified();
159
160                CalLastModified.setTimeInMillis(age);
161                if(Cal.after(CalLastModified))
162                    foo.delete();
163            }
164        }//*/
165    }
166
167    /**
168     * Set minimum level at which an item can be logged.
169     * In descending order:
170     * Severe
171     * Warning
172     * Info
173     * Config
174     * Fine
175     * Finer
176     * Finest
177     * @param newLevel
178     */
179    public static synchronized void setLevel(Level newLevel)
180    {
181        setLevel(newLevel, false);
182    }
183    
184    /**
185     * Set minimum level at which an item can be logged.
186     * In descending order:
187     * Severe
188     * Warning
189     * Info
190     * Config
191     * Fine
192     * Finer
193     * Finest
194     * @param newLevel
195     * @param setConsoleHandler logger could be set to FINE but the console
196     * handler could be set to INFO.  In that case, anything logged at FINE
197     * wouldn't show because it'd get blocked by the console handler.  Set to 
198     * "true" to make sure the console handler will let you log at the level 
199     * you want.  If you're only concerned with the log file, you can leave 
200     * "false"
201     */
202    public static synchronized void setLevel(Level newLevel, Boolean setConsoleHandler)
203    {
204        _level = newLevel;
205        
206    }
207    
208    /**
209     * Specify whether or not this logger should send its output
210     * to it's parent Logger.  This means that any LogRecords will
211     * also be written to the parent's Handlers, and potentially
212     * to its parent, recursively up the namespace.
213     * Defaults to true;
214     *
215     * @param useParentHandlers   true if output is to be sent to the
216     *          logger's parent.
217     * @exception  SecurityException  if a security manager exists and if
218     *             the caller does not have LoggingPermission("control").
219     */
220    public static void setUseParentHandlers(boolean useParentHandlers)
221    {
222        //_Logger.setUseParentHandlers(useParentHandlers);
223    }
224
225    /**
226     * Gets the java.util.logging.Level that the logger is set to.
227     * @return 
228     */
229    public static synchronized Level getLevel()
230    {
231        return _level;
232        //return _Logger.getLevel();
233    }
234
235    private static String getFileName()
236    {
237        //String path = _LoggingPath;//System.getProperty("user.dir");
238        String fileName = "";
239        /*
240        SimpleDateFormat dateFormat = new SimpleDateFormat("_MMMdd");
241        fileName = "TBCRendererLog" + dateFormat.format(new Date()) + ".txt";
242        fileName = path + "\\" + fileName;
243        //fileName = path.substring(0, 2) + "\\" + fileName;//*/
244        return fileName;
245    }
246    
247    /**
248     * Log a method entry.
249     * <p>
250     * This is a convenience method that can be used to log entry
251     * to a method.  A LogRecord with message "ENTRY", log level
252     * FINER, and the given sourceMethod and sourceClass is logged.
253     * <p>
254     * @param   sourceClass    name of class that issued the logging request
255     * @param   sourceMethod   name of method that is being entered
256     */
257    public static void Entering(String sourceClass, String sourceMethod)
258    {
259        //_Logger.entering(sourceClass, sourceMethod);
260        if(_level.intValue() <= Level.FINER.intValue())
261        {
262            Log.i(sourceClass + "." + sourceMethod, "Entering: " + sourceClass + "." + sourceMethod);
263        }
264    }
265    
266    /**
267     * Log a method entry, with one parameter.
268     * <p>
269     * This is a convenience method that can be used to log entry
270     * to a method.  A LogRecord with message "ENTRY {0}", log level
271     * FINER, and the given sourceMethod, sourceClass, and parameter
272     * is logged.
273     * <p>
274     * @param   sourceClass    name of class that issued the logging request
275     * @param   sourceMethod   name of method that is being entered
276     * @param   param1         parameter to the method being entered
277     */
278    public static void Entering(String sourceClass, String sourceMethod, Object param1)
279    {
280        //_Logger.entering(sourceClass, sourceMethod,param1);
281        if(_level.intValue() <= Level.FINER.intValue())
282        {
283                Log.i(sourceClass + "." + sourceMethod, "Entering: " + sourceClass + "." + sourceMethod + 
284                    " - " + String.valueOf(param1));
285            
286        }
287    }
288    
289    /**
290     * Log a method entry, with an array of parameters.
291     * <p>
292     * This is a convenience method that can be used to log entry
293     * to a method.  A LogRecord with message "ENTRY" (followed by a 
294     * format {N} indicator for each entry in the parameter array), 
295     * log level FINER, and the given sourceMethod, sourceClass, and 
296     * parameters is logged.
297     * <p>
298     * @param   sourceClass    name of class that issued the logging request
299     * @param   sourceMethod   name of method that is being entered
300     * @param   params         array of parameters to the method being entered
301     */
302    public static void Entering(String sourceClass, String sourceMethod, Object[] params)
303    {
304        //_Logger.entering(sourceClass, sourceMethod,params);
305        if(_level.intValue() <= Level.FINER.intValue())
306        {
307            Log.i(sourceClass + "." + sourceMethod,"Entering: " + sourceClass + "." + sourceMethod + "with params:");
308            if(params != null)
309            {
310                for(Object param : params)
311                {
312                    System.out.println(String.valueOf(param));
313                }
314            }
315        }
316    }
317    
318    /**
319     * Log a method return.
320     * <p>
321     * This is a convenience method that can be used to log returning
322     * from a method.  A LogRecord with message "RETURN", log level
323     * FINER, and the given sourceMethod and sourceClass is logged.
324     * <p>
325     * @param   sourceClass    name of class that issued the logging request
326     * @param   sourceMethod   name of the method 
327     */
328    public static void Exiting(String sourceClass, String sourceMethod) 
329    {
330        //_Logger.exiting(sourceClass, sourceMethod);
331        if(_level.intValue() <= Level.FINER.intValue())
332        {
333            Log.i(sourceClass + "." + sourceMethod,"Exiting: " + sourceClass + "." + sourceMethod);
334        }
335    }
336    
337    /**
338     * Log a method return, with result object.
339     * <p>
340     * This is a convenience method that can be used to log returning
341     * from a method.  A LogRecord with message "RETURN {0}", log level
342     * FINER, and the gives sourceMethod, sourceClass, and result
343     * object is logged.
344     * <p>
345     * @param   sourceClass    name of class that issued the logging request
346     * @param   sourceMethod   name of the method 
347     * @param   result  Object that is being returned
348     */
349    public static void Exiting(String sourceClass, String sourceMethod, Object result) 
350    {
351        //_Logger.exiting(sourceClass, sourceMethod, result);
352        if(_level.intValue() <= Level.FINER.intValue())
353        {
354            Log.i(sourceClass + "." + sourceMethod,("Entering: " + sourceClass + "." + sourceMethod + 
355                    " - " + String.valueOf(result)));
356        }
357    }
358
359  
360    /**
361     * Defaults to Level.INFO
362     * @param message 
363     */
364    public static void LogMessage(String message)
365    {
366        LogMessage(message, Level.INFO, false);
367    }
368
369    /**
370     * Defaults to Level.INFO
371     * @param message
372     * @param showMessageBox 
373     */
374    public static void LogMessage(String message, Boolean showMessageBox)
375    {
376        LogMessage(message, Level.INFO, showMessageBox);
377    }
378
379    public static void LogMessage(String message, Level lvl, Boolean showMessageBox)
380    {
381        if(lvl.intValue() >= _level.intValue())
382        {
383                Log.i("ErrorLogger",sdf.format(new Date()) + LoggerName);
384                Log.i("ErrorLogger","INFO: " + message);
385        }
386    }
387
388    public static void LogMessage(String sourceClass, String sourceMethod, String message)
389    {
390        LogMessage(sourceClass, sourceMethod, message, Level.INFO, false);
391    }
392
393    public static void LogMessage(String sourceClass, String sourceMethod, String message, Boolean showMessageBox)
394    {
395        LogMessage(sourceClass, sourceMethod, message, Level.INFO, showMessageBox);
396    }
397
398    public static void LogMessage(String sourceClass, String sourceMethod, String message, Level lvl)
399    {
400        LogMessage(sourceClass, sourceMethod, message, lvl, false);
401    }
402
403    public static void LogMessage(String sourceClass, String sourceMethod, String message, Level lvl, Boolean showMessageBox)
404    {
405        if(lvl.intValue() >= _level.intValue())
406        {
407                Log.i(sourceClass + "." + sourceMethod,sdf.format(new Date()) + sourceClass + "." + sourceMethod);
408                Log.i(sourceClass + "." + sourceMethod,lvl.toString() + ": " + message);
409        }
410
411    }
412    
413    public static void LogMessage(String sourceClass, String sourceMethod, String message, Level lvl, Object param1, Boolean showMessageBox)
414    {
415        Object[] params = new Object[1];
416        params[0] = param1;
417        LogMessage(sourceClass, sourceMethod, message, lvl, params, showMessageBox);
418    }
419    
420    public static void LogMessage(String sourceClass, String sourceMethod, String message, Level lvl, Object params[], Boolean showMessageBox)
421    {
422        if(lvl.intValue() >= _level.intValue())
423        {
424                Log.i(sourceClass + "." + sourceMethod,sdf.format(new Date()) + sourceClass + "." + sourceMethod);
425                Log.i(sourceClass + "." + sourceMethod,lvl.toString() + ": " + message);
426
427            for(Object param : params)
428            {
429                Log.i(sourceClass + "." + sourceMethod,String.valueOf(param));
430            }  
431        }
432    }
433
434    public static void LogException(String sourceClass, String sourceMethod, Exception exc)
435    {
436        LogException(sourceClass, sourceMethod, exc, Level.INFO, false);
437    }
438
439    public static void LogException(String sourceClass, String sourceMethod, Exception exc, Boolean showMessageBox)
440    {
441        LogException(sourceClass, sourceMethod, exc, Level.INFO, showMessageBox);
442    }
443
444    public static void LogException(String sourceClass, String sourceMethod, Exception exc, Level lvl)
445    {
446        LogException(sourceClass, sourceMethod, exc, lvl, false);
447    }
448
449    public static void LogException(String sourceClass, String sourceMethod, Exception exc, Level lvl, Boolean showMessageBox)
450    {
451        if(lvl.intValue() >= _level.intValue())
452        {
453                Log.e(sourceClass + "." + sourceMethod,sdf.format(new Date()) + sourceClass + "." + sourceMethod);
454                Log.e(sourceClass + "." + sourceMethod,lvl.toString() + ": " + exc.getMessage());
455                Log.e(sourceClass + "." + sourceMethod,getStackTrace(exc));
456        }
457    }
458    
459    private static String PrintList(ArrayList list)
460    {
461        String message = "";
462        for(Object item : list)
463        {
464
465            message += item.toString() + "\n";
466        }
467        return message;
468    }
469    
470    private static String PrintObjectMap(Map<String, Object> map)
471    {
472        Iterator<Object> itr = map.values().iterator();
473        String message = "";
474        String temp = null;
475        while(itr.hasNext())
476        {
477            temp = String.valueOf(itr.next());
478            if(temp != null)
479                message += temp + "\n";
480        }
481        //ErrorLogger.LogMessage(message);
482        return message;
483    }
484
485}