### Start Network Activity Logging with AlamofireNetworkActivityLogger (Swift) Source: https://context7.com/konkab/alamofirenetworkactivitylogger/llms.txt Initializes and starts logging all Alamofire network requests and responses using the shared singleton instance. This basic setup typically resides in your AppDelegate. The library intercepts network activity without modifying the core networking layer. ```swift import AlamofireNetworkActivityLogger import Alamofire // Basic setup - typically in AppDelegate func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Start logging with default .info level NetworkActivityLogger.shared.startLogging() // Make a sample request - it will be automatically logged AF.request("https://api.github.com/users/alamofire") .responseJSON { response in switch response.result { case .success(let data): print("Success: \(data)") case .failure(let error): print("Error: \(error)") } } return true } // Console output: // --------------------- // GET 'https://api.github.com/users/alamofire' // --------------------- // 200 'https://api.github.com/users/alamofire' [0.3421 s] ``` -------------------------------- ### Start Network Activity Logging in Swift Source: https://github.com/konkab/alamofirenetworkactivitylogger/blob/master/README.md This Swift code snippet shows how to import the AlamofireNetworkActivityLogger library and start the shared logger instance. This will log all network requests and responses made by Alamofire to the console. ```swift import AlamofireNetworkActivityLogger NetworkActivityLogger.shared.startLogging() ``` -------------------------------- ### Usage Example: Fetch User and Log in View Controller in Swift Source: https://context7.com/konkab/alamofirenetworkactivitylogger/llms.txt Demonstrates how to use the `APIClient` within a `UserProfileViewController`. It shows fetching user data and temporarily enabling debug logging for the specific network call, then restoring the previous logging level. This highlights dynamic control over logging. ```swift // Usage in view controller class UserProfileViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Enable detailed logging temporarily for debugging let previousLevel = NetworkActivityLogger.shared.level NetworkActivityLogger.shared.level = .debug APIClient.shared.fetchUser(id: "12345") { result in // Restore previous logging level NetworkActivityLogger.shared.level = previousLevel switch result { case .success(let user): print("Loaded user: \(user.name)") case .failure(let error): print("Failed to load user: \(error)") } } } } ``` -------------------------------- ### Install AlamofireNetworkActivityLogger with Carthage Source: https://github.com/konkab/alamofirenetworkactivitylogger/blob/master/README.md This code snippet demonstrates how to integrate AlamofireNetworkActivityLogger into your Xcode project using Carthage. It involves specifying the framework in the Cartfile. ```ogdl github "konkab/AlamofireNetworkActivityLogger" ~> 3.4 ``` -------------------------------- ### Install AlamofireNetworkActivityLogger with CocoaPods Source: https://github.com/konkab/alamofirenetworkactivitylogger/blob/master/README.md This code snippet shows how to add AlamofireNetworkActivityLogger as a dependency to your Xcode project using CocoaPods. It specifies the source, platform, and framework usage, then installs the pod. ```ruby source 'https://github.com/CocoaPods/Specs.git' platform :ios, '10.0' use_frameworks! pod 'AlamofireNetworkActivityLogger', '~> 3.4' ``` -------------------------------- ### Install AlamofireNetworkActivityLogger with Swift Package Manager Source: https://github.com/konkab/alamofirenetworkactivitylogger/blob/master/README.md This code snippet shows how to add AlamofireNetworkActivityLogger as a dependency to your Swift package. It uses the .package function with the repository URL and versioning information. ```swift dependencies: [ .package(url: "https://github.com/konkab/AlamofireNetworkActivityLogger.git", .upToNextMajor(from: "3.4.0")) ] ``` -------------------------------- ### Demonstrate Alamofire Network Activity Logger Levels Source: https://context7.com/konkab/alamofirenetworkactivitylogger/llms.txt This Swift code demonstrates the usage of different `NetworkActivityLoggerLevel` settings within the Alamofire framework. It shows how to set the shared logger's level to `.off`, `.debug`, `.info`, `.warn`, `.error`, and `.fatal`, and start logging to observe the varying output detail for network requests. This requires the `AlamofireNetworkActivityLogger` framework. ```swift import AlamofireNetworkActivityLogger // Example usage with all levels class LoggingExamples { func demonstrateAllLevels() { // Level: .off - Completely silent NetworkActivityLogger.shared.level = .off NetworkActivityLogger.shared.startLogging() // No output for any requests // Level: .debug - Maximum verbosity NetworkActivityLogger.shared.level = .debug // Output: method, URL, headers, cURL command, response status, // response headers, pretty-printed JSON body, elapsed time // Level: .info - Standard logging (default) NetworkActivityLogger.shared.level = .info // Output: method, URL for requests // status code, URL, elapsed time for responses // Level: .warn - Only failures NetworkActivityLogger.shared.level = .warn // Output: only logs requests that result in errors // Level: .error - Only failures (identical to .warn) NetworkActivityLogger.shared.level = .error // Output: only logs requests that result in errors // Level: .fatal - Completely silent (identical to .off) NetworkActivityLogger.shared.level = .fatal // No output for any requests } func dynamicLevelAdjustment() { // Start with info level NetworkActivityLogger.shared.level = .info NetworkActivityLogger.shared.startLogging() // Temporarily increase to debug for troubleshooting NetworkActivityLogger.shared.level = .debug // Make problematic request AF.request("https://api.example.com/problematic-endpoint") .responseJSON { response in // Analyze debug output // Return to info level NetworkActivityLogger.shared.level = .info } } } ``` -------------------------------- ### Configure Alamofire Network Activity Logger in Swift Source: https://context7.com/konkab/alamofirenetworkactivitylogger/llms.txt Configures the AlamofireNetworkActivityLogger based on the build environment. It sets different logging levels (debug, info, error) and applies a predicate to filter out specific URLs in debug builds. The logger is started using `startLogging()`. ```swift import UIKit import Alamofire import AlamofireNetworkActivityLogger @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Configure network activity logging configureNetworkLogging() return true } private func configureNetworkLogging() { #if DEBUG // Debug builds: verbose logging NetworkActivityLogger.shared.level = .debug // Filter out noisy endpoints let filter = NSPredicate(format: "NOT (URL.path CONTAINS[c] '/analytics' OR URL.path CONTAINS[c] '/tracking')") NetworkActivityLogger.shared.filterPredicate = filter #elseif STAGING // Staging builds: moderate logging NetworkActivityLogger.shared.level = .info #else // Production builds: errors only NetworkActivityLogger.shared.level = .error #endif NetworkActivityLogger.shared.startLogging() } } ``` -------------------------------- ### API Client with Alamofire and Network Logging in Swift Source: https://context7.com/konkab/alamofirenetworkactivitylogger/llms.txt Implements an API client using Alamofire's `Session` with a custom configuration including a request timeout. It provides methods to fetch user data and perform user login, with all network requests automatically logged by the configured AlamofireNetworkActivityLogger. Error handling for responses is included. ```swift // API Client with integrated logging class APIClient { static let shared = APIClient() private let session: Session private init() { let configuration = URLSessionConfiguration.default configuration.timeoutIntervalForRequest = 30 self.session = Session(configuration: configuration) } func fetchUser(id: String, completion: @escaping (Result) -> Void) { // This request will be automatically logged session.request("https://api.example.com/users/\(id)") .validate() .responseDecodable(of: User.self) { response in switch response.result { case .success(let user): completion(.success(user)) case .failure(let error): // Error will be logged automatically completion(.failure(error)) } } } func login(email: String, password: String, completion: @escaping (Result) -> Void) { let parameters: [String: String] = [ "email": email, "password": password ] // Authentication requests might be filtered out by predicate session.request("https://api.example.com/auth/login", method: .post, parameters: parameters, encoder: JSONParameterEncoder.default) .validate() .responseDecodable(of: AuthToken.self) { response in switch response.result { case .success(let token): completion(.success(token)) case .failure(let error): completion(.failure(error)) } } } } // Models struct User: Codable { let id: String let name: String let email: String } struct AuthToken: Codable { let token: String let expiresAt: Date } ``` -------------------------------- ### Expected Console Output for Network Request in Swift Source: https://context7.com/konkab/alamofirenetworkactivitylogger/llms.txt Illustrates the expected console output when a network request is made with AlamofireNetworkActivityLogger set to `.debug` level. It includes the cURL command, the HTTP status code, response time, headers, and the JSON body of the response. ```text // Expected console output at .debug level: // --------------------- // GET 'https://api.example.com/users/12345': // cURL: // curl -v \ // -X GET \ // -H "Accept: application/json" \ // 'https://api.example.com/users/12345' // // --------------------- // 200 'https://api.example.com/users/12345' [0.2841 s]: // Headers: [ // Content-Type: application/json // Content-Length: 156 // ] // Body: // { // "id": "12345", // "name": "John Doe", // "email": "john@example.com" // } ``` -------------------------------- ### Stop and Restart Alamofire Network Logging Source: https://context7.com/konkab/alamofirenetworkactivitylogger/llms.txt Provides methods to dynamically enable or disable Alamofire network request logging at runtime. This is useful for temporary debugging or conditional logging without recompiling. Ensure Alamofire and AlamofireNetworkActivityLogger are imported. ```swift import AlamofireNetworkActivityLogger import Alamofire class NetworkManager { func enableDebugLogging() { NetworkActivityLogger.shared.level = .debug NetworkActivityLogger.shared.startLogging() print("Network logging enabled") } func disableLogging() { NetworkActivityLogger.shared.stopLogging() print("Network logging disabled") } func makeRequest() { AF.request("https://httpbin.org/get") .responseJSON { response in print("Request completed") } } } // Usage example let manager = NetworkManager() // Enable logging for debugging manager.enableDebugLogging() manager.makeRequest() // Disable logging manager.disableLogging() manager.makeRequest() // Re-enable with different level NetworkActivityLogger.shared.level = .info NetworkActivityLogger.shared.startLogging() manager.makeRequest() ``` -------------------------------- ### Conditional Alamofire Logging for Builds (Swift) Source: https://context7.com/konkab/alamofirenetworkactivitylogger/llms.txt Configure AlamofireNetworkActivityLogger based on build configurations like DEBUG, RELEASE, or custom schemes (e.g., DEVELOPMENT, STAGING). This allows for different logging levels or disabling logging entirely for different environments. ```swift import AlamofireNetworkActivityLogger import Alamofire // Example 1: Basic DEBUG/RELEASE configuration class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { #if DEBUG NetworkActivityLogger.shared.level = .debug NetworkActivityLogger.shared.startLogging() print("Network logging enabled for DEBUG build") #else NetworkActivityLogger.shared.level = .off print("Network logging disabled for RELEASE build") #endif return true } } // Example 2: Custom build configuration with schemes enum Environment { case development case staging case production static var current: Environment { #if DEVELOPMENT return .development #elseif STAGING return .staging #else return .production #endif } } func configureNetworkLogging() { switch Environment.current { case .development: NetworkActivityLogger.shared.level = .debug NetworkActivityLogger.shared.startLogging() case .staging: NetworkActivityLogger.shared.level = .info NetworkActivityLogger.shared.startLogging() // Filter out health checks in staging let filter = NSPredicate(format: "URL.path CONTAINS[c] '/health'") NetworkActivityLogger.shared.filterPredicate = filter case .production: // Only log errors in production NetworkActivityLogger.shared.level = .error NetworkActivityLogger.shared.startLogging() } } ``` -------------------------------- ### Define Alamofire Network Activity Logger Levels Source: https://context7.com/konkab/alamofirenetworkactivitylogger/llms.txt This Swift code defines the `NetworkActivityLoggerLevel` enumeration, which controls the verbosity of network request logging. It includes distinct levels like `off`, `debug`, `info`, `warn`, `error`, and `fatal`, each with specific logging behaviors and use cases for managing output. The enum requires the `AlamofireNetworkActivityLogger` framework. ```swift import AlamofireNetworkActivityLogger // NetworkActivityLoggerLevel enum definition public enum NetworkActivityLoggerLevel { case off // No logging case debug // Full details: method, URL, headers, body, cURL, response case info // Basic: method, URL, status code, elapsed time case warn // Only failed requests case error // Only failed requests (same as warn) case fatal // No logging (same as off) } ``` -------------------------------- ### Configure Logging Verbosity Levels for AlamofireNetworkActivityLogger (Swift) Source: https://context7.com/konkab/alamofirenetworkactivitylogger/llms.txt Control the amount of detail logged by setting the logging level, with options ranging from silent to full debug output including cURL commands and response bodies. This allows for dynamic adjustment of logging verbosity based on debugging needs. ```swift import AlamofireNetworkActivityLogger import Alamofire // Example 1: Debug level for maximum detail NetworkActivityLogger.shared.level = .debug NetworkActivityLogger.shared.startLogging() AF.request("https://httpbin.org/get", parameters: ["foo": "bar"]) .responseJSON { response in print("Request completed") } // Console output at .debug level: // --------------------- // GET 'https://httpbin.org/get?foo=bar': // cURL: // curl -v \ // -X GET \ // -H "User-Agent: MyApp/1.0" \ // 'https://httpbin.org/get?foo=bar' // // --------------------- // 200 'https://httpbin.org/get?foo=bar' [0.2145 s]: // Headers: [ // Content-Type: application/json // Content-Length: 324 // ] // Body: // { // "args": { // "foo": "bar" // }, // "headers": { // "User-Agent": "MyApp/1.0" // }, // "url": "https://httpbin.org/get?foo=bar" // } // Example 2: Error level to only log failures NetworkActivityLogger.shared.level = .error AF.request("https://httpbin.org/status/404") .responseJSON { response in print("Request failed as expected") } // Console output at .error level (only failures): // --------------------- // [Error] GET 'https://httpbin.org/status/404' [0.1523 s] // Example 3: Info level (default) for balanced logging NetworkActivityLogger.shared.level = .info AF.request("https://httpbin.org/post", method: .post, parameters: ["key": "value"]) .responseJSON { response in print("Posted data") } // Console output at .info level: // --------------------- // POST 'https://httpbin.org/post' // --------------------- // 200 'https://httpbin.org/post' [0.4231 s] // Example 4: Turn off all logging NetworkActivityLogger.shared.level = .off // No output will be generated ``` -------------------------------- ### Filter Alamofire Network Requests with NSPredicate Source: https://context7.com/konkab/alamofirenetworkactivitylogger/llms.txt Demonstrates how to use NSPredicate to filter which network requests are logged by Alamofire Network Activity Logger. This allows excluding sensitive endpoints, health checks, or other specific requests. It supports filtering by URL path and HTTP method. Ensure Alamofire and AlamofireNetworkActivityLogger are imported. ```swift import AlamofireNetworkActivityLogger import Alamofire // Example 1: Filter out authentication endpoints let authFilter = NSPredicate(format: "URL.path CONTAINS[c] '/auth'") NetworkActivityLogger.shared.filterPredicate = authFilter NetworkActivityLogger.shared.startLogging() // This request will be logged AF.request("https://api.example.com/users/profile") .responseJSON { response in print("Profile loaded") } // This request will NOT be logged (filtered out) AF.request("https://api.example.com/auth/login") .responseJSON { response in print("Login attempted") } // Example 2: Filter multiple endpoints with complex predicate let complexFilter = NSPredicate(format: "URL.path CONTAINS[c] '/health' OR URL.path CONTAINS[c] '/metrics'") NetworkActivityLogger.shared.filterPredicate = complexFilter AF.request("https://api.example.com/health") .responseJSON { _ in } // Not logged AF.request("https://api.example.com/metrics") .responseJSON { _ in } // Not logged AF.request("https://api.example.com/data") .responseJSON { _ in } // Logged normally // Example 3: Filter by HTTP method let postFilter = NSPredicate(format: "httpMethod == 'POST'") NetworkActivityLogger.shared.filterPredicate = postFilter // GET requests will be logged AF.request("https://api.example.com/items", method: .get) .responseJSON { _ in } // POST requests will NOT be logged AF.request("https://api.example.com/items", method: .post) .responseJSON { _ in } // Example 4: Clear filter to log everything NetworkActivityLogger.shared.filterPredicate = nil ``` -------------------------------- ### User-Controlled Alamofire Logging (Swift) Source: https://context7.com/konkab/alamofirenetworkactivitylogger/llms.txt Allow users to toggle Alamofire network logging on or off through application settings, typically using UserDefaults. This provides flexibility for users to control the verbosity of network activity logs. ```swift // Example 3: User-controlled logging with settings class SettingsManager { static var isNetworkLoggingEnabled: Bool { get { UserDefaults.standard.bool(forKey: "networkLoggingEnabled") } set { UserDefaults.standard.set(newValue, forKey: "networkLoggingEnabled") updateNetworkLogging() } } static func updateNetworkLogging() { if isNetworkLoggingEnabled { NetworkActivityLogger.shared.level = .debug NetworkActivityLogger.shared.startLogging() } else { NetworkActivityLogger.shared.stopLogging() } } } // In settings UI func toggleNetworkLogging(_ enabled: Bool) { SettingsManager.isNetworkLoggingEnabled = enabled } ``` -------------------------------- ### Configure Network Activity Logger Level in Swift Source: https://github.com/konkab/alamofirenetworkactivitylogger/blob/master/README.md This Swift code snippet demonstrates how to change the logging level of the NetworkActivityLogger. By setting `NetworkActivityLogger.shared.level` to `.error`, only failed requests will be logged, reducing verbosity. ```swift NetworkActivityLogger.shared.level = .error ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.