log4j的基本使用和参数设定
1、简介
2、核心组件
2.1 Logger
ALL | 打开所有日志 |
DEBUG | 细粒度信息事件,对调试应用程序是非常有帮助的 |
INFO | 粗粒度信息事件,突出强调应用程序的运行过程 |
WARN | 可能出现潜在错误的情形 |
ERROR | 虽然发生错误事件,但仍然不影响系统的继续运行 |
FATAL | 指出每个严重的错误事件将会导致应用程序的退出 |
OFF | 关闭所有日志 |
static Logger logger = Logger.getLogger(test.class);
static Logger logger = Logger.getLogger(test.class);
logger.setLevel((Level)Level.WARN);
logger.setLevel((Level)Level.WARN);
2.2 Appender
ConsoleAppender | 使用用户指定的布局(layout)输出日志事件到System.out或者 System.err。默认的目标是System.out |
FileAppender | 把日志事件写入一个文件 |
DailyRollingFileAppender | 扩展FileAppender,因此多个日志文件可以以一个用户选定的频率进行循环日志记录 |
RollingFileAppender | 扩展FileAppender,备份容量达到一定大小的日志文件 |
WriterAppender | 根据用户的选择把日志事件写入到Writer或者OutputStream |
SMTPAppender | 当特定的日志事件发生时,一般是指发生错误或者重大错误时,发送一封邮件 |
SocketAppender | 给远程日志服务器(通常是网络套接字节点)发送日志事件(LoggingEvent)对象 |
SocketHubAppender | 给远程日志服务器群组(通常是网络套接字节点)发送日志事件(LoggingEvent)对象 |
SyslogAppender | 给远程异步日志记录的后台精灵程序(daemon)发送消息 |
TelnetAppender | 一个专用于向只读网络套接字发送消息的log4j appender |
2.3 Layout
HTMLLayout | 格式化日志输出为HTML表格 |
PatternLayout | 根据指定的转换模式格式化日志输出,或者如果没有指定任何转换模式,就使用默认的转换模式 |
SimpleLayout | 以一种非常简单的方式格式化日志输出,它打印级别 Level,然后跟着一个破折号“-“ ,最后才是日志消息 |
3、配置文件的设置
3.1 根 Logger
log4j.rootLogger = [ level ] , appenderName, appenderName, ...
log4j.rootLogger = [ level ] , appenderName, appenderName, ...
- level 优先级,ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF
- appenderName 指定日志信息输出到哪个地方。您可以同时指定多个输出目的地
3.2 某个包或类的 Logger
log4j.logger.xxx.xxx.xxx=level
log4j.logger.xxx.xxx.xxx=level
log4j.rootLogger=WARN,A log4j.logger.com.opensymphony.xwork2.interceptor.TimerInterceptor=DEBUG
log4j.appender.A=org.apache.log4j.ConsoleAppender
log4j.appender.A.layout=org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern%-d{yyyy-MM-dd HH:mm:ss} [%p]-[%c] %m%n
log4j.rootLogger=WARN,A
log4j.logger.com.opensymphony.xwork2.interceptor.TimerInterceptor=DEBUG
log4j.appender.A=org.apache.log4j.ConsoleAppender
log4j.appender.A.layout=org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern%-d{yyyy-MM-dd HH:mm:ss} [%p]-[%c] %m%n
log.info("微信accessToken刷新 " + WechatAPI.getAccessToken());
log.info("微信accessToken刷新 " + WechatAPI.getAccessToken());
log4j.rootLogger=WARN,A
log4j.logger.indiv.dulk=DEBUG
log4j.logger.com.opensymphony.xwork2.interceptor.TimerInterceptor=DEBUG
log4j.appender.A=org.apache.log4j.ConsoleAppender
log4j.appender.A.layout=org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern%-d{yyyy-MM-dd HH:mm:ss} [%p]-[%c] %m%n
log4j.rootLogger=WARN,A
log4j.logger.indiv.dulk=DEBUG
log4j.logger.com.opensymphony.xwork2.interceptor.TimerInterceptor=DEBUG
log4j.appender.A=org.apache.log4j.ConsoleAppender
log4j.appender.A.layout=org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern%-d{yyyy-MM-dd HH:mm:ss} [%p]-[%c] %m%n
log4j.rootLogger=WARN,A
log4j.logger.indiv.dulk.wechat=DEBUG,wechatlog4j.appender.A=org.apache.log4j.ConsoleAppender
log4j.appender.A.layout=org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%p]-[%c] %m%n
log4j.appender.wechat=org.apache.log4j.ConsoleAppender
log4j.appender.wechat.layout=org.apache.log4j.PatternLayout
log4j.appender.wechat.layout.ConversionPattern=[%p]-[%c] %m%n
log4j.rootLogger=WARN,A
log4j.logger.indiv.dulk.wechat=DEBUG,wechat
log4j.appender.A=org.apache.log4j.ConsoleAppender
log4j.appender.A.layout=org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%p]-[%c] %m%n
log4j.appender.wechat=org.apache.log4j.ConsoleAppender
log4j.appender.wechat.layout=org.apache.log4j.PatternLayout
log4j.appender.wechat.layout.ConversionPattern=[%p]-[%c] %m%n
log4j.rootLogger=WARN,A
log4j.logger.indiv.dulk.wechat=DEBUG,wechat
#不受全局管理
log4j.additivity.indiv.dulk.wechat=false
log4j.appender.A=org.apache.log4j.ConsoleAppender
log4j.appender.A.layout=org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%p]-[%c] %m%n
log4j.appender.wechat=org.apache.log4j.ConsoleAppender
log4j.appender.wechat.layout=org.apache.log4j.PatternLayout
log4j.appender.wechat.layout.ConversionPattern=[%p]-[%c] %m%n
log4j.rootLogger=WARN,A
log4j.logger.indiv.dulk.wechat=DEBUG,wechat
#不受全局管理
log4j.additivity.indiv.dulk.wechat=false
log4j.appender.A=org.apache.log4j.ConsoleAppender
log4j.appender.A.layout=org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%p]-[%c] %m%n
log4j.appender.wechat=org.apache.log4j.ConsoleAppender
log4j.appender.wechat.layout=org.apache.log4j.PatternLayout
log4j.appender.wechat.layout.ConversionPattern=[%p]-[%c] %m%n
3.3 日志输出地址 Appender
log4j.appender.appenderName = fully.qualified.name.of.appender.class (有资格的appender类的全名)
log4j.appender.appenderName.option1 = value1
log4j.appender.appenderName.option = valueN
log4j.appender.appenderName = fully.qualified.name.of.appender.class (有资格的appender类的全名)
log4j.appender.appenderName.option1 = value1
log4j.appender.appenderName.option = valueN
- org.apache.log4j.ConsoleAppender(控制台)
- org.apache.log4j.FileAppender(文件)
- org.apache.log4j.DailyRollingFileAppender(每天产生一个日志文件)
- org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件)
- org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方)
3.4 日志输出格式 Layout
log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class
log4j.appender.appenderName.layout.option1 = value1
log4j.appender.appenderName.layout.option = valueN
log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class
log4j.appender.appenderName.layout.option1 = value1
log4j.appender.appenderName.layout.option = valueN
- org.apache.log4j.HTMLLayout(以HTML表格形式布局)
- org.apache.log4j.PatternLayout(可以灵活地指定布局模式)
- org.apache.log4j.SimpleLayout(包含日志信息的级别和信息字符串)
- org.apache.log4j.TTCCLayout(包含日志产生的时间、线程、类别等等信息)
log4j.appender.log.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t ] %m%n
log4j.appender.log.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t ] %m%n
- %m 输出代码中指定的消息
- %p 输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL
- %r 输出自应用启动到输出该log信息耗费的毫秒数
- %c 输出所属的类目,通常就是所在类的全名
- %t 输出产生该日志事件的线程名
- %n 输出一个回车换行符,Windows平台为“/r/n”,Unix平台为“/n”
- %d 输出日志时间点的日期或时间。默认格式为ISO8601,也可以在其后指定格式。比如:%d{yyy MMM dd HH:mm:ss , SSS},输出类似:2002年10月18日 22:10:28, 921
- %l 输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数
3.5 配置示例
### 设置###
log4j.rootLogger = debug,stdout,D,E
输出信息到控制台
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
输出DEBUG 级别以上的日志到=E://logs/error.log
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
输出ERROR 级别以上的日志到=E://logs/error.log
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### 设置###
log4j.rootLogger = debug,stdout,D,E
### 输出信息到控制台 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
### 输出DEBUG 级别以上的日志到=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### 输出ERROR 级别以上的日志到=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
#指定目录下包下的日志信息都存放到数据库
log4j.logger.database=DEBUG,oracledb
log4j.appender.oracledb=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.oracledb.Driver=oracle.jdbc.driver.OracleDriver
log4j.appender.oracledb.URL=jdbc:oracle:thin:@192.168.20.92:1521:chshsid(切忌此处为sid而不是数据库名)
log4j.appender.oracledb.user=scott
log4j.appender.oracledb.password=tiger
#log4j.appender.encoding=utf-8
log4j.appender.oracledb.sql=INSERT INTO enter_ora_log4j VALUES ('%d{yyyy-MM-dd HH:mm:ss}', '%t', '%p', '%l', '%m')
log4j.appender.oracledb.layout=org.apache.log4j.PatternLayout
#指定目录下包下的日志信息都存放到数据库
log4j.logger.database=DEBUG,oracledb
log4j.appender.oracledb=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.oracledb.Driver=oracle.jdbc.driver.OracleDriver
log4j.appender.oracledb.URL=jdbc:oracle:thin: .168.20.92:1521:chshsid(切忌此处为sid而不是数据库名)
log4j.appender.oracledb.user=scott
log4j.appender.oracledb.password=tiger
#log4j.appender.encoding=utf-8
log4j.appender.oracledb.sql=INSERT INTO enter_ora_log4j VALUES ('%d{yyyy-MM-dd HH:mm:ss}', '%t', '%p', '%l', '%m')
log4j.appender.oracledb.layout=org.apache.log4j.PatternLayout
#指定目录下的java类的日志信息都存放到该目录下
log4j.logger.com.cuigq.TestError=DEBUG,R2
log4j.appender.R2=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R2.File=d:/loginfo/html.html
#log4j.appender.R2.MaxFileSize=500KB
#log4j.appender.R2.MaxBackupIndex=1
log4j.appender.R2.layout=org.apache.log4j.HTMLLayout
#log4j.appender.R2.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n
#指定目录下的java类的日志信息都存放到该目录下
log4j.logger.com.cuigq.TestError=DEBUG,R2
log4j.appender.R2=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R2.File=d:/loginfo/html.html
#log4j.appender.R2.MaxFileSize=500KB
#log4j.appender.R2.MaxBackupIndex=1
log4j.appender.R2.layout=org.apache.log4j.HTMLLayout
#log4j.appender.R2.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n
#指定目录下包下的日志信息都存放到该目录下
log4j.logger.cn.com.cuigq.Theard=DEBUG,R1
log4j.appender.R1=org.apache.log4j.RollingFileAppender
log4j.appender.R1.File=d:/loginfo/iamSystem1.log
log4j.appender.R1.MaxFileSize=500KB
log4j.appender.R1.MaxBackupIndex=1
log4j.appender.R1.layout=org.apache.log4j.PatternLayout
log4j.appender.R1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n
#指定目录下包下的日志信息都存放到该目录下
log4j.logger.cn.com.cuigq.Theard=DEBUG,R1
log4j.appender.R1=org.apache.log4j.RollingFileAppender
log4j.appender.R1.File=d:/loginfo/iamSystem1.log
log4j.appender.R1.MaxFileSize=500KB
log4j.appender.R1.MaxBackupIndex=1
log4j.appender.R1.layout=org.apache.log4j.PatternLayout
log4j.appender.R1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n
4、基本使用 和 Web下的使用
4.1 基本步骤流程
4.1.1 得到日志记录器Logger
public static Logger getLogger( String name)
public static Logger getLogger( String name)
static Logger logger = Logger.getLogger ( ServerWithLog4j.class.getName ())
static Logger logger = Logger.getLogger ( ServerWithLog4j.class.getName ())
4.1.2 读取配置文件
BasicConfigurator.configure (): 自动快速地使用缺省Log4j环境
PropertyConfigurator.configure (String configFilename) :读取使用Java的特性文件编写的配置文件
DOMConfigurator.configure ( String filename ) :读取XML形式的配置文件
BasicConfigurator.configure (): 自动快速地使用缺省Log4j环境
PropertyConfigurator.configure (String configFilename) :读取使用Java的特性文件编写的配置文件
DOMConfigurator.configure ( String filename ) :读取XML形式的配置文件
4.1.3 插入记录信息
Logger.debug ( Object message ) ;
Logger.info ( Object message ) ;
Logger.warn ( Object message ) ;
Logger.error ( Object message ) ;
Logger.debug ( Object message ) ;
Logger.info ( Object message ) ;
Logger.warn ( Object message ) ;
Logger.error ( Object message ) ;
4.2 入门使用
4.3 Web使用
<servlet>
<servlet-name>InitLog4jServlet</servlet-name>
<servlet-class>indiv.dulk.wechat.init.InitLog4jServlet</servlet-class>
<init-param>
<param-name>propertiesLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet>
<servlet-name>InitLog4jServlet</servlet-name>
<servlet-class>indiv.dulk.wechat.init.InitLog4jServlet</servlet-class>
<init-param>
<param-name>propertiesLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
public class InitLog4jServlet extends HttpServlet{
<span class="hljs-comment">/**
* Servlet初始化的执行方法,用以加载log4j配置文件
*
* @throws ServletException
*/</span>
<span class="hljs-meta">@Override</span>
public void init() <span class="hljs-keyword">throws</span> <span class="hljs-type">ServletException</span> {
<span class="hljs-type">System</span>.out.println(<span class="hljs-string">"*** Log4jInitServlet正在初始化log4j日志设置信息 ***"</span>);
<span class="hljs-type">String</span> log4jLocation = getInitParameter(<span class="hljs-string">"propertiesLocation"</span>);
<span class="hljs-keyword">if</span> (log4jLocation == <span class="hljs-literal">null</span>) {
<span class="hljs-type">System</span>.err.println(<span class="hljs-string">"*** 没有找到log4j的properties配置文件,使用缺省log4j环境初始化 ***"</span>);
<span class="hljs-type">BasicConfigurator</span>.configure();
} <span class="hljs-keyword">else</span> {
<span class="hljs-type">String</span> webAppPath = getServletContext().getRealPath(<span class="hljs-string">"/"</span>);
<span class="hljs-type">String</span> log4jRealLocation = webAppPath + log4jLocation;
<span class="hljs-type">File</span> log4jFile = <span class="hljs-keyword">new</span> <span class="hljs-type">File</span>(log4jRealLocation);
<span class="hljs-keyword">if</span> (log4jFile.exists()) {
<span class="hljs-type">System</span>.out.println(<span class="hljs-string">"*** 使用"</span> + log4jRealLocation + <span class="hljs-string">"进行log4j环境初始化 ***"</span>);
<span class="hljs-type">PropertyConfigurator</span>.configure(log4jRealLocation);
} <span class="hljs-keyword">else</span> {
<span class="hljs-type">System</span>.err.println(<span class="hljs-string">"*** "</span> + log4jRealLocation + <span class="hljs-string">"文件未找到,使用缺省log4j环境初始化 ***"</span>);
<span class="hljs-type">BasicConfigurator</span>.configure();
}
}
}
}
public class InitLog4jServlet extends HttpServlet{
/
* Servlet初始化的执行方法,用以加载log4j配置文件
@throws ServletException
/
public void init() throws ServletException {
System.out.println(" Log4jInitServlet正在初始化log4j日志设置信息 ");
String log4jLocation = getInitParameter("propertiesLocation");
if (log4jLocation == null) {
System.err.println(" 没有找到log4j的properties配置文件,使用缺省log4j环境初始化 ");
BasicConfigurator.configure();
} else {
String webAppPath = getServletContext().getRealPath("/");
String log4jRealLocation = webAppPath + log4jLocation;
File log4jFile = new File(log4jRealLocation);
if (log4jFile.exists()) {
System.out.println(" 使用" + log4jRealLocation + "进行log4j环境初始化 ");
PropertyConfigurator.configure(log4jRealLocation);
} else {
System.err.println(" " + log4jRealLocation + "文件未找到,使用缺省log4j环境初始化 ***");
BasicConfigurator.configure();
}
}
}
}
public class InitWechatServlet extends HttpServlet{
private static Logger log = Logger.getLogger(InitWechatServlet.class);
<span class="hljs-comment">/**
* 刷新的间隔时间(单位:毫秒),默认为1h,可以在web.xml自定义配置
*/</span>
<span class="hljs-keyword">private</span> long period = <span class="hljs-number">3600000</span>;
<span class="hljs-comment">/**
* 时间间隔时需要执行的任务内容
*/</span>
<span class="hljs-keyword">private</span> <span class="hljs-type">TimerTask</span> timerTask = <span class="hljs-keyword">new</span> <span class="hljs-type">TimerTask</span>() {
<span class="hljs-meta">@Override</span>
public void run() {
<span class="hljs-comment">//获取最新的access_token并设定到WeChatAPI类中的静态属性中去</span>
<span class="hljs-type">WechatAPI</span>.setAccessToken(<span class="hljs-type">WechatUtil</span>.getNewAccessToken());
log.info(<span class="hljs-string">"微信accessToken刷新 "</span> + <span class="hljs-type">WechatAPI</span>.getAccessToken());
}
};
}
public class InitWechatServlet extends HttpServlet{
private static Logger log = Logger.getLogger(InitWechatServlet.class);
/
* 刷新的间隔时间(单位:毫秒),默认为1h,可以在web.xml自定义配置
*/
private long period = 3600000;
/
* 时间间隔时需要执行的任务内容
*/
private TimerTask timerTask = new TimerTask() {
public void run() {
//获取最新的access_token并设定到WeChatAPI类中的静态属性中去
WechatAPI.setAccessToken(WechatUtil.getNewAccessToken());
log.info("微信accessToken刷新 " + WechatAPI.getAccessToken());
}
};
}
5、参考链接
原文地址:https://www.cnblogs.com/deng-cc/p/6739419.html