package cn.hs.dpl.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.WriterAppender;
import org.apache.log4j.jdbc.JDBCAppender;
/**
* @author wWX61846
* 日志工具类
*
*/
public class LoggerUtil {
private static Logger logger = Logger.getLogger(LoggerUtil.class.getName());
private static Properties properties = new Properties();
/* static{
SimpleLayout layout = new SimpleLayout ();
//向文件中输出信息,OutputStream示例
WriterAppender appender1 = null;
try {
String temp = Thread.currentThread().getContextClassLoader().getResource("").getPath() ;
temp = temp.substring(0, temp.lastIndexOf("WEB-INF")); //WEB-INF 上一級就是項目的根目錄
String s = temp + "\\log" + "\\appMgr_log.txt";
appender1 = new WriterAppender(layout, new FileOutputStream(s));
} catch(Exception ex) {}
logger.addAppender(appender1);
}*/
static{
JDBCAppender appender = new JDBCAppender();
String file = Thread.currentThread().getContextClassLoader().getResource("").getPath()+ "jdbc.properties";
File f = new File(file);
try {
InputStream in = new FileInputStream(f);
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
}
String driverName = properties.getProperty("jdbc.driver");
String url = properties.getProperty("jdbc.url");
String username = properties.getProperty("jdbc.username");
String password = properties.getProperty("jdbc.password");
appender.setDriver(driverName);
appender.setURL(url);
appender.setUser(username);
appender.setPassword(password);
appender.setSql("insert into v5r1_log (operateContent,operateDate) values ('%m','%d{yyyy-MM-dd HH:mm:ss}')");
logger.addAppender(appender);
// log4j.rootLogger=info,db
//
// log4j.appender.db=org.apache.log4j.jdbc.JDBCAppender
// log4j.appender.db.driver=com.mysql.jdbc.Driver
// log4j.appender.db.URL=jdbc:mysql://127.0.0.1/log
// log4j.appender.db.bufferSize=10
// log4j.appender.db.user=root
// log4j.appender.db.password=123
// log4j.appender.db.sql=insert into log (LogName,UserName,Class,Method,createTime,LogLevel,MSG) values ('%X{userId}','%X{userName}','%C','%M','%d{yyyy-MM-dd HH:mm:ss}','%p','%m')
// log4j.appender.db.layout=org.apache.log4j.PatternLayout
}
/**
* @param msg
* INFO级别的日志
*/
public static void tranceINFO(String msg) {
logger.info( msg);
}
/**
* @param username
* @param msg
* 记录用户的操作, eg:张三 --> 删除了XXX应用
*/
public static void tranceINFO(String username, String msg) {
logger.info(username + " --> " + msg);
}
/**
* @param msg
* WARN级别的日志
*/
public static void tranceWARN(String msg) {
logger.warn(msg);
}
/**
* @param msg
* ERROR级别的日志
*/
public static void tranceERROR(String msg) {
logger.error(msg);
}
public static void main(String[] args) {
}
}
java 日志管理
最新推荐文章于 2023-09-05 19:47:03 发布