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