日志的搭建

@

提示:本文仅供学习交流,请勿用于非法活动!


前言

本文内容: 日志搭建

一、依赖

 <!-- Spring集成日志包 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.logback-extensions</groupId>
            <artifactId>logback-ext-spring</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </dependency>

二、日志文件

在resource -- profiles 文件下新建logback.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">

	<property name="project_name" value="com.demo" />

	<contextName>${project_name}</contextName>
	<property name="file_path" value="/logs/${project_name}"/>

	<!-- 日志输出源,输出日志到文件,不满足某个条件时将日志输出到另一个文件 -->
	<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<file>${file_path}/error.log</file>
		<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<!-- 每天日志归档路径以及格式 -->
			<fileNamePattern>${file_path}/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
			<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
				<maxFileSize>100MB</maxFileSize>
			</timeBasedFileNamingAndTriggeringPolicy>
			<!--日志文件保留天数-->
			<maxHistory>30</maxHistory>
		</rollingPolicy>
		<!-- 日志格式化器 -->
		<encoder>
			<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
		</encoder>
		<!-- 此日志文件只记录info级别的 -->
		<filter class="ch.qos.logback.classic.filter.LevelFilter">
			<level>ERROR</level>
			<onMatch>ACCEPT</onMatch>
			<onMismatch>DENY</onMismatch>
		</filter>
	</appender>

	<!-- 时间滚动输出 level为 INFO 日志 -->
	<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<file>${file_path}/info.log</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${file_path}/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
			<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
				<maxFileSize>100MB</maxFileSize>
			</timeBasedFileNamingAndTriggeringPolicy>
			<maxHistory>30</maxHistory>
		</rollingPolicy>
		<encoder>
			<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
		</encoder>
		<!-- 此日志文件只记录info级别的 -->
		<filter class="ch.qos.logback.classic.filter.LevelFilter">
			<level>INFO</level>
			<onMatch>ACCEPT</onMatch>
			<onMismatch>DENY</onMismatch>
		</filter>
	</appender>

	<!-- 时间滚动输出 level为 DEBUG 日志 -->
	<appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<file>${file_path}/debug.log</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${file_path}/log-debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
			<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
				<maxFileSize>100MB</maxFileSize>
			</timeBasedFileNamingAndTriggeringPolicy>
			<maxHistory>30</maxHistory>
		</rollingPolicy>
		<encoder>
			<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
		</encoder>
		<!-- 此日志文件只记录info级别的 -->
		<filter class="ch.qos.logback.classic.filter.LevelFilter">
			<level>DEBUG</level>
			<onMatch>ACCEPT</onMatch>
			<onMismatch>DENY</onMismatch>
		</filter>
	</appender>
	<!-- 根日志输出器:级别TRACE、DEBUG、INFO、WARN、ERROR、ALL、OFF -->
	<root level="ERROR">
		<appender-ref ref="ERROR_FILE" />
	</root>
	<root level="INFO">
		<appender-ref ref="INFO_FILE" />
	</root>
	<root level="DEBUG">
		<appender-ref ref="DEBUG_FILE" />
	</root>

	<!--myibatis log configure-->
	<logger name="com.apache.ibatis" level="TRACE"/>
	<logger name="java.sql.Connection" level="DEBUG"/>
	<logger name="java.sql.Statement" level="DEBUG"/>
	<logger name="java.sql.PreparedStatement" level="DEBUG"/>
	<logger name="com.cherry.shop" level="DEBUG"/>

</configuration>

三、代码编写

需要输出日志的类

@Controller
@RequestMapping("/jobSummary")
public class JobSummaryController {
	// 为该类打上日志
    private final static Logger logger = LoggerFactory.getLogger(JobSummaryController.class);
    @Autowired
    private JobSummaryService jobSummaryService;
    
    /**
     * 修改工作总结
     * @param params
     * @param r
     * @return
     */
    @RequestMapping("/insertJobSummary")
    @ResponseBody
    public Result insertJobSummary(@Valid @RequestBody JobSummaryDto params, BindingResult r){
        try{
        	// 参数检测+
            if(r.hasErrors()){
                return Results.error();
            }
            if(!StringUtils.isBlank(params.getId())){
                // 修改
                JobSummary jobSummary = jobSummaryService.selectById(params.getId());
                jobSummary.setJobContent(params.getJobContent());
                jobSummaryService.updateById(jobSummary);
           
            }
            return Results.opOk();
        } catch (Exception e) {
            logger.error("修改工作总结失败!params:"+params.toString(),e);
            return Results.updateError();
        }
    }

}

四、日志输出

在定义的目录下生成了三个日志文件:
在这里插入图片描述
其中我修改了工作总结,日志记录在debug文件里:

2021-12-03 12:11:23.194 [http-nio-8080-exec-6] DEBUG o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor - Written [Result [code=0, message=查询成功!, success=true, data=[JobSummary(id=687ea022c3744e628c5bcd8727a80002,
jobContent=日常工作开展)]]] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@4ebbb7ef]


随心所往,看见未来。Follow your heart,see night!

欢迎点赞、关注、留言,一起学习、交流!

posted @ 2022-08-13 23:21  folyh  阅读(75)  评论(0编辑  收藏  举报