Linux服务器异常处理:Java Logger
2012-12-01 11:46:57 来源:WEB开发网核心提示: 先定义一个工具类:package org.yxj.utils;//日志类,系统日志为输出到当前用户登陆的根目录下的tongxun文件夹下,Linux服务器异常处理:Java Logger,并以时间命名日志文件//例如:windows系统,文件位于C:\Documents and Settings\Administra
先定义一个工具类:
package org.yxj.utils;
//日志类,系统日志为输出到当前用户登陆的根目录下的tongxun文件夹下,并以时间命名日志文件
//例如:windows系统,文件位于C:\Documents and Settings\Administrator\tongxun\2012-11-29.log
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class LoggerUtil {
/** 存放的文件夹 **/
private static String file_name = "tongxun";
/**
* 得到要记录的日志的路径及文件名称
* @return
*/
private static String getLogName() {
StringBuffer logPath = new StringBuffer();
logPath.append(System.getProperty("user.home"));
logPath.append("\\"+file_name);
File file = new File(logPath.toString());
if (!file.exists())
file.mkdir();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
logPath.append("\\"+sdf.format(new Date())+".log");
return logPath.toString();
}
/**
* 配置Logger对象输出日志文件路径
* @param logger
* @throws SecurityException
* @throws IOException
*/
public static void setLogingProperties(Logger logger) throws SecurityException, IOException {
setLogingProperties(logger,Level.ALL);
}
/**
* 配置Logger对象输出日志文件路径
* @param logger
* @param level 在日志文件中输出level级别以上的信息
* @throws SecurityException
* @throws IOException
*/
public static void setLogingProperties(Logger logger,Level level) {
FileHandler fh;
try {
fh = new FileHandler(getLogName(),true);
logger.addHandler(fh);//日志输出文件
//logger.setLevel(level);
fh.setFormatter(new SimpleFormatter());//输出格式
//logger.addHandler(new ConsoleHandler());//输出到控制台
} catch (SecurityException e) {
logger.log(Level.SEVERE, "安全性错误", e);
} catch (IOException e) {
logger.log(Level.SEVERE,"读取文件日志错误", e);
}
}
}
定义一个工具类
在需要记录异常的地方添加以下代码:
private Logger logger;
Logger logger=Logger.getLogger("LoggerFile");
try {
LoggerUtil.setLogingProperties(logger);
logger.log(Level.INFO, "ddddd");
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// logger.info(ChatUtils.getFormatDate() +"\n"+"终端机"+name+"上线\n");
需要用到捕获异常时输出异常信息到日志中去,比如catch到的异常信息:
- ››linux下两台服务器文件实时同步方案设计和实现
- ››Linux文件描述符中的close on exec标志位
- ››Linux下管道使用的一些限制
- ››Linux 误删/usr/bin 解决方法
- ››linux 添加新用户并赋予sudo执行权限
- ››linux常用软件安装方法
- ››Linux的分区已经被你从Windows中删除,系统启动后...
- ››linux enable命令大全
- ››Linux实现基于Loopback的NVI(NAT Virtual Interfa...
- ››Linux远程访问windows时,出现"连接被对端重...
- ››linux中使用head命令和tail命令查看文件中的指定行...
- ››linux swap 分区调控(swap分区 lvm管理)
更多精彩
赞助商链接
