Search code examples
androidlogback

Specify the sdcard application data directory path to logback-android


I am using logback-android in my app for logging. I need to write the log to a file in the application data directory in sdcard. I used below file appender config.

<appender name="file" class="ch.qos.logback.core.FileAppender">
    <file>/sdcard/Android/data/com.my.app/files/app.log</file>
    <encoder>
        <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
</appender>

It can be seen that I have used following log file location.

/sdcard/Android/data/com.my.app/files/app.log

I also can use log file location like below.

/storage/emulated/0/Android/data/com.my.app/files/app.log

Above path is the path returned by getExternalFilesDir().

But, the example in the project wiki page uses file location in following format.

/data/data/com.example/files/log/foo.log.

Above path format does not work in my case, where earlier two path formats I mentioned did work.

What is the correct way to specify the application data directory path in the logback.xml? Can the directory path vary from the first two patterns I mentioned, in various devices?


Solution

  • I finally decided to set the file path programatically. I added following code to the onCreate() of my custom Application class.

    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) {
        for (Iterator<Appender<ILoggingEvent>> index = logger.iteratorForAppenders(); index.hasNext(); ) {
            Appender<ILoggingEvent> appender = index.next();
            if (appender instanceof FileAppender) {
                ((FileAppender) appender).setFile(new File(getExternalFilesDir(null), "app.log").getAbsolutePath());
                appender.start();
            }
        }
    }