/**
* 该程序是生成日志文件,再将信息输入到日志文件
* 该程序是单例,由多线程访问
*/
public class FileLogger
{
private String date = ""; private Printwriter Writer = null public void log(String msg)
{ // Construct the timestamp we will use, if requested
Timestamp ts = new Timestamp(System.currentTimeMillis());
String tsString = ts.toString().substring(0, 19);
String tsDate = tsString.substring(0, 10); // If the date has changed, switch log files
if (!date.equals(tsDate))
{
synchronized (this) //该锁是锁定哪个对象(我知道是该对象的实例),具体是锁
// 里面的哪一个,为什么
{
if (!date.equals(tsDate))
{
close();
date = tsDate;
open();
}
}
} // Log this message, timestamped if necessary
if (writer != null)
{
writer.println(tsString + " " + msg);
}
} private void open()
{ // Create the directory if necessary
File dir = new File(directory);
if (!dir.isAbsolute())
dir = new File(System.getProperty("user.dir"), "webroot");
dir.mkdirs(); // Open the current log file
try
{
String pathname = dir.getAbsolutePath() + File.separator +
"log_" + date + ".txt";
writer = new PrintWriter(new FileWriter(pathname, true), true);
}
catch (IOException e)
{
writer = null;
} }
}
* 该程序是生成日志文件,再将信息输入到日志文件
* 该程序是单例,由多线程访问
*/
public class FileLogger
{
private String date = ""; private Printwriter Writer = null public void log(String msg)
{ // Construct the timestamp we will use, if requested
Timestamp ts = new Timestamp(System.currentTimeMillis());
String tsString = ts.toString().substring(0, 19);
String tsDate = tsString.substring(0, 10); // If the date has changed, switch log files
if (!date.equals(tsDate))
{
synchronized (this) //该锁是锁定哪个对象(我知道是该对象的实例),具体是锁
// 里面的哪一个,为什么
{
if (!date.equals(tsDate))
{
close();
date = tsDate;
open();
}
}
} // Log this message, timestamped if necessary
if (writer != null)
{
writer.println(tsString + " " + msg);
}
} private void open()
{ // Create the directory if necessary
File dir = new File(directory);
if (!dir.isAbsolute())
dir = new File(System.getProperty("user.dir"), "webroot");
dir.mkdirs(); // Open the current log file
try
{
String pathname = dir.getAbsolutePath() + File.separator +
"log_" + date + ".txt";
writer = new PrintWriter(new FileWriter(pathname, true), true);
}
catch (IOException e)
{
writer = null;
} }
}
synchronized (lock) {
print(x);
println();
}
}