헤르메스 LIFE

[Spring Boot] 개발환경 구축 - Logback 본문

Spring Boot Framework

[Spring Boot] 개발환경 구축 - Logback

헤르메스의날개 2023. 1. 29. 22:05
728x90

AppSpringBoot.zip
0.07MB

개발환경

1. STS 버전 : 4.13.1

2. JDK 버전 : OpenJDK 11.0.14_9_x64

3. Tomcat 버전 : 9.0.71

4. Maven 버전 : 3.8.4

5. Spring 버전 : Spring Boot 2.7.8

6. Thymeleaf 3.0.15


pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.8</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>simple.spring</groupId>
	<artifactId>SimpleSpringBoot</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SimpleSpringBoot</name>
	<description>Simple Spring Boot Project</description>
	<properties>
		<java.version>11</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.3.0</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.postgresql</groupId>
			<artifactId>postgresql</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

Logback 기본 설정

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="30 seconds">
    <!-- 로그 파일이 저장될 경로 -->
    <property name="LOG_PATH" value="C:/greenhorn/logs" />
    <!--로그 파일 저장 위치 -->
    <property name="LOG_FILE_DEV" value="logback-dev#1" />
    <property name="LOG_FILE_PRD" value="logback-prd#1" />

    <!-- pattern -->
    <property name="LOG_PATTERN" value="%-5level %d{yy-MM-dd HH:mm:SSS}[%thread] %logger[%method:%line] - %msg%n" />

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${LOG_PATTERN}</pattern>
        </encoder>
    </appender>
    <appender name="ROLLING-FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_PATH}/${LOG_FILE_DEV}.log</file>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${LOG_PATTERN}</pattern>
            <charset>UTF-8</charset>
        </encoder>
        <!-- Rolling 정책 -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- .gz,.zip 등을 넣으면 자동 일자별 로그파일 압축 -->
            <fileNamePattern>${LOG_PATH}/${LOG_FILE_DEV}.%d{yyyy-MM-dd}.%i.gz</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <!-- 파일당 최고 용량 kb, mb, gb -->
                <maxFileSize>100MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <!-- 일자별 로그파일 최대 보관주기(~일), 해당 설정일 이상된 파일은 자동으로 제거 -->
            <maxHistory>30</maxHistory>
        </rollingPolicy>
    </appender>

    <logger name="simple" level="debug" additivity="false">
        <!-- ref="appender name 지정" -->
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="ROLLING-FILE" />
    </logger>
    <root level="debug">
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="ROLLING-FILE" />
    </root>

</configuration>

Logback Extensions 기능

- logback-spring.xml 파일에서만 사용가능

- <springProfiles></springProfiles> 태그 활용 가능

- <configuration scan="true" scanPeriod="30 seconds"> 사용 불가


아래의 설정은 Spring Boot에서 지원하는 기본 Default 설정을 사용하기위해, application.yml 에 설정을 추가하는 방법을 사용합니다.

logback-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml" />
    <include resource="org/springframework/boot/logging/logback/console-appender.xml" />
    <include resource="org/springframework/boot/logging/logback/file-appender.xml" />

    <springProfile name="dev">
        <logger name="org.springframework.boot" level="WARN" additivity="false" />
        <logger name="org.springframework.web" level="WARN" additivity="false" />
        
        <logger name="simple" level="debug" additivity="false">
            <!-- ref="appender name 지정" -->
            <appender-ref ref="CONSOLE" />
        </logger>
        <root level="DEBUG">
            <appender-ref ref="CONSOLE" />
        </root>
    </springProfile>

    <springProfile name="prod">
        <logger name="org.springframework" level="WARN" additivity="false" />
        
        <logger name="simple" level="debug" additivity="false">
            <!-- ref="appender name 지정" -->
            <appender-ref ref="FILE" />
        </logger>
        <root level="DEBUG">
            <appender-ref ref="FILE" />
        </root>
    </springProfile>

</configuration>

logback.xml 설정 파일은 너무 빨리 로딩되기 때문에, extension을 사용하기 어렵습니다. 그러므로 logging.conifg를 정의해서 logback-spring.xml 을 사용해야 합니다.

logging.config=classpath:logback-spring.xml 로 지정을 해주어야 합니다.

# Logback 설정
logging.level.root=info
logging.config=classpath:logback-spring.xml 
spring.output.ansi.enabled=ALWAYS

application.yml

# Logging
logging:
  level:
  	root: info
    org:
      hibernate:
        SQL: debug
        type:
          descriptor:
            sql: trace
  pattern:
    console: "%-5level %d{yy-MM-dd HH:mm:SSS}[%thread] %logger[%method:%line] - %msg%n"
    file: "%-5level %d{yy-MM-dd HH:mm:SSS}[%thread] %logger[%method:%line] - %msg%n"
  file:
    name: C:/greenhorn/logs/logback-dev#2.log
  logback:
    rollingpolicy:
      max-file-size: 1MB                #default 10M
      max-history: 31                   #default 7
      file-name-pattern: ${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz

# Server port
server:
  port: 9091
  servlet:
    context-path: /
    encoding:
      enabled: true
      charset: UTF-8
      force: true
    session:
      timeout: 120                              # 기본단위 : 초
      
  tomcat:
    uri-encoding: UTF-8                         # Spring Default : UTF-8

spring:
  thymeleaf:
    cache: false
    
spring:
  datasource:
    url: jdbc:h2:tcp://localhost/~/jpashop
    username: sa
    password:
    driver-class-name: org.h2.Driver

  jpa:
    hibernate:
      ddl-auto: create
    properties:
      hibernate:
        #show_sql: true
        format_sql: true
        highlight_sql: true
        use_sql_comments: true
        format_sql: true
        SQL: debug
        type:
          descriptor.sql=trace
      jakarta:
        persistence:
          sharedCache:
            mode: ALL

    open-in-view: false

VM arguments ( -Dspring.profiles.active=dev )


customization을 돕기 위해 다음 표에 설명된 대로 일부 다른 properties가 Spring Environment에서 System properties로 전달됩니다.

Spring Environment System Property Comments
logging.exception-conversion-word LOG_EXCEPTION_CONVERSION_WORD The conversion word used when logging exceptions.
logging.file.name LOG_FILE If defined, it is used in the default log configuration.
logging.file.path LOG_PATH If defined, it is used in the default log configuration.
logging.pattern.console CONSOLE_LOG_PATTERN The log pattern to use on the console (stdout).
logging.pattern.dateformat LOG_DATEFORMAT_PATTERN Appender pattern for log date format.
logging.charset.console CONSOLE_LOG_CHARSET The charset to use for console logging.
logging.pattern.file FILE_LOG_PATTERN The log pattern to use in a file (if LOG_FILE is enabled).
logging.charset.file FILE_LOG_CHARSET The charset to use for file logging (if LOG_FILE is enabled).
logging.pattern.level LOG_LEVEL_PATTERN The format to use when rendering the log level (default %5p).
PID PID The current process ID (discovered if possible and when not already defined as an OS environment variable).

logback을 사용하는 경우 다음 properties도 전달됩니다.

Spring Environment System Property Comments
logging.logback.rollingpolicy.file-name-pattern LOGBACK_ROLLINGPOLICY_FILE_NAME_PATTERN Pattern for rolled-over log file names (default ${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz).
logging.logback.rollingpolicy.clean-history-on-start LOGBACK_ROLLINGPOLICY_CLEAN_HISTORY_ON_START Whether to clean the archive log files on startup.
logging.logback.rollingpolicy.max-file-size LOGBACK_ROLLINGPOLICY_MAX_FILE_SIZE Maximum log file size.
logging.logback.rollingpolicy.total-size-cap LOGBACK_ROLLINGPOLICY_TOTAL_SIZE_CAP Total size of log backups to be kept.
logging.logback.rollingpolicy.max-history
LOGBACK_ROLLINGPOLICY_MAX_HISTORY Maximum number of archive log files to keep.

지원되는 모든 logging system은 configuration file을 parsing 할 때 system properties를 참조할 수 있습니다.
spring-boot.jar의 default configuration을 참조하세요.


https://hermeslog.tistory.com/549

 

[SpringBoot] Logback 설정

Inteceptor 에서 Log를 찍고 싶은데, 찍을 수가 없습니다. logback.xml 은 정상적으로 Log가 찍힙니다. 하지만 logback의 확장기능을 사용하고 싶어서 포기가 안되네요. package com.study.wings.interceptor; import org.

hermeslog.tistory.com

https://hermeslog.tistory.com/662

 

[Spring Boot] Spring Boot + Hello Thymeleaf

개발환경 1. STS 버전 : 4.13.1 2. JDK 버전 : OpenJDK 11.0.14_9_x64 3. Tomcat 버전 : 9.0.71 4. Maven 버전 : 3.8.4 5. Spring 버전 : Spring Boot 2.7.8 6. Thymeleaf 3.0.15 pom.xml 4.0.0 org.springframework.boot spring-boot-starter-parent 2.7.8 sim

hermeslog.tistory.com

https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html#logging.charset.console

 

Common Application Properties

 

docs.spring.io

https://docs.spring.io/spring-boot/docs/2.6.7/reference/html/features.html#features.logging

 

Core Features

Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use a variety of external configuration sources, include Java properties files, YAML files, environment variables, an

docs.spring.io

 

728x90