我正在使用java.util日志记录类来创建滚动文件appender。我想创建一个日志阅读器,当数据写入它们时从这些日志中读取。
滚动日志appender代码可以自行运行。但是一旦我启动读取器线程,就不会创建新文件,即如果将滚动日志appender设置为使用5个文件,它将创建1og.0,log.1,log.2等等但是如果读取器线程启动则它将仅创建log.0没有创建其他文件。我在java logging和log4j中都注意到了这一点。
我正在使用nio来读取日志阅读器。所以我的疑问是,在同一个文件上创建另一个FileChannel会产生一些问题吗?或者我错过了一些导致问题的基本nio内容。
这是代码..
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());
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..
}
}
答案 0 :(得分:0)
我认为RandomAccessFile
可能存在一些并发问题。
我建议您使用其他类来读取文件。例如。 java.io.FileReader