001: package com.xoetrope.service;
002:
003: import java.io.IOException;
004: import java.io.OutputStreamWriter;
005: import java.util.concurrent.BlockingQueue;
006: import java.util.concurrent.LinkedBlockingQueue;
007: import net.xoetrope.xui.XProject;
008: import net.xoetrope.xui.XProjectManager;
009:
010: /**
011: * A logging service implmentation. This class is a singleton.
012: * <p>License: This class is part of a commercial software release. Please see the
013: * license.txt file that ships with the product for further details.</p>
014: *
015: * <p> Copyright (c) Xoetrope Ltd., 2001-2006, This software is licensed under
016: * the GNU Public License (GPL), please see license.txt for more details. If
017: * you make commercial use of this software you must purchase a commercial
018: * license from Xoetrope.</p>
019: * <p> $Revision: 1.7 $</p>
020: */
021: public class LogWriter implements Runnable {
022: private static LogWriter logWriter;
023: private OutputStreamWriter osw;
024: private BlockingQueue msgQ;
025:
026: /**
027: * The owner project and the context in which this object operates.
028: */
029: protected XProject currentProject = XProjectManager
030: .getCurrentProject();
031:
032: private LogWriter() {
033: msgQ = new LinkedBlockingQueue();
034:
035: new Thread(this ).start();
036: }
037:
038: /**
039: * Gets an instance of the LogWriter.
040: */
041: public static LogWriter getInstance() {
042: if (logWriter != null)
043: return logWriter;
044:
045: return logWriter = new LogWriter();
046: }
047:
048: /**
049: * Generates a new line in the log file.
050: * @param name the name/qualifier of the log entry
051: * @param value the output message
052: */
053: public void log(String name, String value) {
054: try {
055: String message = "[" + name + "] " + value + "\n";
056: msgQ.put(message);
057: } catch (InterruptedException ex) {
058: ex.printStackTrace();
059: }
060: }
061:
062: public void open() {
063: try {
064: if (osw == null)
065: osw = new OutputStreamWriter(currentProject
066: .getOutputStream(currentProject
067: .getStartupParam("logfile")));
068: } catch (Exception ex) {
069: }
070: }
071:
072: /**
073: * Closes the output stream.
074: */
075: public void close() {
076: try {
077: if (osw != null) {
078: osw.flush();
079: osw.close();
080: }
081: } catch (IOException ex) {
082: }
083: }
084:
085: public void run() {
086: try {
087: if (osw == null)
088: open();
089:
090: while (true) {
091: String msg = (String) msgQ.take();
092: try {
093: osw.write(msg + "\n");
094: } catch (IOException e) {
095: e.printStackTrace();
096: }
097: }
098: } catch (InterruptedException e) {
099: e.printStackTrace();
100: }
101: }
102: }
|