>  기사  >  Java  >  SpringBoot 프로젝트에 콘솔 로그를 저장하는 방법

SpringBoot 프로젝트에 콘솔 로그를 저장하는 방법

王林
王林앞으로
2023-05-24 11:52:061338검색

SpringBoot 콘솔 로그 저장 구성

시나리오: 콘솔 로그는 SpringBoot 프로젝트에 저장되어야 합니다.

구현 방법:

1. 구성 파일 application-prod.yml

을 다음과 같이 구성합니다.

logging:
  config: classpath:logback-spring-prod.xml

2.logback-spring-prod.xml

이 파일은 콘솔 인쇄 로그를 저장하고 구성하는 경로입니다.

<?xml version="1.0" encoding="UTF-8"?>
 
<!-- 分级别异步文件日志输出配置 -->
<configuration>
    <!-- 日志级别 -->
    <property name="logLevel" value="INFO"></property>
    <!-- 日志地址 -->
    <property name="logPath" value="/usr/server/shop/logs/"></property>
    <property name="logPathDebug" value="/usr/server/shop/logs/debug/"></property>
    <property name="logPathInfo" value="/usr/server/shop/logs/info/"></property>
    <property name="logPathWarn" value="/usr/server/shop/logs/warn/"></property>
    <property name="logPathError" value="/usr/server/shop/logs/error/"></property>
    <!-- 最大保存时间 -->
    <property name="maxHistory" value="30"/>
    <!-- 异步缓冲队列的深度,该值会影响性能.默认值为256 -->
    <property name="queueSize" value="512"></property>
    <!--日志文件名前缀-->
    <property name="name" value="shop_prod"></property>
 
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%black(%contextName -) %red(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{60}) - %gray(%msg%n)</pattern>
        </encoder>
    </appender>
 
    <appender name="FILE_DEBUG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>DEBUG</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <file>${logPathDebug}/${name}_debug.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${logPathDebug}/${name}_debug.log.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxHistory>${maxHistory}</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>50MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [ %thread ] - [ %-5level ] [ %logger{50} : %line ] - %msg%n</pattern>
        </encoder>
    </appender>
 
    <appender name="FILE_INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <file>${logPathInfo}/${name}_info.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${logPathInfo}/${name}_info.log.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxHistory>${maxHistory}</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>50MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [ %thread ] - [ %-5level ] [ %logger{50} : %line ] - %msg%n</pattern>
        </encoder>
    </appender>
 
    <appender name="FILE_WARN" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>WARN</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <file>${logPathWarn}/${name}_warn.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${logPathWarn}/${name}_warn.log.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxHistory>${maxHistory}</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>50MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [ %thread ] - [ %-5level ] [ %logger{50} : %line ] - %msg%n</pattern>
        </encoder>
    </appender>
 
    <appender name="FILE_ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <file>${logPathError}/${name}_error.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${logPathError}/${name}_error.log.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxHistory>${maxHistory}</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>50MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [ %thread ] - [ %-5level ] [ %logger{50} : %line ] - %msg%n</pattern>
        </encoder>
    </appender>
 
    <appender name="ASYNC_LOG_DEBUG" class="ch.qos.logback.classic.AsyncAppender">
        <!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUG、INFO级别的日志 -->
        <discardingThreshold>0</discardingThreshold>
        <!-- 更改默认的队列的深度,该值会影响性能.默认值为256 -->
        <queueSize>${queueSize}</queueSize>
        <appender-ref ref="FILE_DEBUG"/>
    </appender>
 
    <appender name="ASYNC_LOG_INFO" class="ch.qos.logback.classic.AsyncAppender">
        <!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUG、INFO级别的日志 -->
        <discardingThreshold>0</discardingThreshold>
        <!-- 更改默认的队列的深度,该值会影响性能.默认值为256 -->
        <queueSize>${queueSize}</queueSize>
        <appender-ref ref="FILE_INFO"/>
    </appender>
 
    <appender name="ASYNC_LOG_WARN" class="ch.qos.logback.classic.AsyncAppender">
        <!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUG、INFO级别的日志 -->
        <discardingThreshold>0</discardingThreshold>
        <!-- 更改默认的队列的深度,该值会影响性能.默认值为256 -->
        <queueSize>${queueSize}</queueSize>
        <appender-ref ref="FILE_WARN"/>
    </appender>
 
    <appender name="ASYNC_LOG_ERROR" class="ch.qos.logback.classic.AsyncAppender">
        <!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUG、INFO级别的日志 -->
        <discardingThreshold>0</discardingThreshold>
        <!-- 更改默认的队列的深度,该值会影响性能.默认值为256 -->
        <queueSize>${queueSize}</queueSize>
        <appender-ref ref="FILE_ERROR"/>
    </appender>
 
    <root level="${logLevel}">
        <!-- appender referenced after it is defined -->
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="ASYNC_LOG_DEBUG"/>
        <appender-ref ref="ASYNC_LOG_INFO"/>
        <appender-ref ref="ASYNC_LOG_WARN"/>
        <appender-ref ref="ASYNC_LOG_ERROR"/>
    </root>
 
</configuration>

참고:

<property name="logPath" value="/usr/server/shop/logs/"></property>

에 로그가 저장되는 경로는 /usr/server/shop/logs/에 저장됩니다.

SpringBoot 프로젝트에서 서비스의 런타임 로그를 저장하는 방법

이 문제는 비교적 간단하므로 두 단계만 완료하면 됩니다.

log4j 출력 로그 파일을 구성하세요

pom에서 lombok 종속성을 인용해야 합니다. 버전은 springboot 버전을 따릅니다.

<dependency>
 <groupId>org.projectlombok</groupId>
 <artifactId>lombok</artifactId>
 <optional>true</optional>
</dependency>
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds"
	debug="false">
	<contextName>StudentContext</contextName>
	<property name="log.path" value="./logs" />
	<!--输出到控制台 -->
	<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
		<encoder>
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{76}.%M\(%line\) - %msg%n</pattern>
			<charset>UTF-8</charset>
		</encoder>
	</appender>
	<!-- 全部日志 -->
	<appender name="all" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${log.path}/student/student.%d{yyyy-MM-dd}.log</fileNamePattern>
			<maxHistory>60</maxHistory>
		</rollingPolicy>
		<encoder>
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{76}.%M\(%line\) - %msg%n</pattern>
			<charset>UTF-8</charset>
		</encoder>
	</appender>
	<!-- 输出到warn -->
	<appender name="warn" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${log.path}/student/student.warn.%d{yyyy-MM-dd}.log</fileNamePattern>
			<maxHistory>60</maxHistory>
		</rollingPolicy>
		<encoder>
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{76}.%M\(%line\) - %msg%n</pattern>
			<charset>UTF-8</charset>
		</encoder>
		<filter class="ch.qos.logback.classic.filter.LevelFilter"><!-- 只打印WARN日志 -->
			<level>WARN</level>
			<onMatch>ACCEPT</onMatch>
			<onMismatch>DENY</onMismatch>
		</filter>
	</appender>
	
	<!-- 输出到error -->
	<appender name="error" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${log.path}/student/student.error.%d{yyyy-MM-dd}.log</fileNamePattern>
			<maxHistory>60</maxHistory>
		</rollingPolicy>
		<encoder>
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{76}.%M\(%line\) - %msg%n</pattern>
			<charset>UTF-8</charset>
		</encoder>
		<filter class="ch.qos.logback.classic.filter.LevelFilter"><!-- 只打印ERROR日志 -->
			<level>ERROR</level>
			<onMatch>ACCEPT</onMatch>
			<onMismatch>DENY</onMismatch>
		</filter>
	</appender>
	<root level="info">
		<appender-ref ref="console" />
		<appender-ref ref="all" />
		<appender-ref ref="warn" />
		<appender-ref ref="error" />
	</root>
</configuration>

log4j 출력 로그 파일을 리소스 아래에 넣으면 됩니다. fileNamePattern 태그의 항목은 학생 관리 시스템 I과 같은 마이크로서비스의 역할을 식별하는 항목으로 대체됩니다. 작성했기 때문에 Student를 사용합니다

애플리케이션에서 이 구성 파일의 위치를 ​​지정하세요

logging:
  level:
    com.netflix.discovery.shared.resolver.aws.ConfigClusterResolver: WARN
  config: classpath:logback-common.xml

위 내용은 SpringBoot 프로젝트에 콘솔 로그를 저장하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제