一个不错的日志写入类

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

import java.io.*;

import java.util.*;

public class LogWriter {

private static final String DefalutLogFilePathName="c:\\logtext.log";//默认的日志文件的路径和文件名称

private static LogWriter logwriter; //该类的唯一的实例

private static InputStream fin; //属性配置文件的输入流

private static Properties pro; //class Properties′s supper is Hashtable class

private static PrintWriter out; //output stream

private static String logFileName; //output file name

private LogWriter() {

outInit();//init out put stream,实例化PrintWriter out 对象.

}

/**保存你想保存在日志文件中的信息,实现同步

* out put the message infomation

* @param message infomation

*/

public static synchronized void log(String message) {

if (logwriter == null || (out == null)){

logwriter = new LogWriter();

}

if (out != null) {

out.println(new java.util.Date() + ":" + message);

}

}

/**把异常信息保存在日志文件中,实现同步

* out put the Excetion infomation

* @param message infomation

*/

public static synchronized void log(Exception ex) {

if (logwriter == null || (out == null))

logwriter = new LogWriter();

if (out != null) {

out.println(new java.util.Date() + ":" );

ex.printStackTrace(out);

}

}

/**

*输出文件流的init

*/

private void outInit() {

if (logFileName == null)

logFileName = getlogFileName(); 属性文件中类获得日志文件的路径

try {

if (out == null) {//如果输出i/o没有实例,则生成一个信的

out = new PrintWriter(new FileWriter(logFileName, true), true); ; //

中的FileWriter()中的第二个参数的含义是:是否在文件中追加内容

}

}

catch (IOException ex) {

System.out.println("无法打开日志文件:"+logFileName);

ex.printStackTrace();

out = null;

}

}

/**

*根据配置文件.来获得日志文件的位置

*

* @return logFileName

*/

private String getlogFileName() {

try {

if (pro == null) {

pro = new java.util.Properties();

fin = getClass().getResourceAsStream("log.properties"); //在类的当前位置,查找属性配置文件log.properties

pro.load(fin);//载入配置文件

fin.close();

}

}

catch (IOException ex) {

System.err.println("无法打开属性配置文件: log.properties" );

ex.printStackTrace();

}

return pro.getProperty("logfile",DefalutLogFilePathName);

//据属性值获得日志文件路径,第二个参数是:如果找不到"logfile"标志,就返回的默认值

}

/**你也可以在所有的日志都记录完成的时候,调用该方法,释放资源.

* free all the resouce,this is secuty method

*/

public void free() {

try {

this.logwriter = null;

if (out != null)

this.out.close();

if (fin != null)

this.fin.close();

}

catch (IOException ex) {

ex.printStackTrace();

}

}

}

//测试类

public class Do{

public Do(){

}

public static void main(String[] args){

try{

LogWriter.log("张三登陆了该系统");

LogWriter.log("张三删除了xxx条记录:记录id:");

}

catch (Exception ex) {

LogWriter.log(ex);

}

}

}

log.properties文件内容

logfile=e:\\suoxin.log

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航