|
| 1 | +package com.lasthopesoftware.bluewater |
| 2 | + |
| 3 | +import android.content.Context |
| 4 | +import android.os.Environment |
| 5 | +import android.os.StrictMode |
| 6 | +import android.os.StrictMode.VmPolicy |
| 7 | +import androidx.startup.Initializer |
| 8 | +import ch.qos.logback.classic.AsyncAppender |
| 9 | +import ch.qos.logback.classic.Level |
| 10 | +import ch.qos.logback.classic.Logger |
| 11 | +import ch.qos.logback.classic.LoggerContext |
| 12 | +import ch.qos.logback.classic.android.LogcatAppender |
| 13 | +import ch.qos.logback.classic.encoder.PatternLayoutEncoder |
| 14 | +import ch.qos.logback.classic.spi.ILoggingEvent |
| 15 | +import ch.qos.logback.core.rolling.RollingFileAppender |
| 16 | +import ch.qos.logback.core.rolling.TimeBasedRollingPolicy |
| 17 | +import ch.qos.logback.core.util.StatusPrinter |
| 18 | +import com.lasthopesoftware.bluewater.ApplicationDependenciesContainer.applicationDependencies |
| 19 | +import com.lasthopesoftware.bluewater.settings.ApplicationSettingsUpdated |
| 20 | +import com.lasthopesoftware.bluewater.settings.repository.ApplicationSettings |
| 21 | +import com.lasthopesoftware.bluewater.shared.exceptions.UncaughtExceptionHandlerLogger |
| 22 | +import com.lasthopesoftware.bluewater.shared.lazyLogger |
| 23 | +import com.lasthopesoftware.bluewater.shared.messages.registerReceiver |
| 24 | +import com.lasthopesoftware.compilation.DebugFlag |
| 25 | +import com.namehillsoftware.handoff.promises.Promise |
| 26 | +import org.slf4j.ILoggerFactory |
| 27 | +import org.slf4j.LoggerFactory |
| 28 | +import java.io.File |
| 29 | + |
| 30 | +class LoggerFactoryInitializer : Initializer<ILoggerFactory> { |
| 31 | + companion object { |
| 32 | + private val logger by lazyLogger<LoggerFactoryInitializer>() |
| 33 | + } |
| 34 | + |
| 35 | + @Volatile |
| 36 | + private var isLoggingToFile = true |
| 37 | + |
| 38 | + override fun create(context: Context): ILoggerFactory { |
| 39 | + Promise.Rejections.toggleStackTraceFiltering(true) |
| 40 | + |
| 41 | + val loggerFactory = initializeLogging(context) |
| 42 | + |
| 43 | + Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandlerLogger) |
| 44 | + Promise.Rejections.setUnhandledRejectionsReceiver(UncaughtExceptionHandlerLogger) |
| 45 | + |
| 46 | + with (context.applicationDependencies) { |
| 47 | + context |
| 48 | + .applicationDependencies |
| 49 | + .applicationSettings |
| 50 | + .promiseApplicationSettings() |
| 51 | + .then { settings -> |
| 52 | + reinitializeLoggingIfNecessary(context, settings) |
| 53 | + } |
| 54 | + |
| 55 | + registerForApplicationMessages.registerReceiver { _: ApplicationSettingsUpdated -> |
| 56 | + applicationSettings |
| 57 | + .promiseApplicationSettings() |
| 58 | + .then { settings -> |
| 59 | + reinitializeLoggingIfNecessary(context, settings) |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return loggerFactory |
| 65 | + } |
| 66 | + |
| 67 | + override fun dependencies(): List<Class<out Initializer<*>>> = emptyList() |
| 68 | + |
| 69 | + private fun reinitializeLoggingIfNecessary(context: Context, applicationSettings: ApplicationSettings) { |
| 70 | + if (applicationSettings.isLoggingToFile != isLoggingToFile) { |
| 71 | + isLoggingToFile = applicationSettings.isLoggingToFile |
| 72 | + initializeLogging(context) |
| 73 | + |
| 74 | + logger.info("File logging {}.", if (isLoggingToFile) "enabled" else "disabled") |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + private fun initializeLogging(context: Context): ILoggerFactory { |
| 79 | + val loggerFactory = LoggerFactory.getILoggerFactory() |
| 80 | + val lc = loggerFactory as? LoggerContext ?: return loggerFactory |
| 81 | + lc.reset() |
| 82 | + |
| 83 | + // setup LogcatAppender |
| 84 | + val logcatEncoder = PatternLayoutEncoder() |
| 85 | + logcatEncoder.context = lc |
| 86 | + logcatEncoder.pattern = "[%thread] %msg%n" |
| 87 | + logcatEncoder.start() |
| 88 | + val logcatAppender = LogcatAppender() |
| 89 | + logcatAppender.context = lc |
| 90 | + logcatAppender.encoder = logcatEncoder |
| 91 | + logcatAppender.start() |
| 92 | + // add the newly created appenders to the root logger; |
| 93 | + // qualify Logger to disambiguate from org.slf4j.Logger |
| 94 | + val rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME) as Logger |
| 95 | + rootLogger.level = Level.WARN |
| 96 | + rootLogger.addAppender(logcatAppender) |
| 97 | + if (isLoggingToFile && Environment.MEDIA_MOUNTED == Environment.getExternalStorageState() && context.getExternalFilesDir(null) != null) { |
| 98 | + val asyncAppender = AsyncAppender() |
| 99 | + asyncAppender.context = lc |
| 100 | + asyncAppender.name = "ASYNC" |
| 101 | + val externalFilesDir = context.getExternalFilesDir(null) |
| 102 | + if (externalFilesDir != null) { |
| 103 | + val logDir = File(externalFilesDir.path + File.separator + "logs") |
| 104 | + if (!logDir.exists()) logDir.mkdirs() |
| 105 | + val rollingFileAppender = RollingFileAppender<ILoggingEvent>().apply { |
| 106 | + lazy = true |
| 107 | + isAppend = true |
| 108 | + this.context = lc |
| 109 | + file = File(logDir, "log.log").absolutePath |
| 110 | + |
| 111 | + rollingPolicy = TimeBasedRollingPolicy<ILoggingEvent>() |
| 112 | + .also { it.setParent(this) } |
| 113 | + .apply { |
| 114 | + fileNamePattern = File(logDir, "%d{yyyy-MM-dd}.log").absolutePath |
| 115 | + maxHistory = 5 |
| 116 | + this.context = lc |
| 117 | + start() |
| 118 | + } |
| 119 | + |
| 120 | + encoder = PatternLayoutEncoder().apply { |
| 121 | + pattern = "%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n" |
| 122 | + this.context = lc |
| 123 | + start() |
| 124 | + } |
| 125 | + |
| 126 | + start() |
| 127 | + } |
| 128 | + |
| 129 | + asyncAppender.addAppender(rollingFileAppender) |
| 130 | + } |
| 131 | + |
| 132 | + // UNCOMMENT TO TWEAK OPTIONAL SETTINGS |
| 133 | + // excluding caller data (used for stack traces) improves appender's performance |
| 134 | + asyncAppender.isIncludeCallerData = !DebugFlag.isDebugCompilation |
| 135 | + |
| 136 | + asyncAppender.start() |
| 137 | + rootLogger.addAppender(asyncAppender) |
| 138 | + StatusPrinter.print(lc) |
| 139 | + } |
| 140 | + |
| 141 | + if (DebugFlag.isDebugCompilation) { |
| 142 | + rootLogger.level = Level.DEBUG |
| 143 | + logger.info("DEBUG_MODE active") |
| 144 | + StrictMode.setThreadPolicy( |
| 145 | + StrictMode.ThreadPolicy.Builder() |
| 146 | + .detectDiskReads() |
| 147 | + .detectDiskWrites() |
| 148 | + .detectNetwork() // or .detectAll() for all detectable problems |
| 149 | + .penaltyLog() |
| 150 | + .build() |
| 151 | + ) |
| 152 | + StrictMode.setVmPolicy( |
| 153 | + VmPolicy.Builder() |
| 154 | + .detectLeakedSqlLiteObjects() |
| 155 | + .penaltyLog() |
| 156 | + .build() |
| 157 | + ) |
| 158 | + } |
| 159 | + |
| 160 | + return loggerFactory |
| 161 | + } |
| 162 | +} |
0 commit comments