003-log-jul,jdk自带日志服务
一、简介
java官方日志jul,位于java.util.logging包下。
1.1、POM依赖
无依赖
1.2、配置
JUL的默认配置文件是logging.properties ,在 $JAVA_HOME/jre/lib下 (Mac 在 $JAVA_HOME/lib). 当然自己也可以修改文件位置,如:-Djava.util.logging.config.file=xxxpath/logging.properties
jre(java runtime environment, 即java运行环境)的默认日志配置为jre/lib/logging.properties,
其配置如下:
############################################################
# Default Logging Configuration File
#
# You can use a different file by specifying a filename
# with the java.util.logging.config.file system property.
# For example java -Djava.util.logging.config.file=myfile
############################################################ ############################################################
# Global properties
############################################################ # "handlers" specifies a comma separated list of log Handler
# classes. These handlers will be installed during VM startup.
# Note that these classes must be on the system classpath.
# By default we only configure a ConsoleHandler, which will only
# show messages at the INFO and above levels.
handlers= java.util.logging.ConsoleHandler # To also add the FileHandler, use the following line instead.
#handlers= java.util.logging.FileHandler, java.util.logging.ConsoleHandler # Default global logging level.
# This specifies which kinds of events are logged across
# all loggers. For any given facility this global level
# can be overriden by a facility specific level
# Note that the ConsoleHandler also has a separate level
# setting to limit messages printed to the console.
.level= INFO ############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################ # default file output is in user's home directory.
java.util.logging.FileHandler.pattern = %h/java%u.log
java.util.logging.FileHandler.limit = 50000
java.util.logging.FileHandler.count = 1
java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter # Limit the message that are printed on the console to INFO and above.
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter # Example to customize the SimpleFormatter output format
# to print one-line log message like this:
# <level>: <log message> [<date/time>]
#
# java.util.logging.SimpleFormatter.format=%4$s: %5$s [%1$tc]%n ############################################################
# Facility specific properties.
# Provides extra control for each logger.
############################################################ # For example, set the com.xyz.foo logger to only log SEVERE
# messages:
com.xyz.foo.level = SEVERE
在tomcat的conf下就有个logging.properties,同时注意catalina.sh 里就有这样代码
# Set juli LogManager if it is present
if [ -r "$CATALINA_BASE"/conf/logging.properties ]; then
JAVA_OPTS="$JAVA_OPTS -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager"
LOGGING_CONFIG="-Djava.util.logging.config.file=$CATALINA_BASE/conf/logging.properties"
fi
1.3、使用
import java.util.logging.Level;
import java.util.logging.Logger; public class ApplicationMain {
private static Logger logger = Logger.getLogger(ApplicationMain.class.getName()); public static void main(String[] args) {
// 记录debug级别的信息
logger.log(Level.INFO,"This is debug message.");
// 记录info级别的信息
logger.info("This is info message.");
// 记录error级别的信息
logger.warning("This is warning message.");
}
}
二、详细说明
jul模块主要包含三个:Level、Formatter和Handler。
1.1、Level
日志级别,由高到低有:OFF/SEVERE/WARNIN/INFO/CONFIG/FINE/FINERG/FINEST/ALL,
每个级别有自己的数值,在java.util.logging.Level类中源码如下:
public static final Level OFF = new Level("OFF",Integer.MAX_VALUE, defaultBundle);
public static final Level SEVERE = new Level("SEVERE",1000, defaultBundle);
public static final Level WARNING = new Level("WARNING", 900, defaultBundle);
public static final Level INFO = new Level("INFO", 800, defaultBundle);
public static final Level CONFIG = new Level("CONFIG", 700, defaultBundle);
public static final Level FINE = new Level("FINE", 500, defaultBundle);
public static final Level FINER = new Level("FINER", 400, defaultBundle);
public static final Level FINEST = new Level("FINEST", 300, defaultBundle);
public static final Level ALL = new Level("ALL", Integer.MIN_VALUE, defaultBundle);
可自定义日志级别,继承java.util.logging.Level类即可。
1.2、Formatter
定义日志输出的格式,目前有SimpleFormatter和XMLFormatter两种格式,分别对应简单格式和xml格式。
可自定输出格式,继承抽象类java.util.logging.Formatter即可。
1.3、Handler
日志输出的目的,目前有
FileHandler:输出到文件,默认Level为INFO,Formatter为XMLFormatter;;
ConsoleHandler:输出到控制台,默认Level为INFO,流为System.err,Formatter为SimpleFormatter;
SocketHandler:输出到socket;
MemoryHandler:输出到内存;
可自定义日志级别,继承java.util.logging.Formatter类即可。
1.4、简单示例
import java.util.logging.*;
public class JavaLogStudyMain {
public static void main(String[] args) throws Exception {
//简单格式的Formatter
SimpleFormatter sf = new SimpleFormatter();
//xml格式的formatter
XMLFormatter xf = new XMLFormatter();
//输出到文件的hander,指定日志输出级别为ALL
FileHandler fh = new FileHandler("jul_study.log");
fh.setLevel(Level.ALL);
fh.setFormatter(sf);
// fh.setFormatter(xf);
//输出到控制台的handler,指定日志输出级别为INFO
ConsoleHandler ch = new ConsoleHandler();
ch.setLevel(Level.INFO);
//获取logger实例,相同名的只能生成一个实例
Logger logger = Logger.getLogger("javaLog");
logger.addHandler(fh); //添加输出handler
logger.addHandler(ch); //添加输出handler
logger.setLevel(Level.ALL); //指定logger日志级别
//日志输出简写形式,有不同的级别,可带参数,其它类似
logger.log(Level.INFO, "this is a info, {0}", "p1");
logger.log(Level.WARNING, "this is a warn, {0} {1}", new Object[]{"p1", "p2"});
logger.log(Level.SEVERE, "this is a severe");
logger.log(Level.FINE, "this is a fine");
logger.log(Level.FINEST, "this is a finest");
logger.log(Level.CONFIG, "this is a config");
logger.log(Level.INFO, "this is a info", new Exception("my excep")); //带异常输出
//日志输出简写形式,有不同的级别
logger.severe("severe log");
logger.warning("warning log");
logger.info("info log");
logger.config("config log");
logger.fine("fine log");
logger.finer("finer log");
logger.finest("finest log");
}
}
1.5、自定义logger
这里通过继承Level、Handler、Formatter自定义Logger,日志存在文件中,且每个不同的loggerName存不同日志文件中。
示例如下,解释请查看注释:
import org.apache.commons.lang.time.DateFormatUtils; import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.logging.*; public class SelfJavaLogMain {
//生成单例日志输出handler实例
private static SelfHandle sf = new SelfHandle(); /**
* 根据class获取logger
*
* @param clazz
* @return
*/
public static Logger getLogger(Class clazz) {
return getLogger(clazz.getSimpleName());
} /**
* 根据loggerName获取logger
*
* @param loggerName
* @return
*/
public static Logger getLogger(String loggerName) {
Logger logger = Logger.getLogger(loggerName);
logger.addHandler(sf);
return logger;
} /**
* 自定义日志格式formatter
*/
public static class SelfFormater extends Formatter { public static SelfFormater selfFormater = new SelfFormater(); @Override
public String format(LogRecord record) {
return String.format("[%s] %s %s.%s: %s\r\n", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"),
record.getLevel().getName(), record.getSourceClassName(), record.getSourceMethodName(), record.getMessage());
} public static SelfFormater getInstance() {
return selfFormater;
}
} /**
* 自定义日志level
*/
public static class SelfLevel extends Level { public static SelfLevel ERROR = new SelfLevel("ERROR", 910); /**
* @param name 自定义级别名称
* @param value 自定义级别的权重值
*/
protected SelfLevel(String name, int value) {
super(name, value);
}
} /**
* 自定义日志输出handler
*/
public static class SelfHandle extends Handler { /**
* 日志写入的位置
*
* @param record
*/
@Override
public void publish(LogRecord record) {
try {
//每一个不同的loggerName分别记在不同的日志文件中
File file = new File(String.format("%s_%s.log", record.getLoggerName(), DateFormatUtils.format(new Date(), "yyyy-MM-dd")));
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file, true);
PrintWriter pw = new PrintWriter(fw);
String log = String.format("[%s] %s %s.%s: %s\r\n", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"),
record.getLevel().getName(), record.getSourceClassName(), record.getSourceMethodName(), record.getMessage());
pw.write(log);
pw.flush();
} catch (IOException e) {
e.printStackTrace();
} } /**
* 刷新缓存区,保存数据
*/
@Override
public void flush() {
} /**
* 关闭
*
* @throws SecurityException
*/
@Override
public void close() throws SecurityException {
}
} public static void main(String[] args) throws Exception {
//获取自定义的logger
Logger logger = getLogger(SelfJavaLogMain.class);
logger.info("info log");
logger.severe("severe log");
//使用自定义的logger level
logger.log(SelfLevel.ERROR, "error log");
}
}
水电费
003-log-jul,jdk自带日志服务的更多相关文章
- JDK 自带的服务发现框架 ServiceLoader 好用吗?
请点赞关注,你的支持对我意义重大. Hi,我是小彭.本文已收录到 Github · AndroidFamily 中.这里有 Android 进阶成长知识体系,有志同道合的朋友,关注公众号 [彭旭锐] ...
- JDK自带的日志Logging
OK,现在我们来研究下JDK自带的日志Logger. 从jdk1.4起,JDK开始自带一套日志系统.JDK Logger最大的优点就是不需要任何类库的支持,只要有Java的运行环境就可以使用. 相对于 ...
- 【转载】JDK自带的log工具
版权声明:本文为Jaiky_杰哥原创,转载请注明出处.This blog is written by Jaiky, reproduced please indicate. https://blog.c ...
- aliyun 日志服务(Log Service,Log)是针对日志场景的一站式服务
日志服务(Log Service,Log)是针对日志场景的一站式服务,在阿里巴巴集团内部被广泛使用.用户无需开发就能快捷完成日志生命周期中采集.消费.投递以及查询功能. 日志服务当前提供如下功能 日志 ...
- 仵航说 SpringBoot项目配置Log日志服务-仵老大
今天领导让我配置一个log日志服务,我哪里见过哟,然后就去百度了,结果挨个试下去,找到了一个能用的,分享给大家 大致四个地方 分别是 1.pom文件需要引入依赖 2.创建一个TestLog类 3.在y ...
- centos7设置rsyslog日志服务集中服务器
centos7设置rsyslog日志服务集中服务器 环境:centos6.9_x86_64,自带的rsyslog版本是7.4.7,很多配置都不支持,于是进行升级后配置 # 安装新版本的rsyslog程 ...
- 【阿里云产品公测】简单日志服务SLS使用评测 + 教程
[阿里云产品公测]简单日志服务SLS使用评测 + 教程 评测介绍 被测产品: 简单日志服务SLS 评测环境: 阿里云基础ECS x2(1核, 512M, 1M) 操作系统: CentOS 6.5 x6 ...
- CENTOS6.2系统日志rsyslog替换默认的日志服务syslog 转载自http://www.phpboy.net/linux/648.html
最近遇到配置centos 6.2的sshd及sftp日志,发现/etc/syslog.conf文件不存在, 然后: #rpm -qa | grep syslog 出来的是 rsyslog-5.8.10 ...
- JDK内置日志系统
1.Java应用中的日志功能 ================= 一般的Java应用程序中都有记录日志的需求,目前主流的记录日志的方法是在应用程序中引入log4j,用log4j来生成日志.其实,JDK ...
随机推荐
- RT-Thread--简介
RT-Thread 概述 RT-Thread,全称是 Real Time-Thread,它是一个嵌入式实时多线程操作系统,基本属性之一是支持多任务,允许多个任务同时运行,但并不是真正的同时运行,而是宏 ...
- 图像处理---视频<->图片
图像处理---视频<->图片 // 该程序实现视频和图片的相互转换. // Image_to_video()函数将一组图片合成AVI视频文件. // Video_to_image()函数将 ...
- JavaScript基础习题
1.实现输入框的双向绑定 解析:所谓双向绑定,即view->model, model->view,可以考虑对象劫持,监听对象属性的变化 <input type="input ...
- appium+python 【Mac】UI自动化测试封装框架介绍 <五>---脚本编写(多设备)
目的: 通过添加设备号,则自动给添加的设备分配端口,启动对应的appium服务.注意:为了方便,将共用一个配置文件. 1.公共的配置文件名称:desired_caps.yaml platformVer ...
- Illegal mix of collations (utf8mb4_general_ci,IMPLICIT) and (utf8mb4_unicode_ci,IMPLICIT) for operation '<>'
1.问题 今天又在mysql中遇到了,吐血. 2.解决方案 SQL最后加上 COLLATE utf8mb4_unicode_ci SELECT t2.cust_id as cust_id_ex,t1. ...
- 自定义错误throw
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Python 练习实例2
Python 练习实例2 题目:企业发放的奖金根据利润提成.利润(I)低https://www.xuanhe.net/于或等于10万元时,奖金可提10%:利润高于10万元,低于20万元时,低于10万元 ...
- P1578 奶牛浴场 有障碍点的最大子矩形
这题咕咕了很久终于写了\(QwQ\) 思路:扫? 提交:2次 错因:数据差评,第一次把矩形的长宽搞反了竟然只有一个点没有\(A\). 题解: 显然能成为答案的矩形的边界一定有障碍点或者与大矩形边界重合 ...
- jenkins 邮件发送错误
jenkins 在创建新的 Build 的时候希望邮件进行通知. 但是邮件通知的时候出现错误: Unable to Send Mail - javax.net.ssl.SSLException: Un ...
- ECMAScript 5.0 基础语法(上)
银子: 一般来说,一门编程语言的基础语法都是大同小异的.比如,python的基础语法,包括:数据类型,变量,作用域,运算符,流程控制(if...else...语句),循环,编码,数据类型的操作(增删改 ...