Getting Writer error on using TinyLog

350 Views Asked by At

I tried using TinyLog for a sample application to make sure understanding how it works, so that i can use it for my work application.

But, while using i get an exception to type cast the Writer (Compile time error). If i typecast it, it throws runtime error as below.

Code :

import java.io.FileWriter;
import java.io.IOException;

import org.pmw.tinylog.Configurator;
import org.pmw.tinylog.Logger;
import org.pmw.tinylog.writers.ConsoleWriter;
import org.pmw.tinylog.writers.Writer;

public class TestClass {
    public static void main(String[] args) throws IOException {
        Configurator.defaultConfig().writer(new ConsoleWriter()).addWriter((Writer) new FileWriter("data.txt")).activate();
        Logger.info("welcome to tinylog logger.....");
    }
}

Error :-

Exception in thread "main" java.lang.ClassCastException: java.io.FileWriter cannot be cast to org.pmw.tinylog.writers.Writer at TestClass.main(TestClass.java:12)

Please help us :).

1

There are 1 best solutions below

0
On

You can fix it easily. Just import org.pmw.tinylog.writers.FileWriter instead of java.io.FileWriter. The class java.io.FileWriter is the file writer of the JVM, but you need tinylog's file writer.

Afterwards you can remove the class cast "(Writer)" as org.pmw.tinylog.writers.FileWriter is an implementation of the interface org.pmw.tinylog.writers.Writer. However the class java.io.FileWriter does not implement the interface org.pmw.tinylog.writers.Writer. Therefor the reported ClassCastException has been thrown.

import org.pmw.tinylog.Configurator;
import org.pmw.tinylog.Logger;
import org.pmw.tinylog.writers.ConsoleWriter;
import org.pmw.tinylog.writers.FileWriter;

public class TestClass {
    public static void main(String[] args) {
        Configurator.defaultConfig().writer(new ConsoleWriter()).addWriter(new FileWriter("data.txt")).activate();
        Logger.info("welcome to tinylog logger.....");
    }
}