logback--How do I configure an AsyncAppender with code? 转载
原文地址:https://github.com/tony19/logback-android/issues/54
Please provide an example of how to configure the AsyncAppender with a FileAppender to write to the file in an async way. I am getting many StrictMode policy violations (StrictModeDiskWriteViolation) on every log write to my log file.Thanks.
I verified the following config works in Android 4.2.2 without any exceptions.
<configuration debug="true"><property name="LOG_DIR" value="/data/data/com.example/files" /><appender name="FILE" class="ch.qos.logback.core.FileAppender"><file>${LOG_DIR}/log.txt</file><encoder><pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{35} - %msg%n</pattern></encoder></appender><appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender"><appender-ref ref="FILE" /></appender><root level="DEBUG"><appender-ref ref="ASYNC" /></root> </configuration>
Example: Configure by in-memory XML string
package com.example;import java.io.ByteArrayInputStream; import java.io.InputStream;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 android.app.Activity; import android.os.Bundle; import android.view.Menu;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);configureLogbackByString();org.slf4j.Logger log = LoggerFactory.getLogger(MainActivity.class);log.info("hello world!!");}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu);return true;}@Overrideprotected void onDestroy() {super.onDestroy();// Assume SLF4J is bound to logback-classic in the current environment.// This must be called to properly shutdown AsyncAppender and flush logs// upon application exit.LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();loggerContext.stop();}String LOGBACK_XML ="<configuration debug='true'>" +" <property name='LOG_DIR' value='/data/data/com.example/files' />" +" <appender name='FILE' class='ch.qos.logback.core.FileAppender'>" +" <file>${LOG_DIR}/log.txt</file>" +" <encoder>" +" <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{35} - %msg%n</pattern>" +" </encoder>" +" </appender>" +" <appender name='ASYNC' class='ch.qos.logback.classic.AsyncAppender'>" +" <appender-ref ref='FILE' />" +" </appender>" +" <root level='DEBUG'>" +" <appender-ref ref='ASYNC' />" +" </root>" +"</configuration>";private void configureLogbackByString() {// reset the default context (which may already have been initialized)// since we want to reconfigure itLoggerContext lc = (LoggerContext)LoggerFactory.getILoggerFactory();lc.reset();JoranConfigurator config = new JoranConfigurator();config.setContext(lc);InputStream stream = new ByteArrayInputStream(LOGBACK_XML.getBytes());try {config.doConfigure(stream);} catch (JoranException e) {e.printStackTrace();}} }
Example: Configure with direct calls into logback
package com.example;import org.slf4j.Logger; import org.slf4j.LoggerFactory;import android.app.Activity; import android.os.Bundle; import android.view.Menu; import ch.qos.logback.classic.AsyncAppender; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.encoder.PatternLayoutEncoder; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.FileAppender; import ch.qos.logback.core.util.StatusPrinter;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);configureLogbackDirectly();org.slf4j.Logger log = LoggerFactory.getLogger(MainActivity.class);log.info("hello world!!");}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu);return true;}@Overrideprotected void onDestroy() {super.onDestroy();// assume SLF4J is bound to logback-classic in the current environmentLoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();loggerContext.stop();}private void configureLogbackDirectly() {// reset the default context (which may already have been initialized)// since we want to reconfigure itLoggerContext lc = (LoggerContext)LoggerFactory.getILoggerFactory();lc.reset();// setup FileAppenderPatternLayoutEncoder encoder1 = new PatternLayoutEncoder();encoder1.setContext(lc);encoder1.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{35} - %msg%n");encoder1.start();FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();fileAppender.setContext(lc);fileAppender.setName("FILE");fileAppender.setFile(this.getFileStreamPath("log.txt").getAbsolutePath());fileAppender.setEncoder(encoder1);fileAppender.start();AsyncAppender asyncAppender = new AsyncAppender();asyncAppender.setContext(lc);asyncAppender.setName("ASYNC");// UNCOMMENT TO TWEAK OPTIONAL SETTINGS // // excluding caller data (used for stack traces) improves appender's performance // asyncAppender.setIncludeCallerData(false); // // set threshold to 0 to disable discarding and keep all events // asyncAppender.setDiscardingThreshold(0); // asyncAppender.setQueueSize(256); asyncAppender.addAppender(fileAppender);asyncAppender.start();// add the newly created appenders to the root logger;// qualify Logger to disambiguate from org.slf4j.Loggerch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);root.addAppender(asyncAppender);StatusPrinter.print(lc);} }
转载于:https://www.cnblogs.com/davidwang456/p/4913618.html
logback--How do I configure an AsyncAppender with code? 转载相关推荐
- 读logback源码系列文章(五)——Appender --转载
原文地址:http://kyfxbl.iteye.com/blog/1173788 明天要带老婆出国旅游几天,所以这段时间暂时都更新不了博客了,临走前再最后发一贴 上一篇我们说到Logger类的inf ...
- Configure Javadoc and Source Code for JRE in Eclipse JDT
Moved to http://blog.tangcs.com/2010/12/12/configure-javadoc-jre-eclipse/ 转载于:https://www.cnblogs.co ...
- 从零开始玩转logback
为什么80%的码农都做不了架构师?>>> 概述 LogBack是一个日志框架,它与Log4j可以说是同出一源,都出自Ceki Gülcü之手.(log4j的原型是早前由Ceki ...
- logback异步输出日志详解
前言 logback应该是目前最流行的日志打印框架了,毕竟Spring Boot中默认的集成的日志框架也是logback.在实际项目开发过程中,常常会遇到由于打印大量日志而导致程序并发降低,QPS降低 ...
- logback源码解读笔记(springboot)
logback源码解读笔记(springboot) 一.Logfactory初始化 StaticLoggerBinder的初始化 二.springboot与logback整合 三.logger的执行与 ...
- SLF4J和Logback日志框架详解
SLF4J和Logback日志框架详解 作者:chszs,转载需注明.博客主页:http://blog.csdn.net/chszs 本文讲述SLF4J和Logback日志框架. SLF4J是一 ...
- 如何根据configure.ac和Makefile.am为开源代码产生当前平台的Makefile
1 2 3 4 5 6 7 8 9 //根据configure.in和Makefile.am生成makefile的步骤,基于UBUNTU 12.04 1.autoscan (可选) 2.aclocal ...
- 关于configure: error: no acceptable C compiler found in $PATH
Linux系统在安装python3的时候报错: $ ./configure --prefix=/usr/local/python3 checking build system type... x86_ ...
- LogBack 日志压缩产生上百G的tmp文件问题
2019独角兽企业重金招聘Python工程师标准>>> 在使用LogBack打印日志,并根据每天和自定义大小拆分压缩文件时,**出现上百G的tmp文件,不会自动删除,另外,出现tmp ...
最新文章
- 怎么看b树是几阶_看我在B站上怎么学习的
- 后盾网lavarel视频项目---5、淘宝镜像cnpm的原理及如何使用
- 技术面试的时候应该了解公司点什么
- linux swi 内核sp,Linux内核分析课程8_进程调度与进程切换过程
- 动态调用Web Service
- 离线安装minikube—1.10.1
- Qt工作笔记-3D效果唤出QWidgets界面(QGraphicsProxyWidget与QTimeLine)
- Redis的服务端启动和客户端连接
- 系统业务逻辑书籍_新年福利 | 架构的“一小步”,业务的一大步
- channelinactive触发后不关闭channel_golang chan 最详细原理剖析,全面源码分析!看完不可能不懂的!...
- Java自学和培训的区别
- 超分辨率重建测试(DASR)
- 仿360水波评分特效、加速球特效、水波动态加载动画、可改造成圆形进度条,很丝滑!
- 人机交互-3-评估的基础知识
- 镜像文件iso有什么用
- 鸿蒙系统是不是无法注册gmail邮箱也无法正常使用youtube?
- 2022021第二届青少年计算机知识竞赛
- 27、什么是DOM和BOM
- php array assoc,PHP array_diff_assoc() 函数用法及示例
- 上线不到两个月,昇腾AI助推“中国算力网”再添新节点
热门文章
- java 隐藏标题栏_两种方法一句代码隐藏Activity的标题栏
- 未来新一代计算机的发展方向,未来计算机的发展方向 (2)
- C语言中的关键字概览
- .so 依赖目录 cmake_CMake 的研究与学习笔记
- 有没有插件_这 10 款插件让你的 GitHub 更好用、更有趣
- cv2 画多边形不填充_OpenCV python: 任意多边形填充和凸多边形填充(fillPoly和fillConvexPoly的区别,有图有真相!)...
- python 读取txt
- pymongo insert_many 批量插入
- qq分享 设备未授权报错解决方案_金融行业思科设备典型网络故障案例:76系列典型案例(四)...
- Leetcode 42.接雨水 (每日一题 20210629)