采用spring框架的项目如何使用log4j在spring中使用log4j,有些方便的地方,
1.动态的改变记录级别和策略,即修改log4j.properties,不需要重启web应用,这需要在web.xml中设置一下。
2.把log文件定在/WEB-INF/logs而不需要写绝对路径。
3.可以把log4j.properties和其他properties一起放在/WEB-INF下,
首先我们在web.xml中需要设定
log4jConfigLocation
WEB-INF/log4j.properties
log4jRefreshInterval
60000
org.springframework.web.util.Log4jConfigListener
log4jRefreshInterval
60000
logConfig
log4j.properties
其中第二部分是能够动态修改log4j.properties的关键,容器会每60秒扫描log4j的配置文件。有一点就是我们如果用RollingFileAppender或者是FileAppender时,可以通过${webapp.root}来定位到服务器的发布的该项目下,这是spring把web目录的路径压入到了webap.root的系统变量。然后,在log4j.properties里就可以这样定义logfile位置log4j.appender.logfile.File=${webapp.root}/WEB-INF/logs/myfuse.log
如果有多个web应用,怕webapp.root变量重复,可以在context-param里定义webAppRootKey
一、系统日志组件,类加载执行
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.LogManager;
import com.platform.core.util.Debug;
/**
* 系统日志组件
*/
public class Log4j implements StartItem {
/** useLog4J 是否使用Log4j组件 */
public static boolean useLog4J = false;
/**
* {@inheritDoc}
* @return String
*/
public String getName() {
return "系统日志组件";
}
/**
* {@inheritDoc}
*/
public void start() {
useLog4J = Debug.useLog4J;
}
/**
* {@inheritDoc}
*/
public void stop() {
if (useLog4J) {
// 释放Log4j日志资源
LogManager.shutdown();
LogFactory.releaseAll();
}
}
}
二、日志框架
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.util.Date;
import java.util.Properties;
import org.apache.log4j.Category;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import org.apache.log4j.PropertyConfigurator;
import com.platform.core.AppMgr;
import com.platform.core.exception.CoreException;
import com.platform.util.StringUtils;
public final class Debug {
/** LOG TODO */
public static final String LOG = "log.level";
/** LOG4J TODO */
public static final String LOG4J = "log.log4j";
/** SETUPNAME TODO */
public static final String SETUPNAME = "setup";
/** SETUPVALUE TODO */
public static final String SETUPVALUE = "true";
/** useLog4J TODO */
public static boolean useLog4J = false;
/** dateFormat TODO */
public static DateFormat dateFormat = DateFormat.getDateTimeInstance(3, 2);
/** propsUtil TODO */
private static final PropsUtil PROPSUTIL;
/** ALWAYS TODO */
public static final int ALWAYS = 0;
/** VERBOSE TODO */
public static final int VERBOSE = 1;
/** TIMING TODO */
public static final int TIMING = 2;
/** INFO TODO */
public static final int INFO = 3;
/** IMPORTANT TODO */
public static final int IMPORTANT = 4;
/** WARNING TODO */
public static final int WARNING = 5;
/** ERROR TODO */
public static final int ERROR = 6;
/** FATAL TODO */
public static final int FATAL = 7;
/** conf_level TODO */
public static int conf_level = -1;
/** levels TODO */
public static final String[] LEVELS = {"Always", "Verbose",
"Timing", "Info",
"Important", "Warning",
"Error", "Fatal"};
/** LEVELPROPS TODO */
public static final String[] LEVELPROPS = {
"", "print.verbose", "print.timing", "print.info",
"print.important", "print.warning", "print.error",
"print.fatal"
};
/** LEVELOBJS TODO */
public static final Priority[] LEVELOBJS;
/** printStream TODO */
protected static PrintStream printStream;
/** printWriter TODO */
protected static PrintWriter printWriter;
/**
* 构造函数
*/
public Debug() {
}
/**
* Method getPrintStream.
* @return PrintStream
*/
public static PrintStream getPrintStream() {
return printStream;
}
/**
* Method setPrintStream.
* @param printStream PrintStream
*/
public static void setPrintStream(PrintStream printStream) {
printStream = printStream;
printWriter = new PrintWriter(printStream);
}
/**
* Method getPrintWriter.
* @return PrintWriter
*/
public static PrintWriter getPrintWriter() {
return printWriter;
}
/**
* Method getLogger.
* @param module String
* @return Category
*/
public static Category getLogger(String module) {
if (module != null && module.length() > 0) {
return Logger.getLogger(module);
} else {
return Logger.getLogger(Debug.class);
}
}
/**
* Method log.
* @param level int
* @param t Throwable
* @param msg String
* @param module String
*/
public static void log(int level, Throwable t, String msg, String module) {
log(level, t, msg, module, Debug.class.getName());
}
/**
* Method log.
* @param level int
* @param t Throwable
* @param msg String
* @param module String
* @param callingClass String
*/
private static void log(int level, Throwable t, String msg, String module, String callingClass) {
if (level >= conf_level) {
if (useLog4J) {
Category logger = getLogger(module);
logger.log(callingClass, LEVELOBJS[level], msg, t);
} else {
StringBuffer prefixBuf = new StringBuffer();
prefixBuf.append(dateFormat.format(new Date()));
prefixBuf.append(" [Debug");
if (module != null) {
prefixBuf.append(":");
prefixBuf.append(module);
}
prefixBuf.append(":");
prefixBuf.append(LEVELS[level]);
prefixBuf.append("] ");
if (msg != null) {
getPrintStream().print(prefixBuf.toString());
getPrintStream().println(msg);
}
if (t != null) {
getPrintStream().print(prefixBuf.toString());
getPrintStream().println("Received throwable:");
t.printStackTrace(getPrintStream());
}
}
}
}
/**
* Method isOn.
* @param level int
* @return boolean
*/
public static boolean isOn(int level) {
return level == 0;
}
/**
* Method log.
* @param msg String
*/
public static void log(String msg) {
log(0, null, msg, null);
}
/**
* Method log.
* @param msg String
* @param module String
*/
public static void log(String msg, String module) {
log(0, null, msg, module);
}
/**
* Method log.
* @param t Throwable
*/
public static void log(Throwable t) {
log(0, t, null, null);
}
/**
* Method log.
* @param t Throwable
* @param msg String
*/
public static void log(Throwable t, String msg) {
log(0, t, msg, null);
}
/**
* Method log.
* @param t Throwable
* @param msg String
* @param module String
*/
public static void log(Throwable t, String msg, String module) {
log(0, t, msg, module);
}
/**
* Method verboseOn.
* @return boolean
*/
public static boolean verboseOn() {
return isOn(1);
}
/**
* Method logVerbose.
* @param msg String
*/
public static void logVerbose(String msg) {
log(1, null, msg, null);
}
/**
* Method logVerbose.
* @param msg String
* @param module String
*/
public static void logVerbose(String msg, String module) {
log(1, null, msg, module);
}
/**
* Method logVerbose.
* @param t Throwable
*/
public static void logVerbose(Throwable t) {
log(1, t, null, null);
}
/**
* Method logVerbose.
* @param t Throwable
* @param msg String
*/
public static void logVerbose(Throwable t, String msg) {
log(1, t, msg, null);
}
/**
* Method logVerbose.
* @param t Throwable
* @param msg String
* @param module String
*/
public static void logVerbose(Throwable t, String msg, String module) {
log(1, t, msg, module);
}
/**
* Method timingOn.
* @return boolean
*/
public static boolean timingOn() {
return isOn(2);
}
/**
* Method logTiming.
* @param msg String
*/
public static void logTiming(String msg) {
log(2, null, msg, null);
}
/**
* Method logTiming.
* @param msg String
* @param module String
*/
public static void logTiming(String msg, String module) {
log(2, null, msg, module);
}
/**
* Method logTiming.
* @param t Throwable
*/
public static void logTiming(Throwable t) {
log(2, t, null, null);
}
/**
* Method logTiming.
* @param t Throwable
* @param msg String
*/
public static void logTiming(Throwable t, String msg) {
log(2, t, msg, null);
}
/**
* Method logTiming.
* @param t Throwable
* @param msg String
* @param module String
*/
public static void logTiming(Throwable t, String msg, String module) {
log(2, t, msg, module);
}
/**
* Method infoOn.
* @return boolean
*/
public static boolean infoOn() {
return isOn(3);
}
/**
* Method logInfo.
* @param msg String
*/
public static void logInfo(String msg) {
log(3, null, msg, null);
}
/**
* Method logInfo.
* @param msg String
* @param module String
*/
public static void logInfo(String msg, String module) {
log(3, null, msg, module);
}
/**
* Method logInfo.
* @param t Throwable
*/
public static void logInfo(Throwable t) {
log(3, t, null, null);
}
/**
* Method logInfo.
* @param t Throwable
* @param msg String
*/
public static void logInfo(Throwable t, String msg) {
log(3, t, msg, null);
}
/**
* Method logInfo.
* @param t Throwable
* @param msg String
* @param module String
*/
public static void logInfo(Throwable t, String msg, String module) {
log(3, t, msg, module);
}
/**
* Method importantOn.
* @return boolean
*/
public static boolean importantOn() {
return isOn(4);
}
/**
* Method logImportant.
* @param msg String
*/
public static void logImportant(String msg) {
log(4, null, msg, null);
}
/**
* Method logImportant.
* @param msg String
* @param module String
*/
public static void logImportant(String msg, String module) {
log(4, null, msg, module);
}
/**
* Method logImportant.
* @param t Throwable
*/
public static void logImportant(Throwable t) {
log(4, t, null, null);
}
/**
* Method logImportant.
* @param t Throwable
* @param msg String
*/
public static void logImportant(Throwable t, String msg) {
log(4, t, msg, null);
}
/**
* Method logImportant.
* @param t Throwable
* @param msg String
* @param module String
*/
public static void logImportant(Throwable t, String msg, String module) {
log(4, t, msg, module);
}
/**
* Method warningOn.
* @return boolean
*/
public static boolean warningOn() {
return isOn(5);
}
/**
* Method logWarning.
* @param msg String
*/
public static void logWarning(String msg) {
log(5, null, msg, null);
}
/**
* Method logWarning.
* @param msg String
* @param module String
*/
public static void logWarning(String msg, String module) {
log(5, null, msg, module);
}
/**
* Method logWarning.
* @param t Throwable
*/
public static void logWarning(Throwable t) {
log(5, t, null, null);
}
/**
* Method logWarning.
* @param t Throwable
* @param msg String
*/
public static void logWarning(Throwable t, String msg) {
log(5, t, msg, null);
}
/**
* Method logWarning.
* @param t Throwable
* @param msg String
* @param module String
*/
public static void logWarning(Throwable t, String msg, String module) {
log(5, t, msg, module);
}
/**
* Method errorOn.
* @return boolean
*/
public static boolean errorOn() {
return isOn(6);
}
/**
* Method logError.
* @param msg String
*/
public static void logError(String msg) {
log(6, null, msg, null);
}
/**
* Method logError.
* @param msg String
* @param module String
*/
public static void logError(String msg, String module) {
log(6, null, msg, module);
}
/**
* Method logError.
* @param t Throwable
*/
public static void logError(Throwable t) {
log(6, t, null, null);
}
/**
* Method logError.
* @param t Throwable
* @param msg String
*/
public static void logError(Throwable t, String msg) {
log(6, t, msg, null);
}
/**
* Method logError.
* @param t Throwable
* @param msg String
* @param module String
*/
public static void logError(Throwable t, String msg, String module) {
log(6, t, msg, module);
}
/**
* Method fatalOn.
* @return boolean
*/
public static boolean fatalOn() {
return isOn(7);
}
/**
* Method logFatal.
* @param msg String
*/
public static void logFatal(String msg) {
log(7, null, msg, null);
}
/**
* Method logFatal.
* @param msg String
* @param module String
*/
public static void logFatal(String msg, String module) {
log(7, null, msg, module);
}
/**
* Method logFatal.
* @param t Throwable
*/
public static void logFatal(Throwable t) {
log(7, t, null, null);
}
/**
* Method logFatal.
* @param t Throwable
* @param msg String
*/
public static void logFatal(Throwable t, String msg) {
log(7, t, msg, null);
}
/**
* Method logFatal.
* @param t Throwable
* @param msg String
* @param module String
*/
public static void logFatal(Throwable t, String msg, String module) {
log(7, t, msg, module);
}
static {
PROPSUTIL = new PropsUtil("log.xml");
LEVELOBJS = (new Priority[] {
Level.INFO, Level.DEBUG, Level.DEBUG, Level.INFO, Level.INFO,
Level.WARN, Level.ERROR, Level.FATAL
});
printStream = System.out;
printWriter = new PrintWriter(printStream);
try {
String levelStrs = PROPSUTIL.getProperty("log.level");
if (levelStrs != null) {
conf_level = Integer.parseInt(levelStrs);
}
String log4jStrs = PROPSUTIL.getProperty("log.log4j");
if (log4jStrs != null && log4jStrs.equalsIgnoreCase("true")) {
useLog4J = true;
}
} catch (Exception e) {
System.err.print("getLogLevel e");
conf_level = 1;
useLog4J = false;
throw new CoreException(e);
}
if (useLog4J) {
InputStream in = null;
try {
String home = AppMgr.getInstance().getHome();
Properties prop = new Properties();
FileLocator fileLocator = new FileLocator();
in = fileLocator.getConfStream(home.concat("WEB-INF").concat(File.separator).concat("log4j.properties"));
prop.load(in);
String logFile = prop.getProperty("log4j.appender.R.File");
logFile = StringUtils.replace(logFile, "${webapp.root}", home);
File filePath = new File(logFile);
if (!filePath.isDirectory()) {
filePath = filePath.getParentFile();
}
if (!filePath.exists()) {
filePath.mkdirs();
}
prop.setProperty("log4j.appender.R.File", logFile);
PropertyConfigurator.configure(prop);
} catch (Exception e) {
throw new CoreException(e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
log4j.properties
# To continue using the "catalina.out" file (which grows forever),
log4j.rootLogger=DEBUG, A1, R
# Configuration for standard output ("catalina.out").
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
# Print the date in ISO 8601 format
#log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
log4j.appender.A1.layout.ConversionPattern=[%-5p] %-40m %l%n
# Configuration for a rolling log file ("hd.log").
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.DatePattern='.'yyyy-MM-dd
log4j.appender.R.File=${webapp.root}/WEB-INF/logs/hd.log
# Edit the next line to point to your logs directory.
# The last part of the name is the log file name.
log4j.appender.R.layout=org.apache.log4j.PatternLayout
# Print the date in ISO 8601 format
log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p [%F:%L] %c{8}.%M() - %m%n
使用
import com.platform.core.util.Debug;
Debug.logVerbose((new StringBuilder()).append("[Leopard]remove the object of ")
.append(skey).append(" from cache").toString(), module);