问题
I am able to create log files using FileAppender, RollingFileAppender,etc.,
My Problem is that the logs are written as plain text that anyone can read, but I want to register my logs as Binary Files that are not human readable.
Can anyone help me with the suggestion to create a Binary log file for an example code.
回答1:
Its not such a good Idea to do what you wrote, but if you really need to, write an own appender like this:
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.");
}
}
}
Then in your log4j config use this class as appender and you are done with the writing part. for the reading part you again need to read it byte per byte and reduce the byte by one and then load a string from it.
Good luck.
回答2:
I would use DataOutputStream BufferedOutputStream and FileOutputStream to write binary files. I assume you want the files to be machine readable rather than non-readable. ;)
Log4j is designed for text files, however you can use its logging levels like.
private static final Log LOG =
static DataOutputStream out = ... FileOutputStream ...
if(LOG.isDebugEnabled()) {
// write a debug log to out
}
来源:https://stackoverflow.com/questions/6827568/how-to-create-binary-log-file-in-java-using-log4j