我可以使用 FileAppender、RollingFileAppender 等创建日志文件,
我的问题是日志被写成任何人都可以阅读的纯文本,但我想将我的日志注册为人类不可读的二进制文件。
任何人都可以帮助我提出为示例代码创建二进制日志文件的建议。
做你写的东西不是一个好主意,但如果你真的需要,写一个像这样的自己的附加程序:
package de.steamnet.loggingUtils;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
public class BinaryAppender extends AppenderSkeleton {
FileOutputStream fout;
public BinaryAppender() throws FileNotFoundException {
fout = new FileOutputStream("/tmp/somefile.log.bin");
}
@Override
protected void append(LoggingEvent le) {
String origMessage = le.getLoggerName() + " said: " + le.getMessage();
byte[] obscure = origMessage.getBytes();
for(int ii = 0; ii < obscure.length; ii++) {
if(obscure[ii] == Byte.MAX_VALUE) {
obscure[ii] = Byte.MIN_VALUE;
} else {
obscure[ii] = (byte)(obscure[ii] +1); // thats a really bad idea to create 'nonesense stuff' that way!
}
}
try {
fout.write(obscure);
} catch (IOException ex) {
System.out.println("too bad. File writer bombed.");
}
}
@Override
public boolean requiresLayout() {
return false; // we do all layouting in here.
}
@Override
public void close() {
try {
fout.close();
} catch (IOException ex) {
System.out.println("too bad. could not close it.");
}
}
}
然后在你的 log4j 配置中使用这个类作为 appender,你就完成了写作部分。对于阅读部分,您再次需要逐字节读取它并将字节减少一个,然后从中加载一个字符串。
祝你好运。
我会使用 DataOutputStream BufferedOutputStream 和 FileOutputStream 来编写二进制文件。我假设您希望文件是机器可读的而不是不可读的。;)
Log4j 是为文本文件设计的,但是你可以使用它的日志级别。
private static final Log LOG =
static DataOutputStream out = ... FileOutputStream ...
if(LOG.isDebugEnabled()) {
// write a debug log to out
}