systemlog java_LOG处理SystemLogger.java

a4c26d1e5885305701be709a3d33442f.png

LOG处理SystemLogger.java

(2007-04-05 23:13:18)

import java.io.*;

import java.util.*;

import java.text.*;

public class SystemLogger implements Runnable {

public static int DEBUG = 0;

public static int INFO = 1;

public static int NOTICE = 2;

public static int WARNING = 3;

public static int ERROR = 4;

public static int FATAL_ERROR = 5;

public static int MIN_LEVEL = 0;

public static int MAX_LEVEL = 5;

public static int DAILY = 0;

public static int HOURLY = 1;

private static String[] LEVEL_DESC = {

" ",

" ",

" ",

"",

" ",

" ",

};

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 (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

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);

}

}

}

文章引用自:http://locoy.kalvin.cn

分享:

a4c26d1e5885305701be709a3d33442f.png喜欢

0

a4c26d1e5885305701be709a3d33442f.png赠金笔

加载中,请稍候......

评论加载中,请稍候...

发评论

登录名: 密码: 找回密码 注册记住登录状态

昵   称:

评论并转载此博文

a4c26d1e5885305701be709a3d33442f.png

发评论

以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值