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 構成でこのクラスをアペンダーとして使用すると、書き込み部分が完了します。読み取り部分では、バイトごとに読み取り、バイトを1つ減らしてから、そこから文字列をロードする必要があります。
幸運を。
DataOutputStreamBufferedOutputStreamとFileOutputStreamを使用してバイナリファイルを書き込みます。ファイルを読み取り不可ではなく機械可読にする必要があると思います。;)
Log4jはテキストファイル用に設計されていますが、のようなログレベルを使用できます。
private static final Log LOG =
static DataOutputStream out = ... FileOutputStream ...
if(LOG.isDebugEnabled()) {
// write a debug log to out
}