当前位置:网站首页>Slf4j and log4j2 process logs
Slf4j and log4j2 process logs
2022-07-25 16:27:00 【Brother Xing plays with the clouds】
About log4j
Log4j + Slf4j Is the most common use combination , But we know that Log4j It has stopped updating at present .Apache A new Log4j2 Instead of Log4j,Log4j2 It's right Log4j The upgrade , Its predecessor Log4j There has been a significant improvement in comparison , And provided many Logback Available improvements , At the same time Logback Some inherent problems in the architecture . therefore ,Log4j2 + Slf4j Should be the general trend of the future .
About slf4j
- LF4J Unlike other logging libraries , It is quite different from other logging libraries .SLF4J(Simple logging Facade for Java) Not a real logging implementation , It's an abstraction layer ( abstraction layer), It allows you to use any logging library in the background . If written for internal and external use API Or generic class libraries , Then you really don't want clients that use your library to have to use the logging library of your choice .
- If a project is already in use log4j, And you load a library of classes , For example Apache Active MQ—— It depends on another logging library logback, Then you need to load it in as well . But if Apache Active MQ Used SLF4J, You can continue to use your logging library without the pain of loading and maintaining a new logging framework .
- in general ,SLF4J Make your code independent of any particular log API, This is for API Great ideas from developers . The idea of abstract logging libraries is not new, though , and Apache commons logging It's already in use , but SLF4J Is rapidly becoming Java World logging standards .
Use case
introduce slf4j and log4j2 The core of the package
<!-- slf4j Core packages -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.25</version>
<scope>runtime</scope>
</dependency>
<!--log4j2 Core packages -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>2.8.2</version>
<scope>runtime</scope>
</dependency>
<!--log4j2 Asynchronous rely on -->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.3.6</version>
</dependency>log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="off" monitorInterval="120">
<properties>
<property name="LOG_HOME">/mytest_log</property>
</properties>
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<!--RollingFile Global synchronization RandomAccessFile For asynchronous -->
<RollingRandomAccessFile name="rootAppeder"
fileName="${LOG_HOME}/rattanapi.log"
filePattern="${LOG_HOME}/$${date:yyyy-MM}/rattanapi-root-%d{yyyy-MM-dd}-%i.log">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %ex%msg%n"/>
<Policies>
<TimeBasedTriggeringPolicy interval="1"/>
<SizeBasedTriggeringPolicy size="100 MB"/>
</Policies>
<DefaultRolloverStrategy max="30"/>
</RollingRandomAccessFile>
<!-- Error log output -->
<RollingRandomAccessFile name="errorAppeder"
fileName="${LOG_HOME}/rattanapi-error.log"
filePattern="${LOG_HOME}/$${date:yyyy-MM}/rattanapi-error-%d{yyyy-MM-dd}-%i.log">
<Filters>
<ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
</Filters>
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %ex%msg%n"/>
<Policies>
<TimeBasedTriggeringPolicy interval="1"/>
<SizeBasedTriggeringPolicy size="100 MB"/>
</Policies>
<DefaultRolloverStrategy max="30"/>
</RollingRandomAccessFile>
</appenders>
<loggers>
<asyncRoot level="info">
<!-- Depending on whether the configuration file is open or not console Output -->
<appender-ref ref="Console"/>
<appender-ref ref="rootAppeder"/>
<appender-ref ref="errorAppeder"/>
</asyncRoot>
</loggers>
</configuration>web.xml Set in log4j2 Listeners and filters (servlet3.0 And above versions do not require this step ) Development Servlet3.0 The program needs some environmental support .
<!-- about log4j2,Servlet2.5 Previous versions required -->
<listener>
<listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
</listener>
<filter>
<filter-name>log4jServletFilter</filter-name>
<filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>log4jServletFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>Be careful :log4j2 No longer supported properties The file , Only support xml,json or yaml, Does not specify the location of the default in src/main/resources The lookup .
If you need to customize the location , It needs to be up there web.xml Add the following code in
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>classpath:log4j2.xml</param-value>
</context-param>import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
String world = "world";
logger.info("hellp world:{}",world);
logger.error("exception e");
}
}边栏推荐
- 【故障诊断】基于贝叶斯优化支持向量机的轴承故障诊断附matlab代码
- Save the image with gaussdb (for redis), and the recommended business can easily reduce the cost by 60%
- 只有1000元能买什么理财产品赚钱?
- Typescript learning 1 - data types
- Win11桌面切换快捷键是什么?Win11快速切换桌面的方法
- Product dynamics - Android 13 high-efficiency adaptation new upgrade
- leetcode:528. 按权重随机选择【普通随机失效 + 要用前缀和二分】
- leetcode:154. 寻找旋转排序数组中的最小值 II【关于旋转排序数组的中后定位二分法】
- 聊聊如何用 Redis 实现分布式锁?
- 泰雷兹推出解决方案,助力SAP客户控制云端数据
猜你喜欢

easyui datagrid控件使用

柏睿数据加入阿里云PolarDB开源数据库社区

阿唐的小帮手

2D 语义分割——DeepLabV3plus 复现

Visual studio 2022 view class diagram

easyui下拉框,增加以及商品的上架,下架

Food safety - do you really understand the ubiquitous frozen food?

使用Huggingface在矩池云快速加载预训练模型和数据集

leetcode:154. 寻找旋转排序数组中的最小值 II【关于旋转排序数组的中后定位二分法】

Breakthrough in core technology of the large humanoid Service Robot Walker x
随机推荐
【云驻共创】探秘GaussDB如何助力工商银行打造金融核心数据
首页门户分类查询
狂神redis笔记12
Permission management - delete menu (recursive)
自定义mvc项目登录注册和树形菜单
Google Earth Engine——全球建筑物GlobalMLBuildingFootprints矢量集合下载
Crazy God redis notes 12
柏睿数据加入阿里云PolarDB开源数据库社区
Is the win11 dynamic tile gone? Method of restoring dynamic tile in Win 11
Breakthrough in core technology of the large humanoid Service Robot Walker x
Analysis and solution of data and clock mismatch delay in SPI transmission
MySQL self incrementing lock
01.一个更简单的方法来传递大量的props
测试驱动开发(TDD)在线练功房 | 9月17日开课
Leetcode:6127. Number of high-quality number pairs [bit operation finding rules + the sum of two numbers is greater than or equal to K + dichotomy]
What is a physical firewall? What's the effect?
Typescript learning 2 - Interface
MySQL table read lock
MySQL视图
Leetcode:528. select randomly according to the weight [ordinary random failure + prefix and dichotomy]