log4j示例

     試用了下log4j,以下是一個簡單的示例:

 

Symantec Endpoint Protection found a security risk in an attachment from "lxjames.liuxin" <[email protected]>.
Attachment: FlashFXP302.zip
Security risk detected: Trojan Horse
Action taken: Quarantine succeeded
File status: Infected

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class Test {
private static Logger logger = Logger.getLogger(Test.class);
/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
Test test = new Test();
// 在操作系統上java運行的絕對路徑
String path = "E:/SrcCode/java";
// 初始化
try{
test.initLog4j(path);
}
catch (Exception e)
{
}
logger.info("1");
logger.fatal("2");
logger.error("3");
logger.warn("4");
}
public void init(String path) throws Throwable
{
// 配置log4j信息
initLog4j(path);
}
private void initLog4j(String path) throws Exception
{
// 讀取配置文件
Properties p = readConfFile(path + "/conf/log4j.properties");
// 重新定義日誌文件名
// String fileItemKey = "log4j.appender.LOGFILE.File";
// String fileItemValue = path + "/log/SRP_SendF_" + processId + ".log";
// p.setProperty(fileItemKey, fileItemValue);
/**
 * CR_DG_20100916_1177682 全省需求---功能優化專題需求(三)
 * 服務開通進程增加日誌動態控制
 * 2011-02-17 modif by gkf38625
 */
p.setProperty("log4j.rootCategory", "ALL,CONSOLE,LOGFILE");
String logFileThreshold = p.getProperty("log4j.appender.LOGFILE.Threshold");
p.setProperty("log4j.appender.LOGFILE.Threshold", "ALL");
PropertyConfigurator.configure(p);
//將日誌文件輸出級別設置爲配置文件初始值,從根上控制
Logger.getRootLogger().setLevel(Level.toLevel(logFileThreshold));
}
/**
 * @return
 * @throws ExitException
 */
private Properties readConfFile(String fileName) throws Exception
{
Properties p = new Properties();
FileInputStream fs = null;
try
{
fs = new FileInputStream(fileName);
// 讀入配置文件內容
p.load(fs);
}
catch (FileNotFoundException e)
{
logger.fatal("讀取配置信息出錯:沒有找到文件:" + fileName + " " + e.toString());
// 沒有找到配置文件,進程只能退出
throw new Exception("讀取配置信息出錯:沒有找到文件" + fileName);
}
catch (IOException e)
{
logger.fatal("讀取配置信息出錯:" + fileName + " " + e.toString());
// 讀取配置文件出錯,進程只能退出
throw new Exception("讀取配置信息出錯:沒有找到文件" + fileName);
}
finally
{
// 釋放文件句柄
if (null != fs)
{
try
{
fs.close();
}
catch (IOException e)
{
// TODO 自動生成 catch 塊
e.printStackTrace();
}
}
fs = null;
}
return p;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章