I am using java.util logging classes to create a rolling file appender. I want to create a log reader that reads from these logs as data is written to them.
The rolling log appender code works fine on its own. But once I start the reader thread new files are not created i.e. if rolling log appender is set to use 5 files it will create 1og.0, log.1, log.2 and so on but if the reader thread starts then it will only create log.0 no other files are created. I notice this in both java logging and log4j.
I am using nio to read in the log reader. So my doubt is, is creating another FileChannel on the same file creating some problem? or have I missed some basic nio stuff here that is causing problems.
here is the code..
public class Test {
private static final long initialTime = System.currentTimeMillis();
private static Logger logger = Logger.getLogger(Test.class.getName());
public static void main(String[] args) {
logger.setLevel(Level.INFO);
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(
new File(System.getProperty("user.dir")+File.separator+"input.dat"))));
FileHandler handler = new FileHandler("log/test.log", 1024, 5, true);
handler.setFormatter(new SimpleFormatter());
开发者_如何学JAVA logger.addHandler(handler);
logger.setUseParentHandlers(false);
//If I comment the next two lines the rolling appender works as expected both in java logging
//and when using log4j. however once I start the log reader only one file is created.
Thread logReader = new Thread(new LogReader("log/test.log.0"));
logReader.start();
while(reader.ready())
{
String strToLog = reader.readLine();
logger.info(strToLog);
//Only want to run this for 10 secs.
if(System.currentTimeMillis() - initialTime > 10000)
System.exit(0);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
}
}
}
class LogReader implements Runnable {
private final int BUFFER_SIZE = 1024;
private RandomAccessFile file;
private FileChannel chan;
private long offset;
private ByteBuffer buf;
private Charset charset = Charset.forName("UTF-8");
private String filename = "output.log";
public LogReader(String logfile) throws IOException {
System.out.println("Starting log reader from " + logfile);
file = new RandomAccessFile(logfile, "r");
offset = file.length();
chan = file.getChannel();
chan.position(offset);
buf = ByteBuffer.allocateDirect(BUFFER_SIZE);
System.out.println("Started log reader from " + logfile);
}
public void run() {
//Even if I have nothing here..the problem exists..
}
}
I think there might be some concurrency issues with RandomAccessFile
.
I suggest you use a different class for reading the file. E.g. java.io.FileReader
精彩评论