【问题标题】:Spring - Logback catch logging eventsSpring - Logback 捕获日志记录事件
【发布时间】:2017-12-15 12:30:21
【问题描述】:

我是 Spring 和日志记录的新手。

我的目标是创建一个自定义存储库,其中包含 Logback 记录器e.g logger.name / logger.level / logger.message 的数据
然后将映射到MySQL DB

问题是我不知道如何捕捉日志事件。 我试图实例化 LoggingEvent (ILoggingEvent)。但这总是让我返回"null"

我不想使用典型的"Spring-logback-way",因为我正在创建一个带有自定义命名表/属性的自定义 MySQL-DB。

我必须使用哪个接口/类来捕获实际的 loggingEvent?

【问题讨论】:

    标签: java mysql spring spring-mvc logging


    【解决方案1】:

    第 1 步:首先您必须在项目中包含 log4j.jar。

    step 2.Configure JDBCAppender in log4j.properties file as bellow to store 
           logging in database.
    
    log4j.properties:
    
        # Define the root logger with file appender
        log4j.rootLogger = DEBUG, sql
    
        # Define the file appender
        log4j.appender.sql=org.apache.log4j.jdbc.JDBCAppender
        log4j.appender.sql.URL=jdbc:mysql://localhost/test
        # Set Database Driver
        log4j.appender.sql.driver=com.mysql.jdbc.Driver
        # Set database user name and password
        log4j.appender.sql.user=root
        log4j.appender.sql.password=password
        # Set the SQL statement to be executed.
        log4j.appender.sql.sql=INSERT INTO LOGS VALUES ('%x', now() 
            ,'%C','%p','%m')
        # Define the xml layout for file appender
        log4j.appender.sql.layout=org.apache.log4j.PatternLayout
    
    Step 3: Log4jJDBCExample to configure log4j and ites priority level message
    
    import org.apache.log4j.Logger;
    import org.apache.log4j.PropertyConfigurator;
    
    public class Log4jJDBCExample
    {
        static Logger log = Logger.getLogger(Log4jJDBCExample.class);
    
        public static void main(String[] args)
        {
            PropertyConfigurator.configure("log4j.properties");
    
            log.debug("Sample debug message");
            log.info("Sample info message");
            log.error("Sample error message");
            log.fatal("Sample fatal message");
        }
    }
    
    
    Step 4: Create the table in database and test the application
    
        Create the database table LOGS, in schema test.
    
        CREATE TABLE LOGS
        (
            USER_ID VARCHAR(20) NOT NULL,
            DATED   DATETIME NOT NULL,
            LOGGER  VARCHAR(50) NOT NULL,
            LEVEL   VARCHAR(10) NOT NULL,
            MESSAGE VARCHAR(1000) NOT NULL
        );
    
    Explination:
    
      log4j.appender.sql.sql=INSERT INTO LOGS VALUES ('%x', now() ,'%C','%p','%m')
    
      Here now()--> inserts currentdate 
              %c--> Class Name
              %p--> Priority (level)
              %m--> Message 
    

    结果如下:

    【讨论】:

    • 这正是我正在寻找的,只需使用 Logback + SLF4J 实现!
    猜你喜欢
    • 2021-03-15
    • 2014-01-16
    • 2015-01-09
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    相关资源
    最近更新 更多