摘自:https://www.cnblogs.com/h--d/p/5671528.html
通常我们在不同的环境使用不同的日志配置文件,本章讲指定logback的配置文件,如何使用logback参照【Log】logback的配置和使用(一)
写一个配置加载类,注意JoranConfigurator这个导入的是ch.qos.logback.classic.joran.JoranConfigurator包下面的
1 package com.test; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.Date; 6 7 import org.slf4j.Logger; 8 import org.slf4j.LoggerFactory; 9 10 import ch.qos.logback.classic.LoggerContext; 11 import ch.qos.logback.classic.joran.JoranConfigurator; 12 import ch.qos.logback.core.joran.spi.JoranException; 13 import ch.qos.logback.core.util.StatusPrinter; 14 15 /** 16 * 17 * @author H__D 18 * 19 */ 20 public class LogBackConfigLoader { 21 22 public static void main(String[] args) throws IOException, JoranException { 23 load("D:/logback.xml"); 24 25 Logger logger = LoggerFactory.getLogger(LogBackConfigLoader.class); 26 27 logger.debug("现在的时间是 {}", new Date().toString()); 28 29 logger.info(" This time is {}", new Date().toString()); 30 31 logger.warn(" This time is {}", new Date().toString()); 32 33 logger.error(" This time is {}", new Date().toString()); 34 35 @SuppressWarnings("unused") 36 int n = 1 / 0; 37 } 38 39 /** 40 * 加载外部的logback配置文件 41 * 42 * @param externalConfigFileLocation 43 * 配置文件路径 44 * @throws IOException 45 * @throws JoranException 46 */ 47 public static void load(String externalConfigFileLocation) throws IOException, JoranException { 48 49 LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); 50 51 File externalConfigFile = new File(externalConfigFileLocation); 52 53 if (!externalConfigFile.exists()) { 54 55 throw new IOException("Logback External Config File Parameter does not reference a file that exists"); 56 57 } else { 58 59 if (!externalConfigFile.isFile()) { 60 throw new IOException("Logback External Config File Parameter exists, but does not reference a file"); 61 62 } else { 63 64 if (!externalConfigFile.canRead()) { 65 throw new IOException("Logback External Config File exists and is a file, but cannot be read."); 66 67 } else { 68 69 JoranConfigurator configurator = new JoranConfigurator(); 70 configurator.setContext(lc); 71 lc.reset(); 72 configurator.doConfigure(externalConfigFileLocation); 73 74 StatusPrinter.printInCaseOfErrorsOrWarnings(lc); 75 } 76 77 } 78 79 } 80 81 } 82 }
D盘logback.xml文件如下:
1 <?xml version="1.0" encoding="UTF-8" ?> 2 3 <!-- scan="true" 当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true。 --> 4 <!-- scanPeriod="30 seconds" 设置每30秒自动扫描,若没有指定具体单位则以milliseconds为标准(单位:milliseconds, seconds, minutes or hours) --> 5 <!-- debug="false"当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。--> 6 <configuration scan="true" scanPeriod="30 seconds"> 7 <!-- 上下文名称 --> 8 <contextName>test</contextName> 9 10 <!-- 存放日志文件路径 --> 11 <property name="Log_Home" value="D:/logs/test" /> 12 13 14 <!-- ch.qos.logback.core.ConsoleAppender 控制台输出 --> 15 <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> 16 <encoder> 17 <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 --> 18 <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n</pattern> 19 </encoder> 20 </appender> 21 22 <!-- DEBUG级别 --> 23 <appender name="FILE_DEBUG" class="ch.qos.logback.core.rolling.RollingFileAppender"> 24 25 <!-- 级别过滤器 --> 26 <filter class="ch.qos.logback.classic.filter.LevelFilter"> 27 <!-- 设置过滤级别 --> 28 <level>DEBUG</level> 29 <!-- 用于配置符合过滤条件的操作 --> 30 <onMatch>ACCEPT</onMatch> 31 <!-- 用于配置不符合过滤条件的操作 --> 32 <onMismatch>DENY</onMismatch> 33 </filter> 34 <Encoding>UTF-8</Encoding> 35 <File>${Log_Home}/debug/debug.log</File> 36 <!-- 根据时间来制定滚动策略 --> 37 <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> 38 <FileNamePattern> 39 ${Log_Home}/debug/debug.%d{yyyy-MM-dd}.%i.log 40 </FileNamePattern> 41 <!-- 多久后自动清楚旧的日志文件,单位:月 --> 42 <MaxHistory>1</MaxHistory> 43 <TimeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> 44 <!-- 默认值是 10MB,文档最大值 --> 45 <MaxFileSize>2MB</MaxFileSize> 46 </TimeBasedFileNamingAndTriggeringPolicy> 47 </rollingPolicy> 48 49 <encoder> 50 <Pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n</Pattern> 51 </encoder> 52 </appender> 53 54 <!-- INFO级别 --> 55 <appender name="FILE_INFO" class="ch.qos.logback.core.rolling.RollingFileAppender"> 56 57 <!-- 级别过滤器 --> 58 <filter class="ch.qos.logback.classic.filter.LevelFilter"> 59 <!-- 设置过滤级别 --> 60 <level>INFO</level> 61 <!-- 用于配置符合过滤条件的操作 --> 62 <onMatch>ACCEPT</onMatch> 63 <!-- 用于配置不符合过滤条件的操作 --> 64 <onMismatch>DENY</onMismatch> 65 </filter> 66 <Encoding>UTF-8</Encoding> 67 <File>${Log_Home}/info/info.log</File> 68 <!-- 根据时间来制定滚动策略 --> 69 <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> 70 <FileNamePattern> 71 ${Log_Home}/info/info.%d{yyyy-MM-dd}.%i.log 72 </FileNamePattern> 73 <!-- 多久后自动清楚旧的日志文件,单位:月 --> 74 <MaxHistory>1</MaxHistory> 75 <TimeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> 76 <!-- 默认值是 10MB,文档最大值 --> 77 <MaxFileSize>2MB</MaxFileSize> 78 </TimeBasedFileNamingAndTriggeringPolicy> 79 </rollingPolicy> 80 81 <encoder> 82 <Pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n</Pattern> 83 </encoder> 84 </appender> 85 86 87 <!-- WARN级别 --> 88 <appender name="FILE_WARN" class="ch.qos.logback.core.rolling.RollingFileAppender"> 89 90 <!-- 级别过滤器 --> 91 <filter class="ch.qos.logback.classic.filter.LevelFilter"> 92 <!-- 设置过滤级别 --> 93 <level>WARN</level> 94 <!-- 用于配置符合过滤条件的操作 --> 95 <onMatch>ACCEPT</onMatch> 96 <!-- 用于配置不符合过滤条件的操作 --> 97 <onMismatch>DENY</onMismatch> 98 </filter> 99 <Encoding>UTF-8</Encoding> 100 <File>${Log_Home}/warn/warn.log</File> 101 <!-- 根据时间来制定滚动策略 --> 102 <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> 103 <FileNamePattern> 104 ${Log_Home}/warn/warn.%d{yyyy-MM-dd}.%i.log 105 </FileNamePattern> 106 <!-- 多久后自动清楚旧的日志文件,单位:月 --> 107 <MaxHistory>1</MaxHistory> 108 <TimeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> 109 <!-- 默认值是 10MB,文档最大值 --> 110 <MaxFileSize>2MB</MaxFileSize> 111 </TimeBasedFileNamingAndTriggeringPolicy> 112 </rollingPolicy> 113 114 <encoder> 115 <Pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n</Pattern> 116 </encoder> 117 </appender> 118 119 <!-- ERROR级别 --> 120 <appender name="FILE_ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender"> 121 122 <!-- 级别过滤器 --> 123 <filter class="ch.qos.logback.classic.filter.LevelFilter"> 124 <!-- 设置过滤级别 --> 125 <level>ERROR</level> 126 <!-- 用于配置符合过滤条件的操作 --> 127 <onMatch>ACCEPT</onMatch> 128 <!-- 用于配置不符合过滤条件的操作 --> 129 <onMismatch>DENY</onMismatch> 130 </filter> 131 <Encoding>UTF-8</Encoding> 132 <File>${Log_Home}/error/error.log</File> 133 <!-- 根据时间来制定滚动策略 --> 134 <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> 135 <FileNamePattern> 136 ${Log_Home}/error/error.%d{yyyy-MM-dd}.%i.log 137 </FileNamePattern> 138 <!-- 多久后自动清楚旧的日志文件,单位:月 --> 139 <MaxHistory>1</MaxHistory> 140 <TimeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> 141 <!-- 默认值是 10MB,文档最大值 --> 142 <MaxFileSize>2MB</MaxFileSize> 143 </TimeBasedFileNamingAndTriggeringPolicy> 144 </rollingPolicy> 145 146 <encoder> 147 <Pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n</Pattern> 148 </encoder> 149 </appender> 150 151 152 153 <!-- 控制java下面包的打印,没设置等级,将继承上级root的等级,可以指定包和类的打印级别,属性additivity="false",可以阻止打印日志信息传递,默认为true。--> 154 <logger name="com.test"/> 155 156 <!-- 当前日志总级别为TRACE、DEBUG、INFO、 WARN、ERROR、ALL和 OF --> 157 <!-- the level of the root level is set to DEBUG by default. --> 158 <root level="DEBUG"> 159 <appender-ref ref="STDOUT" /> 160 <appender-ref ref="FILE_DEBUG" /> 161 <appender-ref ref="FILE_INFO" /> 162 <appender-ref ref="FILE_WARN" /> 163 <appender-ref ref="FILE_ERROR" /> 164 </root> 165 </configuration>
注:appender相当于输出口,注意父子级的叠加输出
运行LogBackConfigLoader中的main方法,控制台输出如下:
1 2016-07-14 19:15:08 [main] DEBUG com.test.LogBackConfigLoader - 现在的时间是 Thu Jul 14 19:15:08 CST 2016 2 2016-07-14 19:15:08 [main] INFO com.test.LogBackConfigLoader - This time is Thu Jul 14 19:15:08 CST 2016 3 2016-07-14 19:15:08 [main] WARN com.test.LogBackConfigLoader - This time is Thu Jul 14 19:15:08 CST 2016 4 2016-07-14 19:15:08 [main] ERROR com.test.LogBackConfigLoader - This time is Thu Jul 14 19:15:08 CST 2016 5 Exception in thread "main" java.lang.ArithmeticException: / by zero 6 at com.test.LogBackConfigLoader.main(LogBackConfigLoader.java:36)
外部输入日志如下: