首页

Java自定义轻量级日志生成器(方便内置集成及安全)

标签:日志,java,代码,log4j,自定义,logger,集成,高效,     发布时间:2015-06-25   

对于开源的日志生成器(如log4j)不管从输出方式(控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程)或者其他常规使用需求(日志格式、日志信息级别)都已经能完全满足用户需求了,但是对于一些轻量级的集成或者出于安全方面考虑还是需要用户自己实现一套日志生产方式,示例代码如下:

import java.io.File;@b@import java.io.FileWriter;@b@import java.io.IOException;@b@import java.io.RandomAccessFile;@b@import java.io.Serializable;@b@import java.util.Date;@b@@b@import asc.dispatcher.common.Constant;@b@import asc.dispatcher.common.TimeUtil;@b@@b@public class Logger implements Serializable {@b@@b@    private static final long serialVersionUID = -2L;@b@    @b@    private static final String _log_file="dis_patcher";@b@    @b@    private static final String _path=Constant.getDesc("logger_path");@b@    @b@    private static String INFO;@b@    @b@    private static String ERROR;@b@    @b@    private static String WARN;@b@       @b@    public static void info(String message){@b@        INFO=TimeUtil.formatDate(new Date())+" "+Thread.currentThread().getName()+" INFO "+message+"@b@";@b@        appendMethodA(_path+_log_file,INFO);@b@    }@b@    @b@    public static void error(String message){@b@        ERROR=TimeUtil.formatDate(new Date())+" "+Thread.currentThread().getName()+" ERROR "+message+"@b@";@b@        appendMethodA(_path+_log_file,ERROR);@b@    }@b@    @b@    public static void warn(String message){@b@        WARN=TimeUtil.formatDate(new Date())+" "+Thread.currentThread().getName()+" WARN "+message+"@b@";@b@        appendMethodA(_path+_log_file,WARN);@b@    }@b@@b@    public static void appendMethodA(String filePrefix,String content) {@b@        try {@b@            String fileName=filePrefix+"_"+TimeUtil.format2Date(new Date())+".log";@b@            File filePath=new File(_path);@b@            if(!filePath.exists())@b@                filePath.mkdirs();@b@            File _file=new File(fileName);@b@            if(!_file.exists())@b@                _file.createNewFile();@b@            @b@            // 打开一个随机访问文件流,按读写方式@b@            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");@b@            // 文件长度,字节数@b@            long fileLength = randomFile.length();@b@            // 将写文件指针移到文件尾。@b@            randomFile.seek(fileLength);@b@            randomFile.writeBytes(content);@b@            randomFile.close();@b@        } catch (IOException e) {@b@            e.printStackTrace();@b@        }@b@    }@b@@b@    public static void appendMethodB(String fileName, String content) {@b@        try {@b@            // 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件@b@            FileWriter writer = new FileWriter(fileName, true);@b@            writer.write(content);@b@            writer.close();@b@        } catch (IOException e) {@b@            e.printStackTrace();@b@        }@b@    }@b@@b@    public static void main(String[] args) {@b@        Logger.info("test");        @b@    }@b@@b@}