我想仅记录到文件并禁用控制台日志记录,但这不起作用。我认为以下应该有效,但事实并非如此。有谁知道我弄错了什么?
我正在尝试使用detachAndStopAllAppenders
删除任何默认记录器,但仍然不会停止记录到控制台...
import android.util.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
public class FileLogger
{
static Logger mLogger = LoggerFactory.getLogger(FileLogger.class);
public FileLogger(FileLoggingSetup setup)
{
if (setup == null)
throw new RuntimeException("You can't create a FileLogger without providing a setup!");
init(setup);
}
private void init(FileLoggingSetup setup)
{
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
lc.reset();
// 1) FileLoggingSetup - Encoder for File
PatternLayoutEncoder encoder1 = new PatternLayoutEncoder();
encoder1.setContext(lc);
encoder1.setPattern(setup.mLogPattern);
encoder1.start();
// 2) FileLoggingSetup - rolling file appender
RollingFileAppender<ILoggingEvent> rollingFileAppender = new RollingFileAppender<ILoggingEvent>();
rollingFileAppender.setAppend(true);
rollingFileAppender.setContext(lc);
//rollingFileAppender.setFile(setup.mFolder + "/" + setup.mFileName + "." + setup.mFileExtension);
// 3) FileLoggingSetup - Rolling policy (one log per day)
TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new TimeBasedRollingPolicy<ILoggingEvent>();
rollingPolicy.setFileNamePattern(setup.mFolder + "/" + setup.mFileName + "_%d{yyyyMMdd}." + setup.mFileExtension);
rollingPolicy.setMaxHistory(setup.mDaysToKeep);
rollingPolicy.setCleanHistoryOnStart(true);
rollingPolicy.setParent(rollingFileAppender);
rollingPolicy.setContext(lc);
rollingPolicy.start();
rollingFileAppender.setTriggeringPolicy(rollingPolicy);
rollingFileAppender.setEncoder(encoder1);
rollingFileAppender.start();
// add the newly created appenders to the root logger;
// qualify Logger to disambiguate from org.slf4j.Logger
ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) mLogger;
root.detachAndStopAllAppenders();
root.addAppender(rollingFileAppender);
}
}
gradle依赖
compile 'org.slf4j:slf4j-api:1.7.21'
compile 'com.github.tony19:logback-android-core:1.1.1-6'
compile ('com.github.tony19:logback-android-classic:1.1.1-6') {
exclude group: 'com.google.android', module: 'android'
}
我正在通过mLogger.debug(logMessage);
和类似的事件登录......
答案 0 :(得分:0)
问题是,我在另一个库中注册另一个记录器并且log4j
是全局设置的,因此我的小日志类正在登录到其他地方注册的一个记录器...