2

I want to write logback output to a log file which can then be sent back to me by the user. My logback.xml is below. My problem is that my logging will only work if the location that I specify is "/storage/emulated/0"...(which is device-specific). If I simply specify "/data/data/mypackage/files/log/debug.log" then nothing gets written.

What is the best way of specifying the path for my file in a way which will be compatible with all Android 4.x devices?

<configuration debug="true">
    <!-- Create a file appender for a log in the application's data directory -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>/storage/emulated/0/data/data/mypackage/files/log/debug.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
            <fileNamePattern>debug.%i.log.zip</fileNamePattern>
            <minIndex>1</minIndex>
            <maxIndex>3</maxIndex>
        </rollingPolicy>
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <maxFileSize>5MB</maxFileSize>
        </triggeringPolicy>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- Write INFO (and higher-level) messages to the log file -->
    <root level="INFO">
        <appender-ref ref="FILE" />
    </root>
</configuration>

1 Answer 1

0

You can specify file path in code in stead of in logback.xml. Use getFilesDir() to get the absolute path to the filesystem directory where your internal files are saved.

LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
RollingFileAppender rfAppender = new RollingFileAppender();
rfAppender.setContext(loggerContext);

final File folder = getFilesDir();
final File logFile = new File(folder, "testFile.log");
rfAppender.setFile(logFile.getPath());
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply. Where is the optimum place in an Android app to place this sort of code? Presumably it shouldn't be necessary to set the file path before writing each entry to the log, but is there a class/method where this can be placed so that it will always be set correctly whenever it is needed?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.