Java SpringBoot log4j2.xml文件配置,log4j2输出日志文件带日期,log4j输出日期文件,log4j2的使用

前言

SpringBoot 配置log4j2输出日志

实现

pom.xml依赖

<dependencies>
	
	<dependency>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starterartifactId>
		<exclusions>
			<exclusion>
				<groupId>org.springframework.bootgroupId>
				<artifactId>spring-boot-starter-loggingartifactId>
			exclusion>
		exclusions>
	dependency>
	<dependency>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-log4j2artifactId>
		<exclusions>
			<exclusion>
				<groupId>org.apache.logging.log4jgroupId>
				<artifactId>log4j-coreartifactId>
			exclusion>
			<exclusion>
				<groupId>org.apache.logging.log4jgroupId>
				<artifactId>log4j-apiartifactId>
			exclusion>
			<exclusion>
				<groupId>org.apache.logging.log4jgroupId>
				<artifactId>log4j-slf4j-implartifactId>
			exclusion>
		exclusions>
	dependency>
	
	<dependency>
		<groupId>org.apache.logging.log4jgroupId>
		<artifactId>log4j-apiartifactId>
		<version>${log4j.version}version>
	dependency>
	<dependency>
		<groupId>org.apache.logging.log4jgroupId>
		<artifactId>log4j-coreartifactId>
		<version>${log4j.version}version>
	dependency>
	<dependency>
		<groupId>org.apache.logging.log4jgroupId>
		<artifactId>log4j-slf4j-implartifactId>
		<version>${log4j.version}version>
	dependency>
dependencies>

版本使用

<properties>
	
	<log4j.version>2.17.0log4j.version>
properties>

application.yml文件中配置

#日志配置 无特殊需求无需更改
logging:
  config: classpath:log4j2.xml
  level:
    root: INFO
    javax.activation: info
    org.apache.catalina: INFO
    org.apache.commons.beanutils.converters: INFO
    org.apache.coyote.http11.Http11Processor: INFO
    org.apache.http: INFO
    org.apache.tomcat: INFO
    org.springframework: INFO
    com.chinamobile.cmss.bdpaas.resource.monitor: DEBUG

resources目录下创建log4j2.xml


<Configuration>
    
    
    <properties>
        <property name="LOG_HOME">../logsproperty>
    properties>
    <Appenders>
        
        <Console name="consoleAppender" target="SYSTEM_OUT">
            
            <PatternLayout
                    pattern="%style{%d{ISO8601}}{bright,green} %highlight{%-5level} [%style{%t}{bright,blue}] %style{%C{}}{bright,yellow}: %msg%n%style{%throwable}{red}"
                    disableAnsi="false" noConsoleNoAnsi="false"/>
        Console>

        
        
        <RollingFile name="allFileAppender"
                     fileName="${LOG_HOME}/all.log"
                     filePattern="${LOG_HOME}/$${date:yyyy-MM}/all-%d{yyyy-MM-dd}-%i.log">
            
            <PatternLayout>
                <pattern>%d %p %C{} [%t] %m%npattern>
            PatternLayout>
            <Policies>
                
                
                
                <SizeBasedTriggeringPolicy size="100MB"/>
                
                <TimeBasedTriggeringPolicy/>
            Policies>
            
            <DefaultRolloverStrategy max="100"/>
        RollingFile>

        
        <RollingFile name="debugFileAppender"
                     fileName="${LOG_HOME}/debug.log"
                     filePattern="${LOG_HOME}/$${date:yyyy-MM}/debug-%d{yyyy-MM-dd}-%i.log">
            <Filters>
                
                <ThresholdFilter level="info" onMatch="DENY" onMismatch="NEUTRAL"/>
            Filters>
            
            <PatternLayout>
                <pattern>%d %p %C{} [%t] %m%npattern>
            PatternLayout>
            <Policies>
                
                
                
                <SizeBasedTriggeringPolicy size="100MB"/>
                
                <TimeBasedTriggeringPolicy/>
            Policies>
            
            <DefaultRolloverStrategy max="100"/>
        RollingFile>

        
        <RollingFile name="infoFileAppender"
                     fileName="${LOG_HOME}/info.log"
                     filePattern="${LOG_HOME}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log.gz">
            <Filters>
                
                <ThresholdFilter level="warn" onMatch="DENY" onMismatch="NEUTRAL"/>
            Filters>
            
            <PatternLayout>
                <pattern>%d %p %C{} [%t] %m%npattern>
            PatternLayout>
            <Policies>
                
                
                
                <SizeBasedTriggeringPolicy size="100MB"/>
                
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
            Policies>
            
            
        RollingFile>

        
        <RollingFile name="warnFileAppender"
                     fileName="${LOG_HOME}/warn.log"
                     filePattern="${LOG_HOME}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log.gz">
            <Filters>
                
                <ThresholdFilter level="error" onMatch="DENY" onMismatch="NEUTRAL"/>
            Filters>
            
            <PatternLayout>
                <pattern>%d %p %C{} [%t] %m%npattern>
            PatternLayout>
            <Policies>
                
                
                
                <SizeBasedTriggeringPolicy size="100MB"/>
                
                <TimeBasedTriggeringPolicy/>
            Policies>
            
            <DefaultRolloverStrategy max="100"/>
        RollingFile>

        
        <RollingFile name="errorFileAppender"
                     fileName="${LOG_HOME}/error.log"
                     filePattern="${LOG_HOME}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log.gz">
            
            <PatternLayout>
                <pattern>%d %p %C{} [%t] %m%npattern>
            PatternLayout>
            <Policies>
                
                
                
                <SizeBasedTriggeringPolicy size="100MB"/>
                
                <TimeBasedTriggeringPolicy/>
            Policies>
            
            <DefaultRolloverStrategy max="100"/>
        RollingFile>

        
        <RollingFile name="errorJsonAppender"
                     fileName="${LOG_HOME}/error-json.log"
                     filePattern="${LOG_HOME}/error-json-%d{yyyy-MM-dd}-%i.log.gz">
            <JSONLayout compact="true" eventEol="true" locationInfo="true"/>
            <Policies>
                <SizeBasedTriggeringPolicy size="100MB"/>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
            Policies>
        RollingFile>
    Appenders>

    <Loggers>

        
        <Root level="debug">
            <AppenderRef ref="allFileAppender" level="all"/>
            <AppenderRef ref="consoleAppender" level="debug"/>
            <AppenderRef ref="debugFileAppender" level="debug"/>
            <AppenderRef ref="infoFileAppender" level="info"/>
            <AppenderRef ref="warnFileAppender" level="warn"/>
            <AppenderRef ref="errorFileAppender" level="error"/>
            <AppenderRef ref="errorJsonAppender" level="error"/>
        Root>

        
        <Logger name="org.springframework" level="debug"/>
        
        <Logger name="druid.sql.Statement" level="warn"/>
        
        <Logger name="com.mybatis" level="warn"/>
        <Logger name="org.hibernate" level="warn"/>
        <Logger name="com.zaxxer.hikari" level="info"/>
        <Logger name="org.quartz" level="info"/>
        <Logger name="com.andya.demo" level="debug"/>

    Loggers>

Configuration>

java使用

package com.common.exception;

import com.common.constant.LoggerConstant;
import com.common.vo.Result;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常处理类
 * @author YYQ
 *
 */
@ControllerAdvice
public class MyExceptionHandler {
	
	private static final Logger logger = LogManager.getLogger(MyExceptionHandler.class);
	// 此处logger可使用 org.slf4j.LoggerFactory
	//private static final Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);
	
	
	/**
	 * 全局异常返回json格式
	 * @param requset
	 * @param response
	 * @param ex
	 * @return
	 */
	@ExceptionHandler
	@ResponseBody
	public Result<?> handleAndReturnData(HttpServletRequest requset, HttpServletResponse response, Exception ex){
		logger.info("【日志打印带参数的那种】id:{},name:{}", 1, "张三");
        logger.error(LoggerConstant.ERROR_MSG, ex);// LoggerConstant.ERROR_MSG 错误提示自定义
		return Result.error(Result.ERROR_MSG+":"+ex.toString());
	}



}

Console打印
Java SpringBoot log4j2.xml文件配置,log4j2输出日志文件带日期,log4j输出日期文件,log4j2的使用_第1张图片
输出文件
Java SpringBoot log4j2.xml文件配置,log4j2输出日志文件带日期,log4j输出日期文件,log4j2的使用_第2张图片
如:
6小时后自动生成备份:E:\Development\idea-svn\logs\2022-02\all-2022-02-16-1.log
重新创建:E:\Development\idea-svn\logs\all.log

输出文件带日期说明:

RollingFile节点用于实现日志文件更动更新的Appender,当满足条件(日志大小、指定时间等)重命名或打包原日志文件进行归档,生成新日志文件用于日志写入。

更多参考:https://www.cnblogs.com/Andya/p/13641254.html

你可能感兴趣的:(后端,后端封装效果,Spring,Boot,java,spring,boot,xml)