",
"",
};
private PrintWriter out;
private int level = DEBUG;
private DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
private boolean needToCloseOutput = false;
private Thread thread = null;
private String filePrefix = "";
private int switchingFrequency = DAILY;
private Vector listeners = null;
// --- Start of Singleton Pattern ----------------------- //
private static SystemLogger instance = null;
public static SystemLogger getInstance() {
if (instance == null) {
instance = new SystemLogger();
}
return instance;
}
protected SystemLogger() {
// Set default output to System.out:
setOutput(System.out);
}
// --- End of Singleton Pattern ------------------------- //
public synchronized void setOutput(
String filePrefix, boolean autoSwitching, int frequency) {
this.filePrefix = filePrefix;
this.switchingFrequency =
(frequency != DAILY && frequency != HOURLY) ? DAILY : frequency;
if (autoSwitching) {
if (thread == null) {
thread = new Thread(this);
thread.start();
}
} else {
if (thread != null) {
Thread t = thread;
thread = null;
t.interrupt();
}
setOutput(filePrefix ".log");
}
}
private synchronized void setOutput(String filename) {
PrintWriter newOutput = null;
try {
newOutput = new PrintWriter(new FileOutputStream(filename, true));
} catch (IOException e) {
logError("System logger failed to open file " filename, e);
return;
}
if (out != null && needToCloseOutput) {
logInfo("System logger output closed and switched to " filename);
out.close();
}
out = newOutput;
needToCloseOutput = true;
logInfo("System logger started with output to " filename);
logInfo("System logger option (autoSwitching="
((thread == null) ? "false" :
"true, frequency="
((switchingFrequency == DAILY) ? "daily" :
((switchingFrequency == HOURLY) ? "hourly" : "unknown")))
")" );
}
private synchronized void recycleOutput() {
SimpleDateFormat df;
if (switchingFrequency == DAILY) {
df = new SimpleDateFormat("yyyy-MM-dd");
} else {
df = new SimpleDateFormat("yyyy-MM-dd-HH");
}
String filename = filePrefix "-" df.format(new Date()) ".log";
setOutput(filename);
}
public void run() {
int currentDayOfMonth = -1;
int currentHourOfDay = -1;
for (;;) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
int dd = calendar.get(Calendar.DAY_OF_MONTH);
int hh = calendar.get(Calendar.HOUR_OF_DAY);
int mm = calendar.get(Calendar.MINUTE);
int ss = calendar.get(Calendar.SECOND);
int ms = calendar.get(Calendar.MILLISECOND);
if ((switchingFrequency == DAILY &&
(dd != currentDayOfMonth)) ||
(switchingFrequency == HOURLY &&
(dd != currentDayOfMonth || hh != currentHourOfDay))) {
recycleOutput();
}
logDebug("Calendar dd=" dd
" hh=" hh
" mm=" mm
" ss=" ss
" ms=" ms);
currentDayOfMonth = dd;
currentHourOfDay = hh;
int sleep;
if (switchingFrequency == DAILY) {
sleep = 86400000 - (((hh * 60 mm) * 60 ss) * 1000 ms);
} else {
sleep = 3600000 - ((mm * 60 ss) * 1000 ms);
}
sleep = 500; // add 0.5 sec. for tolerance.
logDebug(
"System logger will switch its output to a new file after "
sleep " milliseconds.");
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
logDebug("System logger auto-switching thread interrupted");
}
if (Thread.currentThread() != this.thread) {
break;
}
}
logDebug("System logger auto-switching thread terminated.");
}
public synchronized void setOutput(OutputStream os) {
if (out != null && needToCloseOutput) {
logInfo("System logger output closed.");
out.close();
out = null;
}
out = new PrintWriter(os);
needToCloseOutput = false;
logInfo(
"System logger started with output as "
((os == System.out) ?
"System.out" : "OutputStream " os.toString()));
}
public synchronized void setOutput(PrintWriter writer) {
if (out != null && needToCloseOutput) {
logInfo("System logger output closed.");
out.close();
out = null;
}
out = writer;
needToCloseOutput = false;
logInfo("System logger started with output as PrintWriter "
writer.toString());
}
public synchronized void close() {
logInfo("System logger requested to be closed down.");
if (thread != null) {
Thread t = thread;
thread = null;
t.interrupt();
try {
wait(500);
} catch (InterruptedException e) {}
}
if (out != null && needToCloseOutput) {
out.close();
out = null;
}
listeners = null;
}
/**
Specifies the level of the messages to be logged.
*/
public void setLevel(int level) {
this.level = level;
}
/**
Returns the current logging level.
@return the current logging level.
*/
public int getLevel() {
return this.level;
}
/**
Logs a message with the specified log level and associated
exception.
@param logLevel the level of the message.
@param msg the message string.
@param e an optional exception associated with the message.
*/
public void log(int logLevel, String msg, Exception e) {
if (out == null || this.level > logLevel) {
return;
}
logLevel = logLevel < MIN_LEVEL ? MIN_LEVEL : logLevel;
logLevel = logLevel > MAX_LEVEL ? MAX_LEVEL : logLevel;
String line;
synchronized(this) {
line = "# " dateFormat.format(new Date()) " "
LEVEL_DESC[logLevel] " " msg;
out.println(line);
if (e != null) {
e.printStackTrace(out);
}
out.flush();
}
if (listeners != null) {
SystemLoggerListener listener;
SystemLoggerEvent evt =
new SystemLoggerEvent(this, logLevel, msg, e, line);
for (Enumeration en = ((Vector)listeners.clone()).elements();
en.hasMoreElements(); ) {
try {
listener = (SystemLoggerListener)en.nextElement();
listener.messageLogged(evt);
} catch (Exception e1) {}
}
}
}
/**
Logs a debug message with an exception.
@param msg the message string
@param e the excetpion.
*/
public void logDebug(String msg, Exception e) {
log(DEBUG, msg, e);
}
/**
Logs a debug message without an exception.
@param msg the message string
@param e the excetpion.
*/
public void logDebug(String msg) {
log(DEBUG, msg, null);
}
/**
Logs an info message with an exception.
@param msg the message string
@param e the excetpion.
*/
public void logInfo(String msg, Exception e) {
log(INFO, msg, e);
}
/**
Logs an info message without an exception.
@param msg the message string
@param e the excetpion.
*/
public void logInfo(String msg) {
log(INFO, msg, null);
}
/**
Logs a notice message with an exception.
@param msg the message string
@param e the excetpion.
*/
public void logNotice(String msg, Exception e) {
log(NOTICE, msg, e);
}
/**
Logs a notice message without an exception.
@param msg the message string
@param e the excetpion.
*/
public void logNotice(String msg) {
log(NOTICE, msg, null);
}
/**
Logs a warning message with an exception.
@param msg the message string
@param e the excetpion.
*/
public void logWarning(String msg, Exception e) {
log(WARNING, msg, e);
}
/**
Logs a warning message without an exception.
@param msg the message string
@param e the excetpion.
*/
public void logWarning(String msg) {
log(WARNING, msg, null);
}
/**
Logs an error message with an exception.
@param msg the message string
@param e the excetpion.
*/
public void logError(String msg, Exception e) {
log(ERROR, msg, e);
}
/**
Logs an error message without an exception.
@param msg the message string
@param e the excetpion.
*/
public void logError(String msg) {
log(ERROR, msg, null);
}
/**
Logs a fatal error message with an exception.
@param msg the message string
@param e the excetpion.
*/
public void logFatalError(String msg, Exception e) {
log(FATAL_ERROR, msg, e);
}
/**
Logs a fatal error message without an exception.
@param msg the message string
@param e the excetpion.
*/
public void logFatalError(String msg) {
log(FATAL_ERROR, msg, null);
}
public synchronized void addSystemLoggerListener(
SystemLoggerListener listener) {
if (listeners == null) {
listeners = new Vector();
}
listeners.addElement(listener);
}
public void removeSystemLoggerListener(
SystemLoggerListener listener) {
if (listener != null) {
listeners.removeElement(listener);
}
}
}
下载本文示例代码
LOG处理SystemLogger.javaLOG处理SystemLogger.javaLOG处理SystemLogger.javaLOG处理SystemLogger.javaLOG处理SystemLogger.javaLOG处理SystemLogger.javaLOG处理SystemLogger.javaLOG处理SystemLogger.javaLOG处理SystemLogger.javaLOG处理SystemLogger.javaLOG处理SystemLogger.javaLOG处理SystemLogger.java