Web Spring 전정프

전자정부프레임워크 log4j2 로그 DB 저장 방법

zeuz 2021. 1. 21. 13:43
반응형

1. 로그가 저장될 테이블 생성

CREATE TABLE `log` (
	`reg_dt` DATETIME NULL DEFAULT NULL,
	`level` VARCHAR(100) NULL DEFAULT NULL,
	`logger` VARCHAR(100) NULL DEFAULT NULL,
	`message` LONGTEXT NULL,
	`exception` LONGTEXT NULL
)

 

2. 메이븐 추가 pom.xml

<dependency>
	<groupId>commons-dbcp</groupId>
	<artifactId>commons-dbcp</artifactId>
	<version>1.4</version>
</dependency>
<dependency>
	<groupId>commons-pool</groupId>
	<artifactId>commons-pool</artifactId>
	<version>1.6</version>
</dependency>

 

3. DatabaseConnection 클래스 생성

package net.example.db;
 
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
 
import javax.sql.DataSource;
 
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnection;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.impl.GenericObjectPool;
 
public class ConnectionFactory {
    private static interface Singleton {
        final ConnectionFactory INSTANCE = new ConnectionFactory();
    }
 
    private final DataSource dataSource;
 
    private ConnectionFactory() {
        Properties properties = new Properties();
        properties.setProperty("user", "logging"); //db 계정
        properties.setProperty("password", "abc123"); // db 비밀번호
        
    	try {
    		loadDriver("com.mysql.jdbc.Driver"); //db드라이버 
    	} catch (SQLException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}
 
        GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>();
        DriverManagerConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
                "jdbc:mysql://example.org:3306/exampleDb", properties              
        );// db 주소
        new PoolableConnectionFactory(
                connectionFactory, pool, null, "SELECT 1", 3, false, false, Connection.TRANSACTION_READ_COMMITTED
        );
 
        this.dataSource = new PoolingDataSource(pool);
    }
 
    public static Connection getDatabaseConnection() throws SQLException {
        return Singleton.INSTANCE.dataSource.getConnection();
    }
    
    private static void loadDriver(String driver) throws SQLException{
            try
            {
                Class.forName(driver).newInstance();
            }
            catch(Exception e)
            {
                throw new SQLException("Unable to load driver: " + driver);
            }
       }
    
}

 

4. log4j2.xml 설정 추가

<Appenders>
	<Console name="console" target="SYSTEM_OUT">
		<PatternLayout pattern="%d %5p [%c] %m%n" />
	</Console>
	
    <!-- 추가 -->
    
	<JDBC name="db" tableName="log">
		<ConnectionFactory class="net.example.db.ConnectionFactory" method="getDatabaseConnection" />
		<Column name="reg_dt" isEventTimestamp="true" /> 
		<Column name="level" pattern="%p" />
		<Column name="logger" pattern="%c" />
		<Column name="message" pattern="%m" />
		<Column name="exception" pattern="%ex{full}" />
	
    	<!-- 모든 로그 다 저장하면 속도가 느리기 때문에 로그필터 적용 (없어도 상관없음 , 필요에따라 필터 수정)-->
    	<Filters>
			<ThresholdFilter level="INFO" onMatch="DENY" onMismatch="NEUTRAL"/>
			<RegexFilter regex=".*Exception.*" onMatch="NEUTRAL" onMismatch="DENY"/>
			<RegexFilter regex=".*exception.*" onMatch="NEUTRAL" onMismatch="DENY"/>
		</Filters>
        <!-- 모든 로그 다 저장하면 속도가 느리기 때문에 로그필터 적용 (없어도 상관없음 , 필요에따라 필터 수정)-->
	</JDBC>
    
    <!-- 추가 -->
</Appenders>

<!--로그저장이 필요한곳에 추가 아래는 예시 -->

<Root level="ERROR">
	<AppenderRef ref="console" />
    <AppenderRef ref="db" /> <!--추가 -->
</Root>

<logger name="org.springframework" level="DEBUG" additivity="false">
	<appender-ref ref="console" />
	<AppenderRef ref="db" /> <!--추가 -->
</logger>

 

 

 

Log4j – Log4j 2 Appenders

facility String The facility is used to try to classify the message. The facility option must be set to one of "KERN", "USER", "MAIL", "DAEMON", "AUTH", "SYSLOG", "LPR", "NEWS", "UUCP", "CRON", "AUTHPRIV", "FTP", "NTP", "AUDIT", "ALERT", "CLOCK", "LOCAL0",

logging.apache.org

 

반응형