如何使用Log4J在Java中创建二进制日志文件 [英] How to Create Binary Log File in Java using Log4J

查看:313
本文介绍了如何使用Log4J在Java中创建二进制日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够使用FileAppender,RollingFileAppender等创建日志文件,

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.

推荐答案

做您写的内容不是一个好主意,但是如果您确实需要,请编写一个自己的附加程序,如下所示:

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.");
        }
    }

}

然后在您的log4j配置中,使用此类作为追加器,编写部分就完成了.对于阅读部分,您再次需要按字节读取它,并将字节减少一个,然后从中装入一个字符串.

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.

祝你好运.

这篇关于如何使用Log4J在Java中创建二进制日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆