Re: PrintStream to Writer

Discussion in 'Java' started by Harald Hein, Aug 20, 2003.

  1. Harald Hein

    Harald Hein Guest

    "karl wettin" wrote:

    >
    > Java programmers,
    >
    > I've wrote this software that prints output to a PrintStream (usually
    > System.err), but from time to time I would like to send the output to
    > a Writer (ServletResponse.getWriter()) instead.


    Change your logic. Write your software so that it always writes using a
    Writer. In case you need to write to an OutputStream, use an
    OutputStreamWriter.

    Writers are newer than OutputStreams (added in Java 1.1). Because of
    this, Writers know about OutputStreams, but OutputStreams don't know
    anything about Writers. So the only bridge between them is a Writer
    (OutputStreamWriter) that knows about an output stream.

    > {

    // > PrintStream out=System.err;
    Writer out = OutputStreamWriter(System.err);

    >
    > void someMethod(ServletResponse reponse)
    > {

    // > this.out = new SomeStreamWriterWrapper(response.getWriter());
    this.out = response.getWriter();
    > }
    > }
     
    Harald Hein, Aug 20, 2003
    #1
    1. Advertising

  2. Harald Hein

    Roedy Green Guest

    On 20 Aug 2003 19:44:23 GMT, Harald Hein <> wrote or
    quoted :

    >Change your logic. Write your software so that it always writes using a
    >Writer. In case you need to write to an OutputStream, use an
    >OutputStreamWriter.


    Or better still, use your own class. Then you can change your mind
    and make it do whatever you want, e.g. tee to a log file and the
    console, display in a simulated Jtable console with colour coded
    urgency... I'm willing to share the source code for mine.

    Then there are the heavy duty logging classes that let you decide
    after compilation just how much detail you want. See
    http://mindprod.com/jgloss/log.html

    --
    Canadian Mind Products, Roedy Green.
    Coaching, problem solving, economical contract programming.
    See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
     
    Roedy Green, Aug 20, 2003
    #2
    1. Advertising

  3. Harald Hein

    karl wettin Guest

    On Wed, 20 Aug 2003 20:45:11 GMT
    Roedy Green <> wrote:

    > On 20 Aug 2003 19:44:23 GMT, Harald Hein <> wrote or
    > quoted :
    >
    > >Change your logic. Write your software so that it always writes using a
    > >Writer. In case you need to write to an OutputStream, use an
    > >OutputStreamWriter.

    >
    > Or better still, use your own class. Then you can change your mind
    > and make it do whatever you want, e.g. tee to a log file and the
    > console, display in a simulated Jtable console with colour coded
    > urgency... I'm willing to share the source code for mine.
    >
    > Then there are the heavy duty logging classes that let you decide
    > after compilation just how much detail you want. See
    > http://mindprod.com/jgloss/log.html


    Infact, it was my own Logger-class that I needed the Stream/Writer.
    It can be found in my project sf.net/projects/silvertejp

    Here is the current version :

    ---
    package se.snigel.util;

    import java.io.*;
    import java.util.Properties;
    import java.util.HashMap;
    import java.util.StringTokenizer;

    /**
    * User: karl ()
    * Date: Mar 3, 2003
    * Time: 11:57:23 PM
    */
    public final class Logger
    {
    public static final int DEBUG = 0;
    public static final int INFORMATION = 1;
    public static final int WARNING = 2;
    public static final int ERROR = 3;
    public static final int FATAL = 4;

    private int logLevel;
    private static int globalLogLevel = -1; // if greater than -1, all loggers will log at this level.

    private static HashMap loggers = new HashMap();
    private static Logger lastLogger = null;

    private String identifier;

    //private static final Logger selfLogger = new Logger("Logger framework");

    private Logger(String identifier)
    {
    this.identifier = identifier;
    }

    public static Logger getLogger(Object identifier)
    {
    return getLogger(identifier.getClass().getName());
    }

    public static synchronized Logger getLogger(String identifier)
    {
    Logger ret = (Logger) loggers.get(identifier);
    if (ret == null)
    {
    //selfLogger.information("Created inital "+identifier);
    ret = new Logger(identifier);
    loggers.put(identifier, ret);

    if (settings.containsKey(identifier))
    ret.setLogLevel(Integer.parseInt(settings.getProperty(identifier)));
    else
    {
    settings.put(identifier, String.valueOf(FATAL));
    ret.setLogLevel(FATAL);
    }
    }
    else
    ;//selfLogger.debug("Accessed logger "+identifier);

    return ret;
    }

    public int getLogLevel()
    {
    if (globalLogLevel > -1)
    if (logLevel < globalLogLevel)
    return logLevel;
    else
    return globalLogLevel;

    return logLevel;
    }

    public static int getGlobalLogLevel()
    {
    return globalLogLevel;
    }

    public static void setGlobalLogLevel(int globalLogLevel)
    {
    Logger.globalLogLevel = globalLogLevel;
    }

    public void setLogLevel(int logLevel)
    {
    if (logLevel > FATAL)
    this.logLevel = FATAL;
    else if (logLevel < DEBUG)
    this.logLevel = DEBUG;
    else
    this.logLevel = logLevel;
    }


    public static void saveSettings()
    throws IOException
    {
    settings.store(new FileOutputStream(settingsFile), "se.snigel.util.Logger configuration file.");
    }

    private static Properties settings;
    private static File settingsFile;

    private static boolean initialized = false;

    public static void init(String settingsFilePath)
    throws IOException
    {
    // out.println("Initializing logger framework.");

    if (initialized)
    return;

    settingsFile = new File(settingsFilePath);
    if (!settingsFile.exists())
    settingsFile.createNewFile();

    settings = new Properties();
    settings.load(new FileInputStream(settingsFile));

    initialized = true;
    }

    private static Writer defaultOut = new OutputStreamWriter(System.err);

    public static Writer getMyDefaultOut()
    {
    return defaultOut;
    }

    public static void setDefaultOut(Writer defaultOut)
    {
    Logger.defaultOut = defaultOut;
    }

    private Writer out = defaultOut;

    public Writer getOut()
    {
    return out;
    }

    public void setOut(Writer out)
    {
    this.out = out;
    }

    public boolean willLog(int level)
    {
    if (getLogLevel() <= level)
    return true;
    return false;
    }

    public synchronized void log(int level, String value)
    {
    if (willLog(level))
    {
    if (lastLogger != this)
    {
    lastLogger = this;

    try
    {
    out.write('\n');
    }
    catch (IOException e)
    {

    }

    }

    printLog(value, level);
    }
    }

    private static String cr="\n";
    public static void setCR(String cr)
    {
    Logger.cr=cr;
    }

    private void printLog(String value, int level)
    {
    while (value.endsWith("\n"))
    value = value.substring(0, value.length() - 1);

    StringBuffer bufPrefix = new StringBuffer();
    bufPrefix.append(System.currentTimeMillis());
    bufPrefix.append(' ');
    bufPrefix.append(identifier);
    bufPrefix.append(": ");

    bufPrefix.append(" ( ");
    if (level == DEBUG)
    bufPrefix.append("DEBUG");
    else if (level == INFORMATION)
    bufPrefix.append("INFORMATION");
    else if (level == WARNING)
    bufPrefix.append("WARNING");
    else if (level == ERROR)
    bufPrefix.append("ERROR");
    else if (level == FATAL)
    bufPrefix.append("FATAL");
    bufPrefix.append(" ) ");

    StringBuffer bufRet = new StringBuffer();
    int pos = 0;
    int lastPos = 0;
    while ((pos = value.indexOf('\n', pos)) > -1)
    {

    bufRet.append(bufPrefix);
    bufRet.append(value.substring(lastPos, pos));
    bufRet.append('\n');

    pos++; // skip \n
    lastPos = pos;
    }

    bufRet.append(bufPrefix);
    bufRet.append(value.substring(lastPos));
    bufRet.append('\n');


    try
    {
    out.write(bufRet.toString());
    }
    catch (IOException e)
    {

    }

    }

    public void debug(String value)
    {
    log(DEBUG, value);
    }

    public void debug(char value)
    {
    debug(String.valueOf(value));
    }

    public void debug(int value)
    {
    debug(String.valueOf(value));
    }

    public void debug(short value)
    {
    debug(String.valueOf(value));
    }

    public void debug(long value)
    {
    debug(String.valueOf(value));
    }

    public void debug(float value)
    {
    debug(String.valueOf(value));
    }

    public void debug(double value)
    {
    debug(String.valueOf(value));
    }

    public void debug(Object value)
    {
    debug(value.toString());
    }

    public void information(String value)
    {
    log(INFORMATION, value);
    }

    public void warning(String value)
    {
    log(WARNING, value);
    }

    public void error(Exception e)
    {
    log(ERROR, "Error!");
    e.printStackTrace(new PrintWriter(out));
    }

    public void error(String value)
    {
    log(ERROR, value);
    }

    /** Exit JVM */
    public void fatal(String value)
    {
    log(FATAL, value);
    //System.exit(0);
    }

    /** Exit JVM */
    public void fatal(Exception e)
    {
    e.printStackTrace(new PrintWriter(out));
    fatal(e.getMessage());
    }


    }
     
    karl wettin, Aug 20, 2003
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page