Avinash
Avinash

Reputation: 195

Simple Logger apache common

I need to write a log to a text file using Apache common simplelog rather than printing it into System.err.

I use FileWriter in write method, it's creating the file but not printing the data from the buffer.

protected void log(int type, Object message, Throwable t) {

    StringBuffer buf = new StringBuffer();


    if(showDateTime) {
        Date now = new Date();
        String dateText;
        synchronized(dateFormatter) {
            dateText = dateFormatter.format(now);
        }
        buf.append(dateText);
        buf.append(" ");
    }


    switch(type) {
        case SimpleLog.LOG_LEVEL_TRACE: buf.append("[TRACE] "); break;
        case SimpleLog.LOG_LEVEL_DEBUG: buf.append("[DEBUG] "); break;
        case SimpleLog.LOG_LEVEL_INFO:  buf.append("[INFO] ");  break;
        case SimpleLog.LOG_LEVEL_WARN:  buf.append("[WARN] ");  break;
        case SimpleLog.LOG_LEVEL_ERROR: buf.append("[ERROR] "); break;
        case SimpleLog.LOG_LEVEL_FATAL: buf.append("[FATAL] "); break;
    }


    if( showShortName) {
        if( shortLogName==null ) {

            shortLogName = logName.substring(logName.lastIndexOf(".") + 1);
            shortLogName =
                shortLogName.substring(shortLogName.lastIndexOf("/") + 1);
        }
        buf.append(String.valueOf(shortLogName)).append(" - ");
    } else if(showLogName) {
        buf.append(String.valueOf(logName)).append(" - ");
    }


    buf.append(String.valueOf(message));


    if(t != null) {
        buf.append(" <");
        buf.append(t.toString());
        buf.append(">");

        java.io.StringWriter sw= new java.io.StringWriter(1024);
        java.io.PrintWriter pw= new java.io.PrintWriter(sw);
        t.printStackTrace(pw);
        pw.close();
        buf.append(sw.toString());
    }


    write(buf);

}



protected void write(StringBuffer buffer) {

      System.err.println(buffer.toString());// want to print to a file rather than to err

     FileWriter file=new FileWriter(new File("d:/log.txt"));
     file.write(buffer.toString());   


}

Upvotes: 0

Views: 222

Answers (2)

Matt
Matt

Reputation: 11815

This defeats the purpose of SimpleLog IMHO. If you want more complicated features, such as writing to a file instead of the console, you're better off plugging in log4j, or just use the jdk logging to back commons-logging. Either approach would keep the file writing options (file name, size limit, rollover, formatting) in configuration instead of in code.

Upvotes: 0

oers
oers

Reputation: 18714

You need to flush the stream:

file.flush()

or if you are really done writing to the file you need to close the writer. :

file.close()

close() flushes the stream before closing.

Upvotes: 1

Related Questions