指定目录输出日志(根据日期和操作员信息)


package com.microjava.log;

public interface ILog {
public void write(Object o);
}



package com.microjava.log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class LogService implements ILog {

private String filename;
private FileOutputStream fileoutputstream;
private String encoding;
private static Map instances = null;
private LogService() {

}
private LogService(String today, String branchid) {
//filename = CommonProperties.getAppPath()+"/logs/"+today+"/"+branchid+"/message.log";
filename = "d:/logs/"+today+"/"+branchid+"/message.log";
encoding = "gbk"; //"GB2312";
}

public synchronized static ILog getInstance() {
String branchid = null;
String bankid = "01";//(String)Sessions.getCurrent().getAttribute("bankid");
String branchid_ = "002";//(String)Sessions.getCurrent().getAttribute("branchid");
if(bankid!=null) {
branchid = bankid;
}
if(branchid_!=null) {
if(branchid==null) {
branchid = branchid_;
} else {
branchid += branchid_;
}
}
if(branchid==null || branchid.equals("")) {
branchid = "undefined";
}
String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
if(instances==null) {
instances = new HashMap();
instances.put(today+branchid, new LogService(today, branchid));
} else if(!instances.containsKey(today+branchid)) {
instances.put(today+branchid, new LogService(today, branchid));
}
return (ILog)instances.get(today+branchid);
}

private synchronized void rollingFile() throws IOException {
File file = new File(filename);
if(!file.exists()) {
new File(file.getParent()).mkdirs();
file.createNewFile();
fileoutputstream = null;
} else if(file.length()>=5000000L) {//可以参数化
File file_;
do {
String ext = String.valueOf(System.currentTimeMillis());
file_ = new File(filename+"."+ext);
} while(file_.exists());
file.renameTo(file_);
fileoutputstream = null;
file_ = null;
}
fileoutputstream = new FileOutputStream(file, true);
}
public void write(Object o) {
// TODO Auto-generated method stub
try {
rollingFile();
fileoutputstream.write(("["+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS").format(new Date())+"]"+o.toString()+"\n").getBytes(encoding));
fileoutputstream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}



package com.microjava.log;

import junit.framework.TestCase;

public class ILogTest extends TestCase {

private ILog log;

protected void setUp() {
log = LogService.getInstance();
}

public void testWrite() {
log.write("Hello,microjava!");
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值