I'm using microlog4android to log to file. The question is how can set maximum file size?
microlog4android FileAppender class has two methods: getLogSize (which always return -1 ) and clear. I could clear log when it reaches certain s开发者_JAVA百科ize but getLogSize doesn't seem to work.
Is there any better, more mature android logging solution that I'm not aware of?
You can use logback-android with the RollingFileAppender
and SizeBasedTriggeringPolicy
, but you should be aware of a bug (src) that may cause your working log file to exceed the max file size. A workaround is to subclass the triggering policy to bypass the bug:
package com.example;
import java.io.File;
import ch.qos.logback.core.util.FileSize;
public class SizeBasedTriggeringPolicy<E> extends ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy<E> {
@Override
public boolean isTriggeringEvent(final File activeFile, final E event) {
return (activeFile.length() >= FileSize.valueOf(getMaxFileSize()).getSize());
}
}
Here's an example config (based on the Logback manual and including the workaround above) that you can put into your AndroidManifest.xml. I tested this in Android 4.0.3 emulator, but I imagine it would also work in earlier versions.
<logback>
<configuration debug="true">
<appender
name="LOGCAT"
class="ch.qos.logback.classic.android.LogcatAppender" >
<encoder>
<pattern>[%method] %msg%n</pattern>
</encoder>
</appender>
<property name="dest.dir" value="/sdcard/test/" />
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${dest.dir}/test.log</file>
<append>false</append>
<!-- #########################################
# Max of 2 backup zip's (plus uncompressed
# working file, ${dest.dir}/test.log)
######################################### -->
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<fileNamePattern>${dest.dir}/test.%i.log.zip</fileNamePattern>
<minIndex>1</minIndex>
<maxIndex>2</maxIndex>
</rollingPolicy>
<!-- #########################################
# Rollover when file size reaches 5MB.
# We're using our custom policy here that
# works around a bug (LBCORE-123).
######################################### -->
<!--<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">-->
<triggeringPolicy class="com.example.SizeBasedTriggeringPolicy">
<maxFileSize>5MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
</encoder>
</appender>
<logger name="com.example.HelloAndroidActivity" level="TRACE">
<appender-ref ref="FILE" />
</logger>
<root level="DEBUG" >
<appender-ref ref="LOGCAT" />
</root>
</configuration>
</logback>
May be you can use normal File apis to retrieve file length and then delete/rename it before initializing Logger if it exceeds size limit.
精彩评论