自己写的java日志类和方法代码分享
import java.io.*;
import java.text.simpledateformat;
import java.util.*;
import java.util.logging.logger;
public class andylogger
{
//the defaulted root path of sslvpn installation
private static string rootpath = "c:\\temp2";
//variable for creating new line
private final static string enter = system.getproperty("line.separator");
private static simpledateformat sdf =
new simpledateformat("yyyy-mm-dd hh:mm:ss");
public static synchronized void log(string filename, string logmessage)
{
try
{
file folder = new file(rootpath);
if(!folder.exists())
{
folder.mkdir();
}
file file = new file(rootpath + "\\" + filename + ".log");
if(!file.exists())
{
file.createnewfile();
}
bufferedreader in = new bufferedreader(new filereader(file));
string str = "";
string strtoal = "";
while ((str = in.readline()) != null)
{
strtoal += (str + enter);
}
strtoal = strtoal + (sdf.format(new date()) + " " + logmessage + enter);
in.close();
bufferedwriter out = new bufferedwriter(new filewriter(file));
out.write(strtoal);
out.close();
}
catch (exception e)
{
e.printstacktrace();
}
}
public static synchronized void log(string filename, string[] logmessages)
{
try
{
file folder = new file(rootpath);
if(!folder.exists())
{
folder.mkdir();
}
file file = new file(rootpath + "\\" + filename + ".log");
if(!file.exists())
{
file.createnewfile();
}
bufferedreader in = new bufferedreader(new filereader(file));
string str = "";
string strtoal = "";
while ((str = in.readline()) != null)
{
strtoal += (str + enter);
}
for (int i=0; i < logmessages.length ; i++)
{
string logmessage = logmessages[i];
strtoal = strtoal + (sdf.format(new date()) + " " + logmessage + enter);
}
in.close();
bufferedwriter out = new bufferedwriter(new filewriter(file));
out.write(strtoal);
out.close();
}
catch (exception e)
{
e.printstacktrace();
}
}
public static void main(string args[])
{
andylogger.log("bug223", "timeisjjja");
string[] logmessages = {"111","222","333"};
andylogger.log("bug223", logmessages);
}
}