logback configures output files for individual packages or classes

Keywords: Java Jetty SQL xml

Source: https://www.cnblogs.com/izecsonLee/p/9058385.html

The most recent requirement is to output the log of a certain class to the specified file. Generally, it is output to the corresponding file according to the log level. Refer to related materials and logback tutorial, write the following demo for reference.

 

1. Add an appender

<! -- jetty log output separately -- >
<appender name="demo—all" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${rootpath}gateserver_demo-all.log</file>
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
             <level>DEBUG</level>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy" >
            <FileNamePattern>${rootpath}demo-all.%i.log</FileNamePattern>
            <minIndex>1</minIndex>
            <maxIndex>10</maxIndex>
        </rollingPolicy>   
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <maxFileSize>800MB</maxFileSize>
        </triggeringPolicy>    
         <encoder>
             <pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern>
         </encoder>
  </appender>
2 Add one logger

<logger name="org.xx.demo" level="DEBUG" additivity="false">

      <appender-ref ref="demo—all" />  
 </logger>

additivity must be set to false. Otherwise, not only the new jetty log file will store jetty's logs, but also the original business log (root) file. It does not inherit root.

 

That's OK.

 

The following are common configurations of logback:

<?xml version="1.0" encoding="UTF-8"?>  
  
<!-- From high to low OFF , FATAL , ERROR , WARN , INFO , DEBUG , TRACE , ALL -->  
<!-- Log output rules based on current ROOT Level, when log output, the level is higher than root The default level is output -->  
<!-- For each of the following configurations filter Filter out the output file, high-level file will appear, and low-level log information will still appear filter Filter logs at this level only-->  
  
  
<!-- Attribute description scan: Sex set to true If the configuration file changes, it will be reloaded. The default value is true scanPeriod:Set whether the monitoring profile has a modified time interval. If no time unit is given, the default unit is milliseconds. When scan by true This property takes effect. The default time interval is 1 minute.   
    debug:When this property is set to true Will be printed out logback Internal log information, real-time viewing logback Operation status. The default value is false.  -->  
<configuration scan="true" scanPeriod="60 seconds" debug="false">  
    <!-- Define log file input location -->  
    <property name="log_dir" value="/logs/ev_cmdb" />  
    <!-- Maximum log history 30 days -->  
    <property name="maxHistory" value="30"/>  
  
  
  
  
    <!-- ConsoleAppender Console output log -->  
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">  
        <!-- Format the log -->  
        <encoder>  
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger -%msg%n</pattern>  
        </encoder>  
    </appender>  
      
      
    <!-- ERROR Level log -->  
    <!-- Scroll to record the file, first record the log to the specified file, and when a certain condition is met, record the log to other files RollingFileAppender-->  
    <appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">  
        <!-- Filters, recording only WARN Level log -->  
        <filter class="ch.qos.logback.classic.filter.LevelFilter">  
            <level>ERROR</level>  
            <onMatch>ACCEPT</onMatch>  
            <onMismatch>DENY</onMismatch>  
        </filter>  
        <!-- The most commonly used rolling strategy, which makes rolling strategy according to time.Responsible for rolling as well as starting rolling -->  
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
            <!--Log output location can be relative, absolute path -->  
            <fileNamePattern>${log_dir}/%d{yyyy-MM-dd}/error-log.log</fileNamePattern>  
            <!-- Optional node, which controls the maximum number of archive files to be retained. If the number is exceeded, the old files will be deleted. Suppose that the setting scrolls every month, and<maxHistory>It's 6.  
            Only the files of the last 6 months are saved, and the old files before are deleted. Note that deleting old files means that directories created for archiving will also be deleted-->  
            <maxHistory>${maxHistory}</maxHistory>  
        </rollingPolicy>  
          
        <!-- Generate log file according to fixed window mode, when the file is greater than 20 MB A new log file is generated. The window size is 1 to 3. When three archives are saved, the oldest log will be overwritten.   
        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">     
          <fileNamePattern>${log_dir}/%d{yyyy-MM-dd}/.log.zip</fileNamePattern>     
          <minIndex>1</minIndex>     
          <maxIndex>3</maxIndex>     
        </rollingPolicy>   -->  
        <!-- View the size of the current active file. If it exceeds the specified size, it will be informed RollingFileAppender Trigger current active file scrolling   
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">     
            <maxFileSize>5MB</maxFileSize>     
        </triggeringPolicy>   -->  
          
        <encoder>  
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>  
        </encoder>  
    </appender>  
      
      
      
    <!-- WARN Level log appender -->  
    <appender name="WARN" class="ch.qos.logback.core.rolling.RollingFileAppender">  
        <!-- Filters, recording only WARN Level log -->  
        <filter class="ch.qos.logback.classic.filter.LevelFilter">  
            <level>WARN</level>  
            <onMatch>ACCEPT</onMatch>  
            <onMismatch>DENY</onMismatch>  
        </filter>  
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
            <!-- Roll back by day daily -->  
            <fileNamePattern>${log_dir}/%d{yyyy-MM-dd}/warn-log.log  
            </fileNamePattern>  
            <!-- Maximum log history 60 days -->  
            <maxHistory>${maxHistory}</maxHistory>  
        </rollingPolicy>  
        <encoder>  
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>  
        </encoder>  
    </appender>  
      
      
      
      
    <!-- INFO Level log appender -->  
    <appender name="INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">  
        <!-- Filters, recording only INFO Level log -->  
        <filter class="ch.qos.logback.classic.filter.LevelFilter">  
            <level>INFO</level>  
            <onMatch>ACCEPT</onMatch>  
            <onMismatch>DENY</onMismatch>  
        </filter>  
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
            <!-- Roll back by day daily -->  
            <fileNamePattern>${log_dir}/%d{yyyy-MM-dd}/info-log.log  
            </fileNamePattern>  
            <!-- Maximum log history 60 days -->  
            <maxHistory>${maxHistory}</maxHistory>  
        </rollingPolicy>  
        <encoder>  
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>  
        </encoder>  
    </appender>  
      
      
      
      
    <!-- DEBUG Level log appender -->  
    <appender name="DEBUG" class="ch.qos.logback.core.rolling.RollingFileAppender">  
        <!-- Filters, recording only DEBUG Level log -->  
        <filter class="ch.qos.logback.classic.filter.LevelFilter">  
            <level>DEBUG</level>  
            <onMatch>ACCEPT</onMatch>  
            <onMismatch>DENY</onMismatch>  
        </filter>  
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
            <!-- Roll back by day daily -->  
            <fileNamePattern>${log_dir}/%d{yyyy-MM-dd}/debug-log.log  
            </fileNamePattern>  
            <!-- Maximum log history 60 days -->  
            <maxHistory>${maxHistory}</maxHistory>  
        </rollingPolicy>  
        <encoder>  
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>  
        </encoder>  
    </appender>  
      
      
      
      
    <!-- TRACE Level log appender -->  
    <appender name="TRACE" class="ch.qos.logback.core.rolling.RollingFileAppender">  
        <!-- Filters, recording only ERROR Level log -->  
        <filter class="ch.qos.logback.classic.filter.LevelFilter">  
            <level>TRACE</level>  
            <onMatch>ACCEPT</onMatch>  
            <onMismatch>DENY</onMismatch>  
        </filter>  
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
            <!-- Roll back by day daily -->  
            <fileNamePattern>${log_dir}/%d{yyyy-MM-dd}/trace-log.log  
            </fileNamePattern>  
            <!-- Maximum log history 60 days -->  
            <maxHistory>${maxHistory}</maxHistory>  
        </rollingPolicy>  
        <encoder>  
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>  
        </encoder>  
    </appender>  
  
    <logger name="java.sql.PreparedStatement" value="DEBUG" />    
    <logger name="java.sql.Connection" value="DEBUG" />    
    <logger name="java.sql.Statement" value="DEBUG" />    
    <logger name="com.ibatis" value="DEBUG" />    
    <logger name="com.ibatis.common.jdbc.SimpleDataSource" value="DEBUG" />    
    <logger name="com.ibatis.common.jdbc.ScriptRunner" level="DEBUG"/>    
    <logger name="com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate" value="DEBUG" />    
      
      
      
    <!-- root level   DEBUG -->  
    <root level="debug">  
        <!-- console output  -->  
        <appender-ref ref="STDOUT" />  
        <!-- File output -->  
        <appender-ref ref="ERROR" />  
        <appender-ref ref="INFO" />  
        <appender-ref ref="WARN" />  
        <appender-ref ref="DEBUG" />  
        <appender-ref ref="TRACE" />  
    </root>  
</configuration>

java code:

import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
  
public class LogUtils {  
    /** 
     * Error entry log 
     */  
    public static final Logger log = LoggerFactory.getLogger(LogUtils.class);  
  
    /** 
     * Record info information all the time 
     *  
     * @param message 
     */  
    public static void logInfo(String message) {  
        StringBuilder s = new StringBuilder();  
        s.append((message));  
        log.info(s.toString());  
    }  
  
    public static void logInfo(String message, Throwable e) {  
        StringBuilder s = new StringBuilder();  
        s.append(("exception : -->>"));  
        s.append((message));  
        log.info(s.toString(), e);  
    }  
  
    public static void logWarn(String message) {  
        StringBuilder s = new StringBuilder();  
        s.append((message));  
  
        log.warn(s.toString());  
    }  
  
    public static void logWarn(String message, Throwable e) {  
        StringBuilder s = new StringBuilder();  
        s.append(("exception : -->>"));  
        s.append((message));  
        log.warn(s.toString(), e);  
    }  
  
    public static void logDebug(String message) {  
        StringBuilder s = new StringBuilder();  
        s.append((message));  
        log.debug(s.toString());  
    }  
  
    public static void logDebug(String message, Throwable e) {  
        StringBuilder s = new StringBuilder();  
        s.append(("exception : -->>"));  
        s.append((message));  
        log.debug(s.toString(), e);  
    }  
  
    public static void logError(String message) {  
        StringBuilder s = new StringBuilder();  
        s.append(message);  
        log.error(s.toString());  
    }  
  
    /** 
     * Log error messages 
     *  
     * @param message 
     * @param e 
     */  
    public static void logError(String message, Throwable e) {  
        StringBuilder s = new StringBuilder();  
        s.append(("exception : -->>"));  
        s.append((message));  
        log.error(s.toString(), e);  
    }  
}

Test:

import java.io.File;  
import java.io.IOException;  
  
import org.junit.Before;  
import org.junit.Test;  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
  
import ch.qos.logback.core.joran.spi.JoranException;  
  
import com.ghca.easyview.server.common.utils.LogBackConfigLoader;  
import com.ghca.easyview.server.common.utils.LogUtils;  
import com.ghca.easyview.server.config.ServerConfig;  
  
public class TestLog {  
  
    @Before  
    public void before() {  
        File file = new File(System.getProperty("user.dir"));  
        String path = file.getPath() + File.separator + "conf";  
        // Assign the primary profile path to the ServerConfig.configPath property  
        ServerConfig.config_path = path;  
        try {  
            // Load log file  
            LogBackConfigLoader.load(ServerConfig  
                    .loadLogBackConfPath("logback.xml"));  
        } catch (IOException | JoranException e) {  
            e.printStackTrace();  
        }  
    }  
  
    @Test  
    public void test1() {  
        LogUtils.logInfo("INFO ~");  
        LogUtils.logDebug("DEBUG ~");  
        LogUtils.logError("ERROR~");  
        LogUtils.logWarn("WARN ~");  
    }  
}
First article in the station
Published 165 original articles· Liked 559· 3.75 million visitors+
Private letter follow

Posted by fert on Thu, 02 Apr 2020 01:22:37 -0700