Log.java
Upload User: demmber
Upload Date: 2007-12-22
Package Size: 717k
Code Size: 9k
Category:

Java Develop

Development Platform:

Java

  1. /*
  2.  * @(#)Log.java 0.3-3 06/05/2001
  3.  *
  4.  *  This file is part of the HTTPClient package
  5.  *  Copyright (C) 1996-2001 Ronald Tschal鋜
  6.  *
  7.  *  This library is free software; you can redistribute it and/or
  8.  *  modify it under the terms of the GNU Lesser General Public
  9.  *  License as published by the Free Software Foundation; either
  10.  *  version 2 of the License, or (at your option) any later version.
  11.  *
  12.  *  This library is distributed in the hope that it will be useful,
  13.  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  14.  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  15.  *  Lesser General Public License for more details.
  16.  *
  17.  *  You should have received a copy of the GNU Lesser General Public
  18.  *  License along with this library; if not, write to the Free
  19.  *  Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  20.  *  MA 02111-1307, USA
  21.  *
  22.  *  For questions, suggestions, bug-reports, enhancement-requests etc.
  23.  *  I may be contacted at:
  24.  *
  25.  *  ronald@innovation.ch
  26.  *
  27.  *  The HTTPClient's home page is located at:
  28.  *
  29.  *  http://www.innovation.ch/java/HTTPClient/ 
  30.  *
  31.  */
  32. package HTTPClient;
  33. import java.io.IOException;
  34. import java.io.Writer;
  35. import java.io.FileWriter;
  36. import java.io.PrintWriter;
  37. import java.io.OutputStreamWriter;
  38. import java.io.ByteArrayOutputStream;
  39. import java.util.Calendar;
  40. import java.util.TimeZone;
  41. /**
  42.  * This is a simple logger for the HTTPClient. It defines a number of
  43.  * "facilities", each representing one or more logically connected classes.
  44.  * Logging can be enabled or disabled on a per facility basis. Furthermore, the
  45.  * logging output can be redirected to any desired place, such as a file or a
  46.  * buffer; by default all logging goes to <var>System.err</var>.
  47.  *
  48.  * <P>All log entries are preceded by the name of the currently executing
  49.  * thread, enclosed in {}'s, and the current time in hours, minutes, seconds,
  50.  * and milliseconds, enclosed in []'s. Example:
  51.  * <tt>{Thread-5} [20:14:03.244] Conn:  Sending Request</tt>
  52.  *
  53.  * <P>When the class is loaded, two java system properties are read:
  54.  * <var>HTTPClient.log.file</var> and <var>HTTPClient.log.mask</var>. The first
  55.  * one, if set, causes all logging to be redirected to the file with the given
  56.  * name. The second one, if set, is used for setting which facilities are
  57.  * enabled; the value must be the bitwise OR ('|') of the values of the desired
  58.  * enabled facilities. E.g. a value of 3 would enable logging for the
  59.  * HTTPConnection and HTTPResponse, a value of 16 would enable cookie related
  60.  * logging, and a value of 8 would enable authorization related logging; a
  61.  * value of -1 would enable logging for all facilities. By default logging is
  62.  * disabled.
  63.  *
  64.  * @version 0.3-3  06/05/2001
  65.  * @author Ronald Tschal鋜
  66.  * @since V0.3-3
  67.  */
  68. public class Log
  69. {
  70.     /** The HTTPConnection facility (1) */
  71.     public static final int CONN  = 1 << 0;
  72.     /** The HTTPResponse facility (2) */
  73.     public static final int RESP  = 1 << 1;
  74.     /** The StreamDemultiplexor facility (4) */
  75.     public static final int DEMUX = 1 << 2;
  76.     /** The Authorization facility (8) */
  77.     public static final int AUTH  = 1 << 3;
  78.     /** The Cookies facility (16) */
  79.     public static final int COOKI = 1 << 4;
  80.     /** The Modules facility (32) */
  81.     public static final int MODS  = 1 << 5;
  82.     /** The Socks facility (64) */
  83.     public static final int SOCKS = 1 << 6;
  84.     /** The ULRConnection facility (128) */
  85.     public static final int URLC  = 1 << 7;
  86.     /** All the facilities - for use in <code>setLogging</code> (-1) */
  87.     public static final int ALL   = ~0;
  88.     private static final String NL     = System.getProperty("line.separator");
  89.     private static final long   TZ_OFF;
  90.     private static int     facMask     = 0;
  91.     private static Writer  logWriter   = new OutputStreamWriter(System.err);
  92.     private static boolean closeWriter = false;
  93.     static
  94.     {
  95. Calendar now = Calendar.getInstance();
  96. TZ_OFF = TimeZone.getDefault().getOffset(now.get(Calendar.ERA),
  97.  now.get(Calendar.YEAR),
  98.  now.get(Calendar.MONTH),
  99.  now.get(Calendar.DAY_OF_MONTH),
  100.  now.get(Calendar.DAY_OF_WEEK),
  101.  now.get(Calendar.MILLISECOND));
  102. try
  103. {
  104.     String file = System.getProperty("HTTPClient.log.file");
  105.     if (file != null)
  106.     {
  107. try 
  108.     { setLogWriter(new FileWriter(file), true); }
  109. catch (IOException ioe)
  110. {
  111.     System.err.println("failed to open file log stream `" +
  112.        file + "': " + ioe);
  113. }
  114.     }
  115. }
  116. catch (Exception e)
  117.     { }
  118. try
  119. {
  120.     facMask = Integer.getInteger("HTTPClient.log.mask", 0).intValue();
  121. }
  122. catch (Exception e)
  123.     { }
  124.     }
  125.     // Constructors
  126.     /**
  127.      * Not meant to be instantiated
  128.      */
  129.     private Log()
  130.     {
  131.     }
  132.     // Methods
  133.     /**
  134.      * Write the given message to the current log if logging for the given facility is
  135.      * enabled.
  136.      *
  137.      * @param facility  the facility which is logging the message
  138.      * @param msg       the message to log
  139.      */
  140.     public static void write(int facility, String msg)
  141.     {
  142. if ((facMask & facility) == 0)
  143.     return;
  144. try
  145. {
  146.     writePrefix();
  147.     logWriter.write(msg);
  148.     logWriter.write(NL);
  149.     logWriter.flush();
  150. }
  151. catch (IOException ioe)
  152. {
  153.     System.err.println("Failed to write to log: " + ioe);
  154.     System.err.println("Failed log Entry was: " + msg);
  155. }
  156.     }
  157.     /**
  158.      * Write the stack trace of the given exception to the current log if logging for the
  159.      * given facility is enabled.
  160.      *
  161.      * @param facility  the facility which is logging the message
  162.      * @param prefix    the string with which to prefix the stack trace; may be null
  163.      * @param t         the exception to log
  164.      */
  165.     public static void write(int facility, String prefix, Throwable t)
  166.     {
  167. if ((facMask & facility) == 0)
  168.     return;
  169. synchronized (Log.class)
  170. {
  171.     if (!(logWriter instanceof PrintWriter))
  172. logWriter = new PrintWriter(logWriter);
  173. }
  174. try
  175. {
  176.     writePrefix();
  177.     if (prefix != null)
  178. logWriter.write(prefix);
  179.     t.printStackTrace((PrintWriter) logWriter);
  180.     logWriter.flush();
  181. }
  182. catch (IOException ioe)
  183. {
  184.     System.err.println("Failed to write to log: " + ioe);
  185.     System.err.print("Failed log Entry was: " + prefix);
  186.     t.printStackTrace(System.err);
  187. }
  188.     }
  189.     /**
  190.      * Write the contents of the given buffer to the current log if logging for
  191.      * the given facility is enabled.
  192.      *
  193.      * @param facility  the facility which is logging the message
  194.      * @param prefix    the string with which to prefix the buffer contents;
  195.      *                  may be null
  196.      * @param buf       the buffer to dump
  197.      */
  198.     public static void write(int facility, String prefix, ByteArrayOutputStream buf)
  199.     {
  200. if ((facMask & facility) == 0)
  201.     return;
  202. try
  203. {
  204.     writePrefix();
  205.     if (prefix != null)
  206. logWriter.write(prefix);
  207.     logWriter.write(NL);
  208.     logWriter.write(new String(buf.toByteArray(), "ISO_8859-1"));
  209.     logWriter.flush();
  210. }
  211. catch (IOException ioe)
  212. {
  213.     System.err.println("Failed to write to log: " + ioe);
  214.     System.err.println("Failed log Entry was: " + prefix);
  215.     System.err.println(new String(buf.toByteArray()));
  216. }
  217.     }
  218.     /**
  219.      * Write a log line prefix of the form 
  220.      * <PRE>
  221.      *  {thread-name} [time]
  222.      * </PRE>
  223.      */
  224.     private static final void writePrefix() throws IOException {
  225. logWriter.write("{" + Thread.currentThread().getName() + "} ");
  226. int mill  = (int) ((System.currentTimeMillis() + TZ_OFF) % (24 * 3600000));
  227. int secs  = mill / 1000;
  228. int mins  = secs / 60;
  229. int hours = mins / 60;
  230. logWriter.write("[" + fill2(hours) + ':' + fill2(mins - hours*60) +
  231. ':' + fill2(secs - mins * 60) + '.' +
  232. fill3(mill - secs * 1000) + "] ");
  233.     }
  234.     private static final String fill2(int num) {
  235. return ((num < 10) ? "0" : "") + num;
  236.     }
  237.     private static final String fill3(int num) {
  238. return ((num < 10) ? "00" : (num < 100) ? "0" : "") + num;
  239.     }
  240.     /**
  241.      * Check whether logging for the given facility is enabled or not.
  242.      *
  243.      * @param facility  the facility to check
  244.      * @return true if logging for the given facility is enable; false otherwise
  245.      */
  246.     public static boolean isEnabled(int facility)
  247.     {
  248. return ((facMask & facility) != 0);
  249.     }
  250.     /**
  251.      * Enable or disable logging for the given facilities.
  252.      *
  253.      * @param facilities the facilities for which to enable or disable logging.
  254.      *                   This is bitwise OR ('|') of all the desired
  255.      *                   facilities; use {@link #ALL ALL} to affect all facilities
  256.      * @param enable     if true, enable logging for the chosen facilities; if
  257.      *                   false, disable logging for them.
  258.      */
  259.     public static void setLogging(int facilities, boolean enable)
  260.     {
  261. if (enable)
  262.     facMask |= facilities;
  263. else
  264.     facMask &= ~facilities;
  265.     }
  266.     /**
  267.      * Set the writer to which to log. By default, things are logged to
  268.      * <var>System.err</var>.
  269.      *
  270.      * @param log           the writer to log to; if null, nothing is changed
  271.      * @param closeWhenDone if true, close this stream when a new stream is set
  272.      *                      again
  273.      */
  274.     public static void setLogWriter(Writer log, boolean closeWhenDone)
  275.     {
  276. if (log == null)
  277.     return;
  278. if (closeWriter)
  279. {
  280.   try
  281.       { logWriter.close(); }
  282.   catch (IOException ioe)
  283.       { System.err.println("Error closing log stream: " + ioe); }
  284. }
  285. logWriter   = log;
  286. closeWriter = closeWhenDone;
  287.     }
  288. }