标签:logback consoleappender rollingfileappender
package com.ttpod.chapters.configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MyApp1 { final static Logger logger = LoggerFactory.getLogger(MyApp1.class); public static void main(String[] args) { logger.info("Entering application."); //进行另一个application中 Foo foo = new Foo(); foo.doIt(); //执行其它中的日志输出方法 logger.info("Exiting application."); //退出另一个application } }
package com.ttpod.chapters.configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Foo { <span style="white-space:pre"> </span>static final Logger logger = LoggerFactory.getLogger(Foo.class); <span style="white-space:pre"> </span>public void doIt() { <span style="white-space:pre"> </span>logger.debug("Did it again!"); //定义一个debug级别的日志输出 } ………… }
final static Logger logger = LoggerFactory.getLogger(MyApp2.class); public static void main(String[] args) { // 在当前环境中假设 SLF4J 已经被绑定到logback LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); // 打印logback的内部状态 StatusPrinter.print(lc); ………… } }
<?xml version="1.0" encoding="UTF-8" ?> <configuration> <!--定义一个名为STDOUT的appender,并将其关联到ch.qos.logback.core.ConsoleAppender--> <span style="white-space:pre"> </span><appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <span style="white-space:pre"> </span><!-- encoders 作用是将logger事件转换成字节数组,并将字节数组写入到输出流--> <span style="white-space:pre"> </span><encoder> <span style="white-space:pre"> </span><!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度 %msg:日志消息,%n是换行符--> <span style="white-space:pre"> </span><pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> <span style="white-space:pre"> </span></encoder> <span style="white-space:pre"> </span></appender> <span style="white-space:pre"> </span><root level="debug"> <!-- root logger,定义级别为debug--> <span style="white-space:pre"> </span><appender-ref ref="STDOUT" /> <!--将名为STDOUT的appender添加到root logger下--> <span style="white-space:pre"> </span></root> </configuration>
<?xml version="1.0" encoding="UTF-8" ?> <configuration> <span style="white-space:pre"> </span><appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <span style="white-space:pre"> </span><encoder> <span style="white-space:pre"> </span><pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> <span style="white-space:pre"> </span></encoder> <span style="white-space:pre"> </span></appender> <span style="white-space:pre"> </span><!-- 设置configuration下的logger的级别为INFO,默认是继承root logger的debug级别 --> <span style="white-space:pre"> </span><logger name="chapters.configuration" level="INFO" /> <span style="white-space:pre"> </span><!-- 严格来说, root logger 的level属性没有必要设置,因为 --> <span style="white-space:pre"> </span><!-- root logger的级别被默认设置为DEBUG --> <span style="white-space:pre"> </span><root level="DEBUG"> <span style="white-space:pre"> </span><!--在root标签内没有引入chapters.configuration,所有在此包下不会显示任何组件的任何 DEBUG 信息 --> <span style="white-space:pre"> </span><appender-ref ref="STDOUT" /> <!-- 将appender引入到root logger --> <span style="white-space:pre"> </span></root> </configuration>
<configuration> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>myApp.log</file> <span style="white-space:pre"> </span><!-- encoders are assigned by default the type ch.qos.logback.classic.encoder.PatternLayoutEncoder --> <span style="white-space:pre"> </span><encoder> <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern> <span style="white-space:pre"> </span></encoder> </appender> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <span style="white-space:pre"> </span><encoder> <span style="white-space:pre"> </span><pattern>%msg%n</pattern> <span style="white-space:pre"> </span></encoder> </appender> <root level="debug"> <appender-ref ref="FILE" /> <appender-ref ref="STDOUT" /> </root> </configuration>
<configuration> <span style="white-space:pre"> </span><appender name="STDOUT"class="ch.qos.logback.core.ConsoleAppender"> <span style="white-space:pre"> </span><encoder> <span style="white-space:pre"> </span><pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> <span style="white-space:pre"> </span></encoder> <span style="white-space:pre"> </span></appender> <span style="white-space:pre"> </span><logger name="chapters.configuration"> <span style="white-space:pre"> </span><appender-ref ref="STDOUT" /> <span style="white-space:pre"> </span></logger> <span style="white-space:pre"> </span><root level="debug"> <span style="white-space:pre"> </span><appender-ref ref="STDOUT" /> <!—这会导致重复输出--> <span style="white-space:pre"> </span></root> </configuration>
<configuration> ………… <logger name="com.ttpod.chapters.configuration.Foo" additivity="false"> <appender-ref ref="FILE" /> </logger> <root level="debug"> <appender-ref ref="STDOUT" /> </root> </configuration>
<configuration debug="true"> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder"> <!—自定义的格式化输出处理类--> <layout class="com.ttpod.chapters.layouts.MySampleLayout" /> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="STDOUT" /> </root> </configuration>
调用日志事件的所在的类名,和c转换符一样,可以在右边指定宽度,如%C{2}输出%C{2}
dpackage com.ttpod.file; import org.slf4j.Logger; //用于声明Logger import org.slf4j.LoggerFactory; //用于获取Logger以及LoggerContext import ch.qos.logback.classic.LoggerContext; //用于声明LoggerContext import ch.qos.logback.classic.joran.JoranConfigurator; //用于定义Logback的配置机制 import ch.qos.logback.core.joran.spi.JoranException; //用于定义JoranException import ch.qos.logback.core.util.StatusPrinter; //用于打印logback的内部状态 public class MyApp1 { final static Logger logger = LoggerFactory.getLogger(MyApp1.class); //定义一个全局的记录器,通过LoggerFactory获取 public static void main(String[] args) { //通过getILoggerFactory()方法得到logger上下文件环境,logback默认获得当前应用的logger context LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); //得到当前应用中logger上下文 try { JoranConfigurator configurator = new JoranConfigurator(); //定义一个(JoranConfigurator)配置器 configurator.setContext(context); //将当前应用的logger context的关联到到configurator对象 context.reset(); //清除以前的配置器中的所有内容 //configurator.doConfigure(args[0]); //接收从命令行传入的参数,加载配置文件,并设置到配置器 configurator.doConfigure("src/com/ttpod/file/MyApp1Config.xml"); //配置文件的路径:src/com/ttpod/file/MyApp1Config.xml } catch (JoranException je) { logger.error("JoranException occur at:"+je.getMessage()); //将此处异常也记录到日志 je.printStackTrace(); //在控制打印出异常跟踪信息 } //打印出logger context中的error和供气ing,在此处作用相当于catch中的je.printStackTrace(); StatusPrinter.printInCaseOfErrorsOrWarnings(context); //流程进入有日志生成的类中 logger.info("Entering application.demo class Foo >>>"); Foo foo = new Foo(); foo.doIt(); //执行foo中的一个生成了日志的方法,输出日志 logger.info("Exiting application. demo class Foo <<<"); } }
package com.ttpod.file; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Foo { static final Logger logger = LoggerFactory.getLogger(Foo.class); public void doIt() { logger.debug("test logger in other class!"); } public void createLoggingRequest() { subMethodToCreateRequest(); } //这个方法执行后创建一条异常信息 private void subMethodToCreateRequest() { logger.error("error-level request", new Exception("test exception")); } }
<configuration> <!-- 指定属性文件路径 --> <property file="src/com/ttpod/file/variables.properties" /> <!-- 指定日志输出到文件--> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>${destination}</file> <encoder> <!-- %msg表示日志信息,%n表示换行 --> <pattern>%msg%n</pattern> </encoder> </appender> <root level="debug"> <appender-ref ref="FILE" /><!—添加到根logger--> </root> </configuration>
package com.ttpod.file; import java.util.Date; public class MyApp2 { static Timer t; public static void main(String[] args) { // 调用LoggerFactory 类的静态方法getLogger取得一个Logger实例, final Logger logOut = LoggerFactory.getLogger("SystemOut"); // 定义一个名为SystemOut的logger final Logger logErr = LoggerFactory.getLogger("SystemErr"); // 定义一个名为SystemErr的logger LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); //configurator.doConfigure(args[0]); configurator.doConfigure("src/com/ttpod/file/logback.xml"); } catch (JoranException je) { je.printStackTrace(); } // 打印logback的内部状态 StatusPrinter.print(lc); //固定部分 t = new Timer(); // 定义一个定时器 TimerTask tt = new TimerTask() { // 用定义器执行计划(schedule),并定义一个继承了TimerTask的匿名内部类 @Override public void run() { for (int i = 100; i > 0; i--) { // Timer t=null; MyApp2.t.cancel(); logOut.info("测试Logback日志的使用"); // 定义了一个info级别的日志消息 logErr.error("发生错误"); // 定义了一个error级别的日志消息 } System.out.println("~~~~~~~~~~~~~ "); } }; t.schedule(tt, new Date(), 50); // 从当前系统时间开始,每50毫秒执行一次计划 } }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration> <configuration> <jmxConfigurator /> <!-- 配置文件路径 --> <property file="src/com/ttpod/file/variables.properties" /> <!--logback的版本必须是0.9.21以上才支持--> <timestamp key="byDay" datePattern="yyyyMMdd"/> <!-- 控制台输出日志 --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <layout class="ch.qos.logback.classic.PatternLayout"> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </layout> </appender> <!-- 文件输出日志 (文件大小策略进行文件输出,超过指定大小对文件压缩(.zip)备份)--> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 文件的路径及文件名 --> <File>${USER_HOME}/SystemOut.log</File> <!-- 定义窗口滚动策略 --> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <!-- 每触发一次,自动压缩日志文件,%i在1-3之间循环变化 --> <FileNamePattern>${USER_HOME}/SystemOut_%i.log.zip</FileNamePattern> <MinIndex>1</MinIndex> <!-- %i的最小值为1--> <MaxIndex>3</MaxIndex> <!-- %i的最大值为3--> </rollingPolicy> <!-- 触发策略,通常rollingPolicy与triggeringPolicy联合使用 --> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <MaxFileSize>10KB</MaxFileSize> </triggeringPolicy> <!-- 格式化输出 --> <!-- %d表示日期,格式为:yyyy-MM-dd HH:mm:ss.SSS ;%thread:线程名; %-5level:从左边以5个字符的宽度显示级别; %logger:显示logger名;%msg:日志消息;%n:换行 <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern> </layout> --> <!-- 或者用下面的形式格式(推荐)--> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS}%relative%thread%mdc%level%logger%msg</pattern> </encoder> <!-- 以html文件输出 --> <!-- <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder"> <layout class="ch.qos.logback.classic.html.HTMLLayout"> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS}%relative%thread%mdc%level%logger%msg</pattern> </layout> </encoder> --> </appender> <!-- 输出ERROR级别的日志到文件(同样采用文件大小策略进行文件输出,超过指定大小对文件压缩(.zip)备份) --> <appender name="FILE-ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender"> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> <!-- 指定要对级别为ERROR日志信息过滤 --> <OnMismatch>DENY</OnMismatch> <!-- 如果不匹配,则拒绝处理 --> <OnMatch>ACCEPT</OnMatch> <!-- 如果匹配,则立即处理 --> </filter> <File>${USER_HOME}/SystemErr.log</File> <!-- 文件名即路径 --> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <FileNamePattern>${USER_HOME}/SystemErr_%i.log.zip</FileNamePattern> <MinIndex>1</MinIndex> <MaxIndex>3</MaxIndex> </rollingPolicy> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <MaxFileSize>10KB</MaxFileSize> </triggeringPolicy> <!-- 格式化输出 --> <!-- <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern> </layout> --> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS}%relative%thread%mdc%level%logger%msg</pattern> </encoder> </appender> <!--这里指定logger name 是为jmx设置日志级别做铺垫 --> <!-- 分别将STDOUT与FILE appender都添加到自定义的logger中,否则将不会输出到appender指定的 目的地--> <logger name="SystemOut" level="INFO"> <appender-ref ref="STDOUT" /> <appender-ref ref="FILE" /> </logger> <logger name="SystemErr" level="INFO"> <appender-ref ref="STDOUT" /> <appender-ref ref="FILE-ERROR" /> </logger> </configuration>
package com.ttpod.file; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.util.StatusPrinter; import com.ttpod.file.Foo;; public class MyApp3 { public static void main(String[] args) throws InterruptedException { Logger logger = (Logger) LoggerFactory.getLogger(MyApp3.class); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure(args[0]); } catch (JoranException je) { je.printStackTrace(); } //固定部分 //打印logback的内部状态 StatusPrinter.print(lc); logger.debug("**Hello {}", new Foo()); //客户端的每个记录请求添加唯一戳(uniquely stamp),运用MDC(Mapped Diagnostic Context) //在分布式应用程序中,可以区分并处理不同客户端的记录输出,而不增加logger的开销 MDC.put("testKey", "testValueFromMDC"); //在appender中用%X{testKey},可以输出MDC中test对应的值 MDC.put("testKey2", "value2"); for (int i = 0; i < 10; i++) { logger.debug("logging statement " + i); Thread.sleep(100); } Foo foo = new Foo(); foo.createLoggingRequest(); } }
<configuration> <!-- 指定属性文件路径 --> <property file="src/com/ttpod/file/variables.properties" /> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${USER_HOME}/testFile.log</file> <!--滚动策略--> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <!—自动压缩备份--> <fileNamePattern>${USER_HOME}/testFile.%i.log.zip</fileNamePattern> <minIndex>1</minIndex> <maxIndex>3</maxIndex><!--%i在1-3之间循环变化--> </rollingPolicy> <!—触发策略--> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <!--日志文件大小限制在5kB以内,否则就触发滚动--> <maxFileSize>5kB</maxFileSize> </triggeringPolicy> <encoder><!--格式化输出--> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="FILE" /> </root> </configuration>
<configuration> <span style="white-space:pre"> </span><!-- 指定属性文件路径 --> <span style="white-space:pre"> </span><property file="src/com/ttpod/file/variables.properties" /> <span style="white-space:pre"> </span><!-- 基于时间的滚动策略 --> <span style="white-space:pre"> </span><appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <span style="white-space:pre"> </span><file>${USER_HOME}/logFile.log</file> <span style="white-space:pre"> </span><rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <span style="white-space:pre"> </span><!-- 每天滚动<fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>--> <span style="white-space:pre"> </span><!-- 每分钟滚动 --> <span style="white-space:pre"> </span><fileNamePattern>${USER_HOME}/logFile.%d{yyyy-MM-dd_HH-mm}.log</fileNamePattern> <span style="white-space:pre"> </span><!-- 限制文件最大保存时间为30天--> <span style="white-space:pre"> </span><maxHistory>30</maxHistory> <span style="white-space:pre"> </span></rollingPolicy> <span style="white-space:pre"> </span><encoder> <span style="white-space:pre"> </span><pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> <span style="white-space:pre"> </span></encoder> <span style="white-space:pre"> </span></appender> <span style="white-space:pre"> </span><root level="DEBUG"> <span style="white-space:pre"> </span><appender-ref ref="FILE" /> <span style="white-space:pre"> </span></root> </configuration>
<configuration> <span style="white-space:pre"> </span><!-- 基于时间与大小的归档 --> <span style="white-space:pre"> </span><statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" /> <span style="white-space:pre"> </span><!-- 指定属性文件路径 --> <span style="white-space:pre"> </span><property file="src/com/ttpod/file/variables.properties" /> <span style="white-space:pre"> </span><!-- 基于时间与大小的归档 --> <span style="white-space:pre"> </span><appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender"> <span style="white-space:pre"> </span><file>${USER_HOME}/mylog.txt</file> <span style="white-space:pre"> </span><rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <span style="white-space:pre"> </span><!-- 每天滚动<fileNamePattern>${USER_HOME}/mylog-%d{yyyy-MM-dd}.%i.txt</fileNamePattern>--> <span style="white-space:pre"> </span><minIndex>1</minIndex> <span style="white-space:pre"> </span><maxIndex>3</maxIndex> <span style="white-space:pre"> </span><!-- 每分钟滚动 --> <span style="white-space:pre"> </span><fileNamePattern>${USER_HOME}/mylog-%d{yyyy-MM-dd_HH-mm}.%i.txt</fileNamePattern> <span style="white-space:pre"> </span><!-- 限制文件最大保存时间为30天--> <span style="white-space:pre"> </span><maxHistory>30</maxHistory> <span style="white-space:pre"> </span><timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <span style="white-space:pre"> </span><!-- 当文件大小超过5kB时触发滚动,这里设置5kb只是便于测试 --> <span style="white-space:pre"> </span><maxFileSize>5kB</maxFileSize> <span style="white-space:pre"> </span></timeBasedFileNamingAndTriggeringPolicy> <span style="white-space:pre"> </span></rollingPolicy> <span style="white-space:pre"> </span><encoder> <span style="white-space:pre"> </span><pattern>%msg%n</pattern> <span style="white-space:pre"> </span></encoder> <span style="white-space:pre"> </span></appender> <span style="white-space:pre"> </span><root level="debug"> <span style="white-space:pre"> </span><appender-ref ref="ROLLING" /> <span style="white-space:pre"> </span></root> </configuration>
package com.ttpod.html; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.util.StatusPrinter; public class HtmlTest1 { <span style="white-space:pre"> </span>public static void main(String[] args) throws InterruptedException { <span style="white-space:pre"> </span>Logger logger = LoggerFactory.getLogger(HtmlTest1.class); <span style="white-space:pre"> </span>LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); <span style="white-space:pre"> </span>try { <span style="white-space:pre"> </span>JoranConfigurator configurator = new JoranConfigurator(); <span style="white-space:pre"> </span>configurator.setContext(lc); <span style="white-space:pre"> </span>lc.reset(); <span style="white-space:pre"> </span>configurator.doConfigure(args[0]); <span style="white-space:pre"> </span>//configurator.doConfigure("./src/com/ttpod/html/htmlLayoutConfig1.xml"); <span style="white-space:pre"> </span>} catch (JoranException je) { <span style="white-space:pre"> </span>je.printStackTrace(); //固定部分 <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>StatusPrinter.printInCaseOfErrorsOrWarnings(lc); <span style="white-space:pre"> </span>for (int i = 0; i < 6; i++) { <span style="white-space:pre"> </span>if (i % 5 == 0) { <span style="white-space:pre"> </span>logger.warn("a warning message " + i); //声明一条warn级别的日志消息 <span style="white-space:pre"> </span>//logger.info("a warning message " + i); <span style="white-space:pre"> </span>} else { <span style="white-space:pre"> </span>logger.debug("hello world number" + i); <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>logger.error("Finish off with fireworks", new Exception("Just testing")); <span style="white-space:pre"> </span>} }
<configuration> <span style="white-space:pre"> </span><!-- 指定属性文件路径 --> <span style="white-space:pre"> </span><property file="src/com/ttpod/html/variables.properties" /> <span style="white-space:pre"> </span><!-- 指定日志输出到文件--> <span style="white-space:pre"> </span><appender name="FILE" class="ch.qos.logback.core.FileAppender"> <span style="white-space:pre"> </span><encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder"> <span style="white-space:pre"> </span><layout class="ch.qos.logback.classic.html.HTMLLayout"> <span style="white-space:pre"> </span><pattern>%relative%thread%mdc%level%logger%msg</pattern> <span style="white-space:pre"> </span></layout> <span style="white-space:pre"> </span></encoder> <span style="white-space:pre"> </span><file>${destination}</file> <span style="white-space:pre"> </span></appender> <span style="white-space:pre"> </span><root level="DEBUG"> <span style="white-space:pre"> </span><appender-ref ref="FILE" /> <span style="white-space:pre"> </span></root>
</configuration>
package com.ttpod.mail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.util.StatusPrinter; public class EMail { <span style="white-space:pre"> </span>static public void main(String[] args) throws Exception { <span style="white-space:pre"> </span>if (args.length != 2) { <span style="white-space:pre"> </span>usage("Wrong number of arguments."); <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>int runLength = Integer.parseInt(args[0]); <span style="white-space:pre"> </span>String configFile = args[1]; <span style="white-space:pre"> </span>//int runLength = Integer.parseInt("300"); <span style="white-space:pre"> </span>//String configFile="src/com/ttpod/mail/gmailSSL.xml"; <span style="white-space:pre"> </span>//String configFile = "src/com/ttpod/mail/gmailSTARTTLS.xml"; <span style="white-space:pre"> </span>//自定义配置文件,得到日志固定格式 <span style="white-space:pre"> </span>LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); <span style="white-space:pre"> </span>JoranConfigurator configurator = new JoranConfigurator(); <span style="white-space:pre"> </span>lc.reset(); <span style="white-space:pre"> </span>configurator.setContext(lc); <span style="white-space:pre"> </span>configurator.doConfigure(configFile); <span style="white-space:pre"> </span>Logger logger = LoggerFactory.getLogger(EMail.class); <span style="white-space:pre"> </span>for (int i = 1; i <= runLength; i++) { <span style="white-space:pre"> </span>if ((i % 10) < 9) { <span style="white-space:pre"> </span>logger.debug("This is a debug message. Message number: " + i); <span style="white-space:pre"> </span>} else { <span style="white-space:pre"> </span>logger.warn("This is a warning message. Message number: " + i); <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>//定义一条error级别的日志输出 <span style="white-space:pre"> </span>logger.error("At last an error.", new Exception("Just testing")); <span style="white-space:pre"> </span>//打印logger内部状态 <span style="white-space:pre"> </span>StatusPrinter.printInCaseOfErrorsOrWarnings(lc); <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>static void usage(String msg) { //当参数传入错误时,提供的处理惯例 <span style="white-space:pre"> </span>System.err.println(msg); <span style="white-space:pre"> </span>System.err.println("Usage: java " + EMail.class.getName() + <span style="white-space:pre"> </span>" runLength configFile\n" + <span style="white-space:pre"> </span>" runLength (integer) the number of logs to generate\n" + <span style="white-space:pre"> </span>" configFile a logback configuration file in XML format." + <span style="white-space:pre"> </span>" XML files must have a '.xml' extension."); <span style="white-space:pre"> </span>System.exit(1); //退出程序 <span style="white-space:pre"> </span>} }
<configuration> <span style="white-space:pre"> </span><!-- 指定属性文件的位置 --> <span style="white-space:pre"> </span><property file="src/com/ttpod/mail/gmailSSL.properties" /> <span style="white-space:pre"> </span><!-- 目的指定向email的appender --> <span style="white-space:pre"> </span><appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender"> <span style="white-space:pre"> </span><SMTPHost>${SMTPHOST}</SMTPHost><!-- 邮件服务器地址 --> <span style="white-space:pre"> </span><SMTPPort>${SMTPPORT}</SMTPPort><!--SMTPPORT端口--> <span style="white-space:pre"> </span><SSL>true</SSL> <span style="white-space:pre"> </span><Username>${EMAIL_USERNAME}</Username><!-- 用户名 --> <span style="white-space:pre"> </span><Password>${EMAIL_PASSWORD}</Password><!-- 密码 --> <span style="white-space:pre"> </span><To>${EMAIL-DESTINATION}</To><!-- 目标接收人 --> <span style="white-space:pre"> </span><To>${ANOTHER_EMAIL_DESTINATION}</To> <!-- additional destinations are possible --> <span style="white-space:pre"> </span><From>${EMAIL_USERNAME}</From><!-- 发件人 --> <span style="white-space:pre"> </span><Subject>TESTING: %logger{20} - %m</Subject><!-- 主题 --> <span style="white-space:pre"> </span><encoder><!-- 一般采用这种方式格式化输出 --> <span style="white-space:pre"> </span><layout class="ch.qos.logback.classic.html.HTMLLayout"> <span style="white-space:pre"> </span><!-- 采用什么渲染方式,这采取的是HTML方式 --> <span style="white-space:pre"> </span><Pattern>%date %-5level %logger - %message%n</Pattern> <span style="white-space:pre"> </span></layout> <span style="white-space:pre"> </span></encoder> <span style="white-space:pre"> </span><!-- <span style="white-space:pre"> </span><layout class="ch.qos.logback.classic.PatternLayout"> <span style="white-space:pre"> </span><Pattern>%date %-5level %logger - %message%n</Pattern> <span style="white-space:pre"> </span></layout> <span style="white-space:pre"> </span>--> <span style="white-space:pre"> </span></appender> <span style="white-space:pre"> </span><!-- 输出到控制台,以便将日志也打印到控制台--> <span style="white-space:pre"> </span><appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <span style="white-space:pre"> </span><encoder> <span style="white-space:pre"> </span><pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> <span style="white-space:pre"> </span></encoder> <span style="white-space:pre"> </span></appender> <span style="white-space:pre"> </span><!-- 输出到文件,将日志记录到本地文件--> <span style="white-space:pre"> </span><appender name="FILE" class="ch.qos.logback.core.FileAppender"> <span style="white-space:pre"> </span><file>./log/mailtest.log</file> <span style="white-space:pre"> </span><encoder> <span style="white-space:pre"> </span><!-- %msg表示日志信息,%n表示换行 --> <span style="white-space:pre"> </span><pattern>%msg%n</pattern> <span style="white-space:pre"> </span></encoder> <span style="white-space:pre"> </span></appender> <span style="white-space:pre"> </span><root level="debug"> <span style="white-space:pre"> </span><appender-ref ref="EMAIL" /> <span style="white-space:pre"> </span><appender-ref ref="STDOUT" /> <span style="white-space:pre"> </span><appender-ref ref="FILE"></appender-ref> <span style="white-space:pre"> </span></root> </configuration>
标签:logback consoleappender rollingfileappender
原文地址:http://blog.csdn.net/lovesomnus/article/details/41977499