KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > compiere > util > Log


1 /******************************************************************************
2  * The contents of this file are subject to the Compiere License Version 1.1
3  * ("License"); You may not use this file except in compliance with the License
4  * You may obtain a copy of the License at http://www.compiere.org/license.html
5  * Software distributed under the License is distributed on an "AS IS" basis,
6  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
7  * the specific language governing rights and limitations under the License.
8  * The Original Code is Compiere ERP & CRM Business Solution
9  * The Initial Developer of the Original Code is Jorg Janke and ComPiere, Inc.
10  * Portions created by Jorg Janke are Copyright (C) 1999-2001 Jorg Janke, parts
11  * created by ComPiere are Copyright (C) ComPiere, Inc.; All Rights Reserved.
12  * Contributor(s): ______________________________________.
13  *****************************************************************************/

14 package org.compiere.util;
15
16 import java.sql.*;
17 import java.util.*;
18 import java.io.*;
19 import java.net.*;
20 import java.awt.*;
21 import java.text.*;
22
23 import org.compiere.*;
24 import org.compiere.db.*;
25
26 /**
27  * Logging Facilities.
28  * - The Methods returning void can be removed
29  *
30  * @author Jorg Janke
31  * @version $Id: Log.java,v 1.5 2003/10/04 03:55:46 jjanke Exp $
32  */

33 public final class Log implements Serializable
34 {
35     /** Error Level */
36     private static final int l0_Error = 0;
37     /** User Level */
38     public static final int l1_User = 1;
39     /** Sub program Level */
40     public static final int l2_Sub = 2;
41     /** Utility Level */
42     public static final int l3_Util = 3;
43     /** Data Level */
44     public static final int l4_Data = 4;
45     /** Detail Data Level */
46     public static final int l5_DData = 5;
47     /** Database Level */
48     public static final int l6_Database = 6;
49
50     /** Used trace level */
51     private static int s_traceLevel = 0;
52     /** Output device */
53     private static PrintWriter s_out = null;
54     /** Do we write to the console */
55     private static boolean s_console = false;
56
57     /** Log4J */
58     private static Logger s_log = Logger.getCLogger(Log.class);
59
60
61     /**
62      * Initiate log writing to System.out with the log level of the environment
63      *
64      * @see org.compiere.util.Ini
65      */

66     public static void initLog ()
67     {
68         initLog(false, -1);
69     } // initLog
70

71     /**
72      * Initiate log writing to temp file or System.out
73      *
74      * @param writeToTempLogFile if true, a trace wile will be created in the local temp directory
75      * @param traceLevel Set level from 0 (only errors) to 9 (everything) - if -1 the tracelevel of the user environment is used
76      * @see org.compiere.util.Ini
77      */

78     public static void initLog (boolean writeToTempLogFile, int traceLevel)
79     {
80     // System.out.println("Log.initLog - ToTemp=" + writeToTempLogFile);
81
// TraceLevel
82
int level = 0;
83         try
84         {
85             if (traceLevel < 0)
86                 level = Integer.parseInt(Ini.getProperty(Ini.P_DEBUGLEVEL));
87             else
88                 level = traceLevel;
89             if (level < 0)
90                 level = 0;
91         }
92         catch (Exception JavaDoc e)
93         {
94             System.err.println("Log.initLog - Cannot parse Trace level - Set to 9");
95             level = 9;
96         }
97         setTraceLevel(level);
98
99         // Write to Temp file or System.out
100
if (Ini.isClient())
101             setOutput(writeToTempLogFile);
102
103         // Database tracing
104
if (level < l6_Database)
105             return;
106     // traceJDBC(true);
107

108         // Print System Properties
109
if (level < 10)
110             return;
111         printProperties (System.getProperties(), "System", writeToTempLogFile);
112     } // initDebug
113

114     /**
115      * Print Properties
116      *
117      * @param p Properties to print
118      * @param description Description of properties
119      * @param logLevel10 if true write to Log with level 10, else to System.out
120      */

121     public static void printProperties (Properties p, String JavaDoc description, boolean logLevel10)
122     {
123         if (p == null)
124             return;
125         if (logLevel10)
126             Log.trace(9, "Log.printProperties = " + description, "Size=" + p.size()
127                 + ", Hash=" + p.hashCode() + "\n" + getLocalHost());
128         else
129             System.out.println("Log.printProperties = " + description + ", Size=" + p.size()
130                 + ", Hash=" + p.hashCode() + "\n" + getLocalHost());
131
132         Object JavaDoc[] pp = p.keySet().toArray();
133         Arrays.sort(pp);
134         for (int i = 0; i < pp.length; i++)
135         {
136             String JavaDoc key = pp[i].toString();
137             String JavaDoc value = p.getProperty(key);
138             if (logLevel10)
139                 Log.trace(10, key, value);
140             else
141                 System.out.println(" " + key + " = " + value);
142         }
143     } // printProperties
144

145     /**
146      * Create System Info
147      * @param sb Optional string buffer
148      * @param ctx Environment
149      * @return System Info
150      */

151     public static StringBuffer JavaDoc getInfo (StringBuffer JavaDoc sb, Properties ctx)
152     {
153         if (sb == null)
154             sb = new StringBuffer JavaDoc();
155         if (ctx == null)
156             ctx = Env.getCtx();
157         // Envoronment
158
CConnection cc = CConnection.get();
159         sb.append("\n\n===Environment===").append(Compiere.getCheckSum())
160             .append(Compiere.getSummaryAscii())
161             .append("\n").append(getLocalHost())
162             .append("\n").append(cc.toStringLong())
163             .append("\n").append(cc.getInfo());
164         // Context
165
sb.append("\n\n===Context===");
166         String JavaDoc[] context = Env.getEntireContext(ctx);
167         Arrays.sort(context);
168         for (int i = 0; i < context.length; i++)
169             sb.append("\n").append(context[i]);
170         // System
171
sb.append("\n\n===System===");
172         Object JavaDoc[] pp = System.getProperties().keySet().toArray();
173         Arrays.sort(pp);
174         for (int i = 0; i < pp.length; i++)
175         {
176             String JavaDoc key = pp[i].toString();
177             String JavaDoc value = System.getProperty(key);
178             sb.append("\n").append(key).append("=").append(value);
179         }
180         return sb;
181     } // getInfo
182

183     /**
184      * Get Localhost
185      * @return local host
186      */

187     private static String JavaDoc getLocalHost()
188     {
189         try
190         {
191             InetAddress id = InetAddress.getLocalHost();
192             return id.toString();
193         }
194         catch (Exception JavaDoc e)
195         {
196             error("Log.getLocalHost", e);
197         }
198         return "-no local host info -";
199     } // getLocalHost
200

201     /*************************************************************************/
202
203     /**
204      * Output a trace if the threshold level is high enough
205      *
206      * @param level Trace Level
207      * @param message Information
208      * @param addlInfo Additional Information
209      */

210     public static void trace (int level, String JavaDoc message, Object JavaDoc addlInfo)
211     {
212         if (level < 0 || level > s_traceLevel)
213             return;
214         StringBuffer JavaDoc sb = new StringBuffer JavaDoc (message);
215         sb.append(" - ");
216         if (addlInfo == null)
217             sb.append("null");
218         else
219             sb.append(addlInfo);
220         trace (level, sb.toString());
221     } // trace
222

223     /**
224      * Output a formatted trace message "{0}, {1,number}, {2}" if the threshold level is high enough
225      *
226      * @param level Trace Lebel
227      * @param message Information like "{0}, {1,number}, {2}"
228      * @param parameter addition info like new Object[] { }
229      */

230     public static void trace (int level, String JavaDoc message, Object JavaDoc[] parameter)
231     {
232         if (level < 0 || level > s_traceLevel || message == null)
233             return;
234         //
235
String JavaDoc msg = null;
236         try
237         {
238             msg = MessageFormat.format(message, parameter);
239         }
240         catch (Exception JavaDoc e)
241         {
242             System.err.println("Log.trace - invalid message - " + e.getMessage());
243             msg = message;
244         }
245         trace(level, msg);
246     } // trace
247

248     /**
249      * Trace to output if the threshold level is high enough
250      *
251      * @param level Trace Level
252      * @param msg Information
253      */

254     public static void trace (int level, Object JavaDoc msg)
255     {
256         if (level < 0 || level > s_traceLevel || msg == null)
257             return;
258         if (!Ini.isClient())
259         {
260             if (level == l0_Error)
261                 s_log.error(msg);
262             else if (level == l1_User || level == l2_Sub)
263                 s_log.info(msg);
264             else
265                 s_log.debug(msg);
266             return;
267         }
268
269         String JavaDoc message = msg.toString();
270         if (message.length() == 0)
271             return;
272         //
273
Timestamp ts = new Timestamp(System.currentTimeMillis());
274         String JavaDoc tstr = ts.toString() + "00";
275         StringBuffer JavaDoc sb = new StringBuffer JavaDoc ();
276         // Error
277
if (level == 0)
278         { // 12:12:12.123
279
sb.append("===========> ").append(message);
280             if (Ini.isClient())
281                 Toolkit.getDefaultToolkit().beep();
282         }
283         // Std Message
284
else
285         {
286             sb.append(tstr.substring(11, 23));
287             // + " [" + level + "]"
288
sb.append(" ".substring(0, level << 1)).append(message);
289         }
290
291         // Make sure we always can print
292
if (s_out == null)
293             setOutput(false);
294
295         // Print it
296
s_out.println(sb.toString());
297
298         // Additional Error Info
299
if (level == l0_Error)
300         {
301             String JavaDoc errMsg = ts.toString() + " " + message;
302             if (!s_console)
303                 System.err.println (sb.toString());
304             // write to db
305
writeDBLog(".", errMsg);
306             // beep
307
if (Ini.isClient())
308                 Toolkit.getDefaultToolkit().beep();
309         }
310     } // trace
311

312     /**
313      * Simple Info output to out for temporary test purposes
314      *
315      * @deprecated
316      * @param message Information
317      */

318     public static void print (String JavaDoc message)
319     {
320         if (s_out != null)
321             s_out.println(message);
322     } // info
323

324     /**
325      * Signal Error
326      *
327      * @param description Information
328      * @return true (indicator that method cannot be deleted)
329      */

330     public static boolean error (String JavaDoc description)
331     {
332         if (Ini.isClient())
333             trace (l0_Error, description);
334         else
335             s_log.error(description);
336         return true;
337     } // error
338

339     /**
340      * Signal Error
341      *
342      * @param description Information
343      * @param e Exception
344      * @return true (indicator that method cannot be deleted)
345      */

346     public static boolean error (String JavaDoc description, Exception JavaDoc e)
347     {
348         if (!Ini.isClient())
349         {
350             s_log.error (description, e);
351             return true;
352         }
353
354         StringBuffer JavaDoc output = new StringBuffer JavaDoc();
355         output.append(description).append(" - ");
356         output.append(e.getClass().getName()).append(": ");
357         if (e.getMessage() == null)
358             output.append(e.toString());
359         else
360             output.append(e.getMessage());
361         if (!(e instanceof SQLException))
362         {
363             StackTraceElement JavaDoc[] elements = e.getStackTrace();
364             for (int i = 0; i < 3 || i < elements.length; i++)
365                 output.append(" > ").append(elements[i].toString());
366         }
367         trace (l0_Error, output.toString());
368         e.printStackTrace(s_out);
369         return true;
370     } // error
371

372     /**
373      * Signal Error
374      *
375      * @param description Information
376      * @param sqlEx Exception
377      * @return true (indicator that method cannot be deleted)
378      */

379     public static boolean error(String JavaDoc description, SQLException sqlEx)
380     {
381         if (description == null || sqlEx == null || description.length() == 0)
382             throw new IllegalArgumentException JavaDoc("DB.printException - required parameter missing");
383         if (!Ini.isClient())
384         {
385             s_log.error(description, sqlEx);
386             return true;
387         }
388         error("SQL Exception: " + description); // initial log
389
if (sqlEx == null)
390             return true;
391         //
392
SQLException ex = sqlEx;
393         while (ex != null)
394         {
395             StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
396             buffer.append(ex.getMessage());
397             buffer.append("; State=").append(ex.getSQLState()).append("; ErrorCode=").append(ex.getErrorCode());
398             error(buffer.toString()); // additional log infos
399
ex = ex.getNextException();
400         }
401         return true;
402     } // error
403

404     /*************************************************************************/
405
406     /**
407      * Trace JDBC
408      *
409      * @param traceDB if true, enable DriverManaer output
410      */

411     public static void traceJDBC (boolean traceDB)
412     {
413         System.out.println("Log.traceJDBC = " + traceDB);
414         if (traceDB && getTraceLevel() >= l6_Database)
415             DriverManager.setLogWriter(s_out); // lists Statements
416
else
417             DriverManager.setLogWriter(null);
418     } // traceJDBC
419

420     /**
421      * Set Trace Level
422      *
423      * @param traceLevel new TraceLevel
424      */

425     public static void setTraceLevel(int traceLevel)
426     {
427         if (traceLevel == s_traceLevel)
428             return;
429         s_traceLevel = traceLevel;
430         Ini.setProperty(Ini.P_DEBUGLEVEL, s_traceLevel);
431         // Init Log4J
432
if (Ini.isClient())
433         {
434             if (traceLevel == l0_Error)
435                 Logger.getRootLogger().setLevel(org.apache.log4j.Level.ERROR);
436             else if (traceLevel == l1_User || traceLevel == l3_Util)
437                 Logger.getRootLogger().setLevel(org.apache.log4j.Level.INFO);
438             else
439                 Logger.getRootLogger().setLevel(org.apache.log4j.Level.ALL);
440         }
441         s_log.info("setTraceLevel - " + traceLevel);
442     } // setTraceLevel
443

444     /**
445      * Return Trace Level
446      * @return Trace Level
447      */

448     public static int getTraceLevel()
449     {
450         return s_traceLevel;
451     } // getTraceLevel
452

453     /**
454      * Is it at least Trace Level
455      * @param level test level
456      * @return true if level less or equal tarce level
457      */

458     public static boolean isTraceLevel(int level)
459     {
460         return level <= s_traceLevel;
461     } // getTraceLevel
462

463     /*************************************************************************/
464
465     /**
466      * Set Output
467      * @param out PrintWriter for logs
468      */

469     public static void setOutput(PrintWriter out)
470     {
471         if (out == null)
472             throw new IllegalArgumentException JavaDoc("Log.setOutput - PrintWriter cannot be null");
473
474         // Close old
475
if (s_out != null)
476         {
477             s_out.flush();
478             s_out.close();
479         }
480         // Set new
481
s_out = out;
482         s_console = false;
483         if (getTraceLevel() > 0)
484             System.out.println("Log.setOutput - PW=" + s_out.toString());
485     } // setOutput
486

487     /**
488      * Set Output to file
489      * @param filename FileName for log output
490      */

491     public static void setOutput(String JavaDoc filename)
492     {
493         if (filename == null || filename.length() == 0)
494             throw new IllegalArgumentException JavaDoc("Log.setOutput - Invalid filename");
495
496         // Close old
497
if (s_out != null)
498         {
499             s_out.flush();
500             s_out.close();
501         }
502         // Create new
503
try
504         {
505             Time t = new Time(System.currentTimeMillis());
506             String JavaDoc logName = filename + t;
507             FileWriter fw = new FileWriter(logName);
508             s_out = new PrintWriter(fw, true);
509             s_console = false;
510             if (getTraceLevel() > 0)
511                 System.out.println("Log.setOutput - File=" + logName);
512         }
513         catch (Exception JavaDoc e)
514         {
515             System.err.println("========> Log.setOutput - " + e.getMessage());
516             s_out = new PrintWriter(System.out, true);
517             s_console = true;
518             if (getTraceLevel() > 0)
519                 System.out.println("Log.setOutput - C=" + s_out.toString());
520         }
521     } // setOutput
522

523     /**
524      * Write Logfile in temporary directory
525      * @param writeToTempLogFile if true temporary file is used for log, otherwise System.out
526      */

527     public static void setOutput (boolean writeToTempLogFile)
528     {
529         // Close old
530
if (s_out != null)
531         {
532             s_out.flush();
533             s_out.close();
534         }
535
536         try
537         {
538             if (writeToTempLogFile)
539             {
540                 String JavaDoc dirName = Ini.getProperty(Ini.P_TEMP_DIR);
541                 File tempDir = new File(dirName);
542                 File tempFile = File.createTempFile("Compiere", ".log", tempDir);
543                 s_out = new PrintWriter(new FileOutputStream(tempFile), true); // autoFlush
544
s_console = false;
545                 if (getTraceLevel() > 0)
546                     System.out.println("Log.setOutput - File=" + tempFile.getAbsolutePath());
547             }
548             else
549             {
550                 s_out = new PrintWriter(System.out, true);
551                 s_console = true;
552             // if (getTraceLevel() > 0)
553
// System.out.println("Log.setOutput - C=" + s_out.toString());
554
}
555         }
556         catch (IOException e)
557         {
558             System.err.println("========> Log.setOutput - " + e.getMessage());
559             s_out = new PrintWriter(System.out, true);
560             s_console = true;
561         // System.out.println("Log.setOutput - C=" + s_out.toString());
562
}
563     } // setOutput
564

565
566     /*************************************************************************/
567
568     /** Last Error Message */
569     private static ValueNamePair s_lastError = null;
570
571     /**
572      * Set and issue Error and save as ValueNamePair
573      * @param AD_Message message key
574      * @param message clear text message
575      * @return true (to avoid removal of method)
576      */

577     public static boolean saveError (String JavaDoc AD_Message, String JavaDoc message)
578     {
579         return saveError (AD_Message, message, true);
580     } // setError
581

582
583     /**
584      * Set Error and save as ValueNamePair
585      * @param AD_Message message key
586      * @param message clear text message
587      * @param issueError print error message (default true)
588      * @return true (to avoid removal of method)
589      */

590     public static boolean saveError (String JavaDoc AD_Message, String JavaDoc message, boolean issueError)
591     {
592         s_lastError = new ValueNamePair (AD_Message, message);
593         // print it
594
if (issueError)
595             error(AD_Message + " - " + message);
596         return true;
597     } // setError
598

599     /**
600      * Get Error from Stack
601      * @return AD_Message as Value and Message as String
602      */

603     public static ValueNamePair retrieveError()
604     {
605         ValueNamePair vp = s_lastError;
606         s_lastError = null;
607         return vp;
608     } // getError
609

610
611     /*************************************************************************/
612
613     /**
614      * Write to Database
615      * @param summary name/title
616      * @param msg Database Message
617      */

618     protected static void writeDBLog (String JavaDoc summary, String JavaDoc msg)
619     {
620         // Nothing there
621
if (msg == null || msg.length() == 0)
622             return;
623         // Is there a DB connection?
624
if (!DB.isConnected())
625             return;
626
627         // Don't store Error messages about AD_Error
628
if (msg.indexOf("AD_Error") != -1)
629             return;
630         // Get Context
631
Properties ctx = Env.getCtx();
632         //
633
StringBuffer JavaDoc sql = new StringBuffer JavaDoc();
634         try
635         {
636             sql.append("INSERT INTO AD_Error "
637                 + "(AD_Error_ID, AD_Client_ID, AD_Org_ID, CreatedBy, UpdatedBy,"
638                 + "Name, Code, AD_Language) VALUES (");
639             sql.append("AD_Error_Seq.nextval,"); // AD_Error_ID
640
sql.append(Env.getContextAsInt(ctx, 0, "AD_Client_ID")).append(",");// AD_Client_ID
641
sql.append(Env.getContextAsInt(ctx, 0, "AD_Org_ID")).append(","); // AD_Org_ID
642
sql.append(Env.getContextAsInt(ctx, "#AD_User_ID")).append(","); // CreatedBy
643
sql.append(Env.getContextAsInt(ctx, "#AD_User_ID")).append(","); // UpdatedBy
644
sql.append(DB.TO_STRING(summary)).append(","); // Name
645
sql.append(DB.TO_STRING(msg, 2000)).append(","); // Code
646
sql.append("'").append(Env.getAD_Language(ctx)).append("')"); // AD_Language
647

648             String JavaDoc sqlExec = DB.getDatabase().convertStatement(sql.toString());
649             // Get standard RW connection
650
Connection con = DB.getConnectionRW();
651             if (con == null)
652             {
653                 System.err.println("===========> Log.writeDB - No Connection - Error not logged in DB -");
654                 System.err.println(msg);
655                 return;
656             }
657             Statement stmt = con.createStatement();
658             stmt.executeUpdate(sqlExec);
659             stmt.close(); // cursor not closed, if statement fails
660
}
661         catch (Exception JavaDoc e)
662         {
663             System.err.println("===========> Log.writeDB - Message=" + msg + " - Error: " + e);
664         }
665     } // writeDB
666

667 } // Debug
668

669
Popular Tags