### FlexiLogger Ktor HTTP Client Plugin Installation Source: https://github.com/projectdelta6/flexilogger/blob/master/CLAUDE.md Demonstrates how to install the FlexiLogger plugin into a Ktor HTTP client. This allows for logging of requests and responses across all supported platforms. ```kotlin HttpClient { installFlexiLogger(Log, LoggingLevel.D) } ``` -------------------------------- ### Basic Logging Examples (Kotlin) Source: https://github.com/projectdelta6/flexilogger/blob/master/README.md This Kotlin code demonstrates various ways to use the `Log` object for different logging levels and scenarios. It shows logging with a class name tag, a string tag, and including exceptions, as well as how to force a log message to be reported. ```kotlin import com.example.Log // Using 'this' as the tag (extracts class name) Log.d(this, "Debug message") Log.i(this, "Info message") Log.w(this, "Warning message") Log.e(this, "Error message", exception) // Using a string tag Log.d("MyTag", "Debug message") // With throwable Log.e("NetworkError", "Failed to fetch data", exception) // Force report (bypasses shouldReport check) Log.e("CriticalError", "This must be reported", forceReport = true) ``` -------------------------------- ### Install FlexiLogger and HTTP Integrations (Kotlin) Source: https://context7.com/projectdelta6/flexilogger/llms.txt Add the FlexiLogger library and its optional HTTP integrations (Ktor or OkHttp) to your Kotlin Multiplatform or Android/JVM project's Gradle build file. This enables flexible logging across different platforms. ```kotlin import io.github.projectdelta6:flexilogger:2.0.0 // Kotlin Multiplatform - build.gradle.kts kotlin { sourceSets { commonMain.dependencies { implementation("io.github.projectdelta6:flexilogger:2.0.0") // Optional: Ktor HTTP logging (all platforms) implementation("io.github.projectdelta6:flexilogger-ktor:2.0.0") } // Optional: OkHttp HTTP logging (JVM/Android only) jvmMain.dependencies { implementation("io.github.projectdelta6:flexilogger-okhttp:2.0.0") } androidMain.dependencies { implementation("io.github.projectdelta6:flexilogger-okhttp:2.0.0") } } } // Android/JVM only - build.gradle.kts dependencies { implementation("io.github.projectdelta6:flexilogger:2.0.0") implementation("io.github.projectdelta6:flexilogger-okhttp:2.0.0") // Optional } ``` -------------------------------- ### Ktor Integration for HTTP Logging in Kotlin (All Platforms) Source: https://github.com/projectdelta6/flexilogger/blob/master/README.md This snippet shows how to integrate FlexiLogger with Ktor's `HttpClient` for logging HTTP requests and responses across all platforms. It offers both a simple installation and a more configurable option using `FlexiLoggerPlugin`. ```kotlin import com.duck.flexilogger.ktor.FlexiLoggerPlugin import com.duck.flexilogger.ktor.installFlexiLogger import io.ktor.client.* // Simple installation val client = HttpClient { installFlexiLogger(Log, LoggingLevel.D) } // Or with full configuration val client = HttpClient { install(FlexiLoggerPlugin) { logger = Log level = LoggingLevel.D tag = "HTTP" logHeaders = true logBody = false sanitizedHeaders = setOf("Authorization", "Cookie") } } ``` -------------------------------- ### Basic FlexiLog Setup (Kotlin) Source: https://github.com/projectdelta6/flexilogger/blob/master/README.md This Kotlin code defines a `Log` object that extends `FlexiLog` to configure logging behavior. It overrides methods to control console output, determine which log types should be reported for crash reporting, and implement the actual reporting mechanism. ```kotlin package com.example import com.duck.flexilogger.FlexiLog import com.duck.flexilogger.LogType object Log : FlexiLog() { override fun canLogToConsole(type: LogType): Boolean { // Return true to output logs to the platform console // Android: android.util.Log // iOS: NSLog // JVM: java.util.logging // JS: console.log/warn/error return true // or: BuildConfig.DEBUG on Android } override fun shouldReport(type: LogType): Boolean { // Return true for log types you want sent to crash reporting return type == LogType.E || type == LogType.WTF } override fun shouldReportException(tr: Throwable): Boolean { // Filter which exceptions get reported // Return false to ignore network errors, cancellations, etc. return true } override fun report(type: LogType, tag: String, msg: String) { // Implement crash reporting (Sentry, Crashlytics, etc.) } override fun report(type: LogType, tag: String, msg: String, tr: Throwable) { // Implement crash reporting with exception } } ``` -------------------------------- ### LogType Enum for Severity Levels (Kotlin) Source: https://context7.com/projectdelta6/flexilogger/llms.txt Defines the LogType enum, representing severity levels for logging. These are used to control console output, crash reporting, and file logging behavior. Includes examples of implementing shouldReport and canLogToConsole. ```kotlin import com.duck.flexilogger.LogType // Available log types val debugType = LogType.D // Debug - development information val errorType = LogType.E // Error - error conditions val infoType = LogType.I // Info - informational messages val verboseType = LogType.V // Verbose - detailed trace information val warningType = LogType.W // Warning - warning conditions val wtfType = LogType.WTF // What a Terrible Failure - should never happen // Usage in shouldReport implementation override fun shouldReport(type: LogType): Boolean { return when (type) { LogType.E, LogType.WTF -> true // Report errors and WTF LogType.W -> false // Don't report warnings LogType.D, LogType.I, LogType.V -> false // Don't report info/debug } } // Usage in canLogToConsole implementation override fun canLogToConsole(type: LogType): Boolean { return when (type) { LogType.V -> isVerboseMode // Verbose only in verbose mode LogType.D -> BuildConfig.DEBUG // Debug only in debug builds else -> true // Always log info, warning, error, wtf } } ``` -------------------------------- ### Gradle Build Commands for FlexiLogger Source: https://github.com/projectdelta6/flexilogger/blob/master/CLAUDE.md Provides essential Gradle commands for building, testing, and cleaning the FlexiLogger project and its modules. These commands are used to manage the build lifecycle across different platforms. ```bash ./gradlew assemble ./gradlew :flexilogger:assemble ./gradlew :flexilogger-okhttp:assemble ./gradlew :flexilogger-ktor:assemble ./gradlew :TestApp:assembleDebug ./gradlew allTests ./gradlew clean ``` -------------------------------- ### Standard Log Methods (Kotlin) Source: https://context7.com/projectdelta6/flexilogger/llms.txt Demonstrates the use of standard log methods like debug, info, verbose, warning, error, and wtf. These methods accept either an object for automatic class name extraction or a string tag, and can include exceptions for error logging. ```kotlin import com.example.Log class UserRepository { fun fetchUser(userId: String) { // Using 'this' as tag - automatically extracts class name "UserRepository" Log.d(this, "Fetching user with ID: $userId") Log.i(this, "User request initiated") Log.v(this, "Verbose details about the request") try { // ... fetch user logic Log.i(this, "User fetched successfully") } catch (e: Exception) { // Error with exception - triggers crash reporting if shouldReport returns true Log.e(this, "Failed to fetch user", e) // Force report even if shouldReport returns false Log.e(this, "Critical failure", e, forceReport = true) } } fun criticalError() { // Using string tag directly Log.wtf("UserRepository", "This should never happen!") // Warning with throwable Log.w("NetworkWarning", "Slow network detected", TimeoutException()) } } // Output examples: // D/UserRepository: Fetching user with ID: user_123 // I/UserRepository: User request initiated // E/UserRepository: Failed to fetch user // java.io.IOException: Network error // at UserRepository.fetchUser(UserRepository.kt:15) ``` -------------------------------- ### FlexiLog Methods Source: https://github.com/projectdelta6/flexilogger/blob/master/README.md Core logging methods available in FlexiLog. ```APIDOC ## FlexiLog Methods ### Description Core logging methods available in FlexiLog. ### Method Logging functions ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```kotlin // Example usage of logging methods: Log.i(this, "User logged in") Log.d("MyTag", "Debug message") Log.e(this, "An error occurred", exception) Log.onCondition(userIsAdmin) { Log.w(this, "Admin action performed") } Log.withLevel(LoggingLevel.D).i(this, "Info message with debug level filter") ``` ### Response N/A ### Details | Method | Description | |--------|-------------| | `i(caller, msg?, tr?)` | Info log | | `d(caller, msg?, tr?)` | Debug log | | `v(caller, msg?, tr?)` | Verbose log | | `w(caller, msg?, tr?)` | Warning log | | `e(caller, msg?, tr?, forceReport?)` | Error log | | `wtf(caller, msg?, tr?)` | What a Terrible Failure log | | `onCondition(condition, log)` | Conditional logging | | `withLevel(level)` | Create level-filtered logger | The `caller` parameter can be: - `Any` - class name is extracted automatically - `String` - used directly as the tag - `Class<*>` - (JVM/Android only) class name is extracted ``` -------------------------------- ### Ktor Client HTTP Logging with FlexiLogger Source: https://context7.com/projectdelta6/flexilogger/llms.txt Integrates FlexiLogger with Ktor's HttpClient to log HTTP requests and responses. Supports custom configurations for log level, headers, and body logging. Requires the flexilogger-ktor module. ```kotlin import com.duck.flexilogger.ktor.FlexiLoggerPlugin import com.duck.flexilogger.ktor.installFlexiLogger import com.duck.flexilogger.LoggingLevel import com.example.Log import io.ktor.client.* import io.ktor.client.request.* import io.ktor.client.statement.* // Simple installation with defaults val simpleClient = HttpClient { installFlexiLogger(Log, LoggingLevel.D) } // Full configuration with all options val configuredClient = HttpClient { install(FlexiLoggerPlugin) { logger = Log level = LoggingLevel.D tag = "HTTP" // Custom log tag logHeaders = true // Log request/response headers logBody = false // Log request/response bodies (impacts performance) sanitizedHeaders = setOf( // Headers to redact from logs "Authorization", "Cookie", "Set-Cookie", "X-Api-Key" ) } } // Make requests - logging happens automatically suspend fun fetchUsers() { val response: HttpResponse = configuredClient.get("https://api.example.com/users") { header("Authorization", "Bearer token123") header("Accept", "application/json") } println("Status: ${response.status}") } ``` -------------------------------- ### File Logging Configuration Source: https://github.com/projectdelta6/flexilogger/blob/master/README.md Override `shouldLogToFile` and `writeLogToFile` methods to customize file logging behavior. ```APIDOC ## File Logging Configuration ### Description Override the file logging methods to enable persistent logging. ### Method Overrides in a `FlexiLog` subclass ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```kotlin object Log : FlexiLog() { // ... other overrides ... override fun shouldLogToFile(type: LogType): Boolean { return true // or filter by type } override fun writeLogToFile( timestamp: Long, type: LogType, tag: String, msg: String, tr: Throwable? ) { // Implement your file writing logic val logLine = "[$timestamp] ${type.name}/$tag: $msg" // Write to file... } } ``` ### Response N/A ``` -------------------------------- ### OkHttp Integration Source: https://github.com/projectdelta6/flexilogger/blob/master/README.md Integrate FlexiLogger with OkHttp for logging HTTP requests and responses. ```APIDOC ## OkHttp Integration ### Description Integrate FlexiLogger with OkHttp for logging HTTP requests and responses on JVM/Android. ### Method Interceptor configuration ### Endpoint N/A ### Parameters N/A ### Request Example ```kotlin import com.duck.flexilogger.okhttp.FlexiLogHttpLoggingInterceptorLogger import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor val loggingInterceptor = HttpLoggingInterceptor( FlexiLogHttpLoggingInterceptorLogger.with(Log, LoggingLevel.D) ).apply { level = HttpLoggingInterceptor.Level.BODY } val client = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build() ``` ### Response N/A ``` -------------------------------- ### Ktor Integration Source: https://github.com/projectdelta6/flexilogger/blob/master/README.md Integrate FlexiLogger with Ktor for logging HTTP requests and responses across all platforms. ```APIDOC ## Ktor Integration ### Description Integrate FlexiLogger with Ktor for logging HTTP requests and responses on all platforms. ### Method Client installation ### Endpoint N/A ### Parameters N/A ### Request Example ```kotlin import com.duck.flexilogger.ktor.FlexiLoggerPlugin import com.duck.flexilogger.ktor.installFlexiLogger import io.ktor.client.* // Simple installation val client = HttpClient { installFlexiLogger(Log, LoggingLevel.D) } // Or with full configuration val client = HttpClient { install(FlexiLoggerPlugin) { logger = Log level = LoggingLevel.D tag = "HTTP" logHeaders = true logBody = false sanitizedHeaders = setOf("Authorization", "Cookie") } } ``` ### Response N/A ``` -------------------------------- ### OkHttp Integration with FlexiLogger in Kotlin Source: https://context7.com/projectdelta6/flexilogger/llms.txt The `flexilogger-okhttp` module integrates FlexiLogger with OkHttp's `HttpLoggingInterceptor`. It allows using FlexiLogger for logging HTTP requests and responses, configurable with a logging level and an optional custom tag. The interceptor can be added to an OkHttpClient builder. ```kotlin import com.duck.flexilogger.okhttp.FlexiLogHttpLoggingInterceptorLogger import com.duck.flexilogger.LoggingLevel import com.example.Log import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.logging.HttpLoggingInterceptor // Create the logging interceptor with FlexiLogger val loggingInterceptor = HttpLoggingInterceptor( FlexiLogHttpLoggingInterceptorLogger.with(Log, LoggingLevel.D) ).apply { level = HttpLoggingInterceptor.Level.BODY // NONE, BASIC, HEADERS, or BODY } // Or with a custom tag val customTagInterceptor = HttpLoggingInterceptor( FlexiLogHttpLoggingInterceptorLogger.with(Log, LoggingLevel.D, "API") ) // Build the OkHttpClient with the interceptor val client = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build() // Make requests - logging happens automatically val request = Request.Builder() .url("https://api.example.com/users") .build() client.newCall(request).execute().use { response -> println("Response: ${response.code}") } // Console output example: // I/HttpLoggingInterceptor: --> GET https://api.example.com/users // I/HttpLoggingInterceptor: Host: api.example.com // I/HttpLoggingInterceptor: --> END GET // I/HttpLoggingInterceptor: <-- 200 OK (150ms) // I/HttpLoggingInterceptor: Content-Type: application/json // I/HttpLoggingInterceptor: {"users": [...]} // I/HttpLoggingInterceptor: <-- END HTTP ``` -------------------------------- ### Platform-Specific Logging Declarations (Kotlin Multiplatform) Source: https://github.com/projectdelta6/flexilogger/blob/master/CLAUDE.md Defines `expect` declarations for platform-specific logging functions and utility methods in Kotlin Multiplatform projects. These are implemented in `actual` declarations for each target platform (Android, JVM, iOS, JS). ```kotlin internal expect fun platformLog(type: LogType, tag: String, message: String, throwable: Throwable?) internal expect fun getSimpleClassName(obj: Any): String internal expect fun getSimpleClassName(clazz: KClass<*>): String internal expect fun currentTimeMillis(): Long ``` -------------------------------- ### Create Custom FlexiLog Implementation (Kotlin) Source: https://context7.com/projectdelta6/flexilogger/llms.txt Extend the `FlexiLog` abstract class to create a custom logger singleton. This implementation allows you to control console output, crash reporting, exception filtering, and file logging behavior based on log types and specific exceptions. ```kotlin package com.example import com.duck.flexilogger.FlexiLog import com.duck.flexilogger.LogType import java.net.ConnectException import java.net.SocketException import java.net.SocketTimeoutException import java.net.UnknownHostException import kotlin.coroutines.cancellation.CancellationException object Log : FlexiLog() { // Control whether logs appear in console output // Android uses android.util.Log, iOS uses NSLog, JVM uses java.util.logging, JS uses console override fun canLogToConsole(type: LogType): Boolean { return BuildConfig.DEBUG // Only log to console in debug builds } // Determine which log types should trigger crash reporting override fun shouldReport(type: LogType): Boolean { return type == LogType.E || type == LogType.WTF } // Filter out exceptions that shouldn't be reported (network errors, cancellations) override fun shouldReportException(tr: Throwable): Boolean { return when (tr) { is CancellationException, is UnknownHostException, is ConnectException, is SocketException, is SocketTimeoutException -> false else -> true } } // Implement crash reporting (Sentry, Crashlytics, etc.) override fun report(type: LogType, tag: String, msg: String) { // Crashlytics.log("${type.name}/$tag: $msg") } override fun report(type: LogType, tag: String, msg: String, tr: Throwable) { // Crashlytics.recordException(tr) } // Optional: Enable file logging override fun shouldLogToFile(type: LogType): Boolean { return type == LogType.E || type == LogType.WTF } override fun writeLogToFile(timestamp: Long, type: LogType, tag: String, msg: String, tr: Throwable?) { val logLine = "[$timestamp] ${type.name}/$tag: $msg" // Write to your log file implementation } } ``` -------------------------------- ### Add FlexiLogger Dependency (JitPack Legacy) Source: https://github.com/projectdelta6/flexilogger/blob/master/README.md This snippet provides instructions for adding FlexiLogger (legacy 1.x versions) using JitPack for Android-only projects. It includes configuring the JitPack repository in `settings.gradle.kts` and adding the necessary dependencies in `build.gradle.kts`. ```kotlin dependencyResolutionManagement { repositories { maven { url = uri("https://jitpack.io") } } } dependencies { implementation("com.github.projectdelta6.FlexiLogger:FlexiLogger:1.x.x") implementation("com.github.projectdelta6.FlexiLogger:FlexiHttpLogger:1.x.x") // Optional } ``` -------------------------------- ### FlexiLogger OkHttp Interceptor Logger Bridge Source: https://github.com/projectdelta6/flexilogger/blob/master/CLAUDE.md Shows how to bridge FlexiLog with OkHttp's HttpLoggingInterceptor.Logger for JVM and Android platforms. This enables detailed HTTP request and response logging within OkHttp clients. ```kotlin FlexiLogHttpLoggingInterceptorLogger.with(Log, LoggingLevel.D) ``` -------------------------------- ### Add FlexiLogger Dependency (Android/JVM) Source: https://github.com/projectdelta6/flexilogger/blob/master/README.md This snippet demonstrates how to include the FlexiLogger library and its optional OkHttp integration for Android and JVM-only projects. It simplifies adding the logging functionality to applications targeting these specific platforms. ```kotlin dependencies { implementation("io.github.projectdelta6:flexilogger:2.0.0") implementation("io.github.projectdelta6:flexilogger-okhttp:2.0.0") // Optional } ``` -------------------------------- ### File Logging Implementation with FlexiLogger Source: https://context7.com/projectdelta6/flexilogger/llms.txt Customizes FlexiLogger to enable file logging by overriding `shouldLogToFile` and `writeLogToFile`. This allows persisting logs to a specified file with timestamps and formatting. Requires manual implementation of file writing logic. ```kotlin import com.duck.flexilogger.FlexiLog import com.duck.flexilogger.LogType import java.io.File import java.text.SimpleDateFormat import java.util.* object Log : FlexiLog() { private val logFile = File("/path/to/app/logs/app.log") private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US) override fun canLogToConsole(type: LogType) = true override fun shouldReport(type: LogType) = type == LogType.E override fun shouldReportException(tr: Throwable) = true override fun report(type: LogType, tag: String, msg: String) {} override fun report(type: LogType, tag: String, msg: String, tr: Throwable) {} // Enable file logging for errors and warnings only override fun shouldLogToFile(type: LogType): Boolean { return type == LogType.E || type == LogType.W || type == LogType.WTF } // Write logs to file with timestamp and formatting override fun writeLogToFile( timestamp: Long, type: LogType, tag: String, msg: String, tr: Throwable? ) { val date = dateFormat.format(Date(timestamp)) val logLine = buildString { append("[$date] ${type.name}/$tag: $msg") if (tr != null) { append("\n") append(tr.stackTraceToString()) } append("\n") } logFile.appendText(logLine) } } // Usage - file logging happens automatically for E, W, WTF levels Log.d("App", "Debug message") // Console only Log.i("App", "Info message") // Console only Log.w("App", "Warning message") // Console + File Log.e("App", "Error occurred", exception) // Console + File + Crash reporting ``` -------------------------------- ### Add FlexiLogger Dependency (Kotlin Multiplatform) Source: https://github.com/projectdelta6/flexilogger/blob/master/README.md This snippet shows how to add the FlexiLogger library and its optional Ktor HTTP logging module to a Kotlin Multiplatform project's common main source set dependencies. It ensures the logging capabilities are available across all supported platforms. ```kotlin kotlin { sourceSets { commonMain.dependencies { implementation("io.github.projectdelta6:flexilogger:2.0.0") // Optional: Ktor HTTP logging (all platforms) implementation("io.github.projectdelta6:flexilogger-ktor:2.0.0") } // Optional: OkHttp HTTP logging (JVM/Android only) jvmMain.dependencies { implementation("io.github.projectdelta6:flexilogger-okhttp:2.0.0") } androidMain.dependencies { implementation("io.github.projectdelta6:flexilogger-okhttp:2.0.0") } } } ``` -------------------------------- ### OkHttp Integration for HTTP Logging in Kotlin (JVM/Android) Source: https://github.com/projectdelta6/flexilogger/blob/master/README.md This code integrates FlexiLogger with OkHttp for HTTP request and response logging on JVM and Android platforms. It uses `FlexiLogHttpLoggingInterceptorLogger` to bridge FlexiLogger with OkHttp's `HttpLoggingInterceptor`. ```kotlin import com.duck.flexilogger.okhttp.FlexiLogHttpLoggingInterceptorLogger import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor val loggingInterceptor = HttpLoggingInterceptor( FlexiLogHttpLoggingInterceptorLogger.with(Log, LoggingLevel.D) ).apply { level = HttpLoggingInterceptor.Level.BODY } val client = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build() ``` -------------------------------- ### LogType Enum Source: https://github.com/projectdelta6/flexilogger/blob/master/README.md Defines the different types of log messages. ```APIDOC ## LogType Enum ### Description Defines the different types of log messages. ### Method Enum definition ### Endpoint N/A ### Parameters N/A ### Request Example ```kotlin enum class LogType { D, // Debug E, // Error I, // Info V, // Verbose W, // Warning WTF // What a Terrible Failure } ``` ### Response N/A ``` -------------------------------- ### Level-Based Logging with LoggerWithLevel (Kotlin) Source: https://github.com/projectdelta6/flexilogger/blob/master/README.md This Kotlin code shows how to create a `LoggerWithLevel` instance from the main `Log` object to filter logs based on a minimum severity level. This is useful for isolating logs from specific subsystems, such as network operations, ensuring only relevant messages are displayed. ```kotlin // Create a logger that only logs WARNING and above val networkLogger = Log.withLevel(LoggingLevel.W) networkLogger.d("Network", "This won't be logged") // Filtered out networkLogger.w("Network", "This will be logged") // Passes through networkLogger.e("Network", "This will be logged") // Passes through ``` -------------------------------- ### LoggingLevel Enum Source: https://github.com/projectdelta6/flexilogger/blob/master/README.md Hierarchical levels for filtering log messages. ```APIDOC ## LoggingLevel Enum ### Description Hierarchical levels for filtering (higher value = more verbose). ### Method Enum definition ### Endpoint N/A ### Parameters N/A ### Request Example ```kotlin enum class LoggingLevel(val level: Int) { V(5), // Verbose - logs everything I(4), // Info D(3), // Debug W(2), // Warning E(1), // Error only NONE(0) // Logs nothing } ``` ### Response N/A ``` -------------------------------- ### Conditional Logging (Kotlin) Source: https://github.com/projectdelta6/flexilogger/blob/master/README.md This Kotlin code illustrates conditional logging using `Log.onCondition` and `Log.onConditionSuspend`. These methods allow logging messages only when a specified condition is met, which is useful for enabling detailed logs in debug builds or specific runtime states. ```kotlin // Only logs if condition is true Log.onCondition(BuildConfig.DEBUG) { logger -> logger.d(this, "This only logs in debug builds") } // Suspend version for coroutines Log.onConditionSuspend(isVerboseMode) { logger -> logger.v(this, "Verbose logging enabled") } ``` -------------------------------- ### Conditional Logging in Kotlin Source: https://context7.com/projectdelta6/flexilogger/llms.txt The `onCondition` and `onConditionSuspend` methods enable logging only when a specified condition is true. This prevents unnecessary string concatenation and computation for logs that would otherwise be filtered out. The suspend version is suitable for use within coroutines. ```kotlin import com.example.Log class DataProcessor { private val isVerboseMode = false private val isDebugBuild = BuildConfig.DEBUG fun processData(data: List) { // Conditional logging - block only executes if condition is true Log.onCondition(isDebugBuild) { logger -> logger.d(this, "Processing ${data.size} items") logger.d(this, "First item: ${data.firstOrNull()}") } // Useful for expensive logging that should only run in debug Log.onCondition(isVerboseMode) { logger -> val expensiveDebugInfo = data.joinToString("\n") { "Item: $it" } logger.v(this, "Full data dump:\n$expensiveDebugInfo") } // Nothing happens if condition is false - no string building overhead Log.onCondition(false) { logger -> logger.d(this, "This will never execute") } } // Suspend version for coroutines suspend fun processDataAsync(data: List) { Log.onConditionSuspend(isDebugBuild) { logger -> // Can call suspend functions inside val asyncInfo = fetchDebugInfoAsync() logger.d(this, "Async debug info: $asyncInfo") } } } ``` -------------------------------- ### Filtered Logging with LoggerWithLevel in Kotlin Source: https://context7.com/projectdelta6/flexilogger/llms.txt LoggerWithLevel allows creating loggers that filter messages based on a minimum logging level. This is useful for subsystem-specific logging. It takes a LoggingLevel and a FlexiLog instance, and supports dynamic level updates and checking if a log type will pass the filter. ```kotlin import com.example.Log import com.duck.flexilogger.LoggingLevel class NetworkClient { // Create a logger that only logs WARNING and above private val networkLogger = Log.withLevel(LoggingLevel.W) // Alternative: Create with LoggerWithLevel directly // private val networkLogger = LoggerWithLevel(LoggingLevel.W, Log) fun makeRequest(url: String) { // These will be filtered out (below WARNING level) networkLogger.d("NetworkClient", "Starting request to $url") networkLogger.i("NetworkClient", "Request in progress") networkLogger.v("NetworkClient", "Verbose network details") // These will be logged (at or above WARNING level) networkLogger.w("NetworkClient", "Slow response detected") networkLogger.e("NetworkClient", "Request failed", IOException()) networkLogger.wtf("NetworkClient", "Unexpected state") } fun updateLogLevel(isDebugMode: Boolean) { // Dynamically update the logging level val newLevel = if (isDebugMode) LoggingLevel.V else LoggingLevel.W networkLogger.updateLogger(newLevel = newLevel) } fun checkIfWillLog() { // Check if a specific log type will pass the filter if (networkLogger.canLog(LogType.D)) { // Expensive debug computation only if it will be logged val debugInfo = computeExpensiveDebugInfo() networkLogger.d("NetworkClient", debugInfo) } } } ``` -------------------------------- ### Override File Logging Methods in Kotlin Source: https://github.com/projectdelta6/flexilogger/blob/master/README.md This snippet demonstrates how to override the `shouldLogToFile` and `writeLogToFile` methods in a custom `FlexiLog` object to enable persistent file logging. You can customize the file writing logic and filtering based on log type. ```kotlin object Log : FlexiLog() { // ... other overrides ... override fun shouldLogToFile(type: LogType): Boolean { return true // or filter by type } override fun writeLogToFile( timestamp: Long, type: LogType, tag: String, msg: String, tr: Throwable? ) { // Implement your file writing logic val logLine = "[$timestamp] ${type.name}/$tag: $msg" // Write to file... } } ``` -------------------------------- ### LoggingLevel Enum Definition in Kotlin Source: https://github.com/projectdelta6/flexilogger/blob/master/README.md Defines the `LoggingLevel` enum, which provides hierarchical levels for filtering log messages. Higher values indicate more verbose logging, allowing fine-grained control over which messages are outputted. ```kotlin enum class LoggingLevel(val level: Int) { V(5), // Verbose - logs everything I(4), // Info D(3), // Debug W(2), // Warning E(1), // Error only NONE(0) // Logs nothing } ``` -------------------------------- ### LogType Enum Definition in Kotlin Source: https://github.com/projectdelta6/flexilogger/blob/master/README.md Defines the `LogType` enum, which represents different levels of log messages such as Debug, Error, Info, Verbose, Warning, and WTF (What a Terrible Failure). This enum is used to categorize log entries. ```kotlin enum class LogType { D, // Debug E, // Error I, // Info V, // Verbose W, // Warning WTF // What a Terrible Failure } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.