In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "Log configuration tutorial and framework performance comparison". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. Summary
No matter what programming language or framework is used, log output is almost ubiquitous and is an essential part of any commercial software.
To sum up, the uses of logs can be summarized into the following three categories:
Problem tracking: the log not only includes some bug of our program, but also can find the problem when installing the configuration.
Status monitoring: through real-time analysis of the log, you can monitor the running status of the system, so as to find and deal with problems early.
Security audit: the audit is mainly reflected in security. Through the analysis of the log, we can find out whether there are unauthorized operations.
Take the Java programming language as an example, there are many ways to print logs, such as outputting key information to the console through the System.out.print () method, or through the log Logger class that comes with JDK. Although JDK supports log output from 1.4, it has a single function and can not better meet business requirements, so many third-party log libraries have been born, such as log4j, log4j2, logback and so on. The API functions provided are far better than the Logger provided by JDK.
II. Log4j
2.1. Introduction
Log4j is a very popular logging framework pioneered by Ceki G ü lc ü before contributing its open source to the Apache Software Foundation.
Log4j has three main components: Loggers (logger), Appenders (output source), and Layouts (layout). Here, it can be simply understood as the type of log, where the log is to be output, and how the log is output.
A combination of these three components makes it easy to record the type and level of information, and to control the style and location of log output at run time.
The architecture of Log4j is roughly as follows:
When we use Log4j to output a log, Log4j automatically outputs the same log to different destinations through different Appender (output source). For example:
Console: output to screen
File: exporting to fil
Socket: output to remote computers over the network
Jdbc: exporting to database
In the process of outputting the log, Filter is used to filter which log needs to be output and which log does not need to be output.
Among the Loggers components, there are five levels: DEBUG, INFO, WARN, ERROR, and FATAL.
These five levels are in order, DEBUG.
< INFO < WARN < ERROR < FATAL,分别用来指定这条日志信息的重要程度,明白这一点很重要,Log4j有一个规则:只输出级别不低于设定级别的日志信息。 假设Loggers级别设定为INFO,则INFO、WARN、ERROR和FATAL级别的日志信息都会输出,而级别比INFO低的DEBUG则不会输出。 最后,通过Layout来格式化日志信息,例如,自动添加日期、时间、方法名称等信息。 具体输出样式配置,可以参考如下内容Log4j2 - Layouts布局介绍 2.2、项目应用 以 Java 项目为例,在 Maven 的pom.xml中添加如下依赖! 2.2.1、添加 maven 依赖 org.slf4j slf4j-api 1.6.6 org.slf4j slf4j-log4j12 1.6.6 log4j log4j 1.2.17 2.2.2、创建log4j配置 在实际应用中,要使Log4j在系统中运行须事先设定配置文件。 配置文件实际上也就是对Logger、Appender及Layout进行相应设定。 Log4j支持两种配置文件格式,一种是XML格式的文件,一种是properties属性文件,二选一。 创建一个log4j.xml或者log4j.properties,将其放入项目根目录下。 1、XML格式 2、XML格式 log4j.rootLogger=INFO,M,C,E log4j.additivity.monitorLogger=false # INFO级别文件输出配置 log4j.appender.M=org.apache.log4j.DailyRollingFileAppender log4j.appender.M.File=/logs/info.log log4j.appender.M.ImmediateFlush=false log4j.appender.M.BufferedIO=true log4j.appender.M.BufferSize=16384 log4j.appender.M.Append=true log4j.appender.M.Threshold=INFO log4j.appender.M.DatePattern='.'yyyy-MM-dd log4j.appender.M.layout=org.apache.log4j.PatternLayout log4j.appender.M.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} %p %l %m %n # ERROR级别文件输出配置 log4j.appender.E=org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File=/logs/error.log log4j.appender.E.ImmediateFlush=true log4j.appender.E.Append=true log4j.appender.E.Threshold=ERROR log4j.appender.E.DatePattern='.'yyyy-MM-dd log4j.appender.E.layout=org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} %p %l %m %n # 控制台输出配置 log4j.appender.C=org.apache.log4j.ConsoleAppender log4j.appender.C.Threshold=INFO log4j.appender.C.layout=org.apache.log4j.PatternLayout log4j.appender.C.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %l %m %n 2.2.3、log4j使用 在需要打印日志的类中,引入Logger类,在需要的地方打印即可! package org.example.log4j.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LogPrintUtil { /**log静态常量*/ private static final Logger logger = LoggerFactory.getLogger(LogPrintUtil.class); public static void main(String[] args){ logger.info("info信息"); logger.warn("warn信息"); logger.error("error信息"); } } 当然你还可以这样写 if(logger.isInfoEnabled()) { logger.info("info信息"); } if(logger.isWarnEnabled()) { logger.warn("warn信息"); } 2.2.4、isInfoEnabled()有何作用呢? 简单来说,在某些场景下,用isInfoEnabled()方法判断下是能提升性能的! 例如我们打印这段内容logger.info("User:" + userId + appId),程序在打印这行代码时,先对内容("User:" + userId + appId)进行字符串拼接,然后再输出。 如果当前配置文件中日志输出级别是info,是直接输出的,当日志输出级别是error时,logger.info()的内容时不输出的,但是我们却进行了字符串拼接,如果加上if(logger.isInfoEnabled())进行一次判定,logger.info()就不会执行,从而更好的提升性能,这个尤其是在高并发和复杂log打印情况下提升非常显著。 另外,ERROR及其以上级别的log信息是一定会被输出的,所以只有logger.isDebugEnabled、logger.isInfoEnabled和logger.isWarnEnabled()方法,而没有logger.isErrorEnabled方法。 三、Log4j2 3.1、介绍 log4j2 是 log4j 1.x 的升级版,参考了 logback 的一些优秀的设计,并且修复了一些问题,因此带来了一些重大的提升,主要特点有: 异常处理:在logback中,Appender中的异常不会被应用感知到,但是在log4j2中,提供了一些异常处理机制。 性能提升, log4j2相较于log4j 1和logback都具有很明显的性能提升,后面会有官方测试的数据。 自动重载配置:参考了logback的设计,当然会提供自动刷新参数配置,最实用的就是我们在生产上可以动态的修改日志的级别而不需要重启应用——那对监控来说,是非常敏感的。 无垃圾机制:log4j2在大部分情况下,都可以使用其设计的一套无垃圾机制,避免频繁的日志收集导致的jvm gc。 3.2、项目应用 3.2.1、添加 maven 依赖 org.slf4j slf4j-api 1.7.13 org.slf4j jcl-over-slf4j 1.7.13 runtime org.apache.logging.log4j log4j-api 2.4.1 org.apache.logging.log4j log4j-core 2.4.1 org.apache.logging.log4j log4j-slf4j-impl 2.4.1 com.lmax disruptor 3.2.0 3.2.2、创建log4j2配置 在项目的根目录下创建一个log4j2.xml的文件,与log4j相比,log4j2的异步输出日志性能非常强劲,配置如下: 1、同步输出日志 /logs/log4j2 /logs/log4j2/history 2、异步输出日志 /logs/log4j2 /logs/log4j2/history 详细 API 可以参考官方网站! 3.2.3、log4j2使用 与 log4j 类似,直接在需要位置打印日志即可 package org.example.log4j.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LogPrintUtil { /**log静态常量*/ private static final Logger logger = LoggerFactory.getLogger(LogPrintUtil.class); public static void main(String[] args){ logger.info("info信息"); logger.warn("warn信息"); logger.error("error信息"); } } 四、Logback 4.1、介绍 Logback 也是用 java 编写一款非常热门的日志开源框架,由 log4j 创始人写的,性能比 log4j 要好! logback 主要分为3个模块: logback-core:核心代码模块 logback-classic:log4j的一个改良版本,同时实现了slf4j的接口,这样你如果之后要切换其他日志组件也是一件很容易的事 logback-access:访问模块与Servlet容器集成提供通过Http来访问日志的功能 4.2、项目应用 4.2.1、添加 maven 依赖 ch.qos.logback logback-classic 1.2.3 org.codehaus.janino janino 2.7.8 4.2.2、创建logback配置文件 1、配置说明 logback在启动的时候,会按照下面的顺序加载配置文件: 如果java程序启动时指定了logback.configurationFile属性,就用该属性指定的配置文件。如java -Dlogback.configurationFile=/path/to/mylogback.xml Test,这样执行Test类的时候就会加载/path/to/mylogback.xml配置 在classpath中查找logback.groovy文件 在classpath中查找logback-test.xml文件 在classpath中查找logback.xml文件 如果是jdk6+,那么会调用ServiceLoader查找 com.qos.logback.classic.spi.Configurator接口的第一个实现类 自动使用ch.qos.logback.classic.BasicConfigurator,在控制台输出日志 上面的顺序表示优先级,使用java -D配置的优先级最高,只要获取到配置后就不会再执行下面的流程。相关代码可以看ContextInitializer#autoConfig()方法。 2、同步输出日志 ${CONTEXT_NAME} ${CUSTOM_LOG_PATTERN} UTF-8 log/testC.%d{yyyy-MM-dd}.%i.log 30 100MB WARN ACCEPT DENY ${CUSTOM_LOG_PATTERN} UTF-8 ${logs.dir}/logback-test.log ${logs.dir}/logback-test.%i.log 1 3 INFO ACCEPT DENY 30MB ${CUSTOM_LOG_PATTERN} UTF-8 注意:logback如果配置要输出行号,性能会明显降低,如果不是必须,建议不要配置! 4.2.3、logback使用 package org.example.logback.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LogPrintUtil { /**log静态常量*/ private static final Logger logger = LoggerFactory.getLogger(LogPrintUtil.class); public static void main(String[] args){ logger.info("info信息"); logger.warn("warn信息"); logger.error("error信息"); } } 五、SLF4J桥接 细心的你,会发现上面代码使用时,都使用的是private static final Logger logger = LoggerFactory.getLogger(LogPrintUtil.class)这个,其中都来自org.slf4j包,SLF4J是啥?有什么作用呢? SLF4J本身并不输出日志,最大的特色是**:它可以通过适配的方式挂接不同的日志系统,属于一个日志接口**。 如果项目适配到log4j就使用log4j日志库进行输出;如果适配到logback就使用logback日志库进行输出;如果适配到log4j2就使用log4j2日志库进行输出。 这样最大的好处,就是当你想将项目从log4j换成log4j2的时候,只需要在项目pom.xml中进行桥接适配即可,不用修改具体需要打印日志的代码! 六、三大主流日志框架性能比较 介绍了这么多,但是我们还不知道三个日志框架的日志输出性能如何,本文以10000条数据进行打印,比较log4j、log4j2、logback日志的输出时间。 本次测试采用的是本地电脑(win7),每个电脑的配置不一样,测试的结果也不一样,结果是真实的。 同步输出 异步输出As can be seen from the test results:
Console output in production environment is not recommended
In the pure file output environment, the output of logback is better than log4j2, while log4j2 is better than log4j. If you want to deploy in the production environment, it is recommended to use logback. If you use log4j2, it is recommended to use asynchronous output. The output result is basically real-time output.
The last thing to note is that log is risky, so you need to be careful about its output!
Because the output log process requires disk operation, and log4j uses synchronization locks to ensure the thread safety of the log output process, the output log becomes a very time-consuming operation, so the log information must be concise and do not output some useless log.
This is the end of the content of "Log configuration tutorial and framework performance comparison". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.