Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improvements to logging #457

Merged
merged 5 commits into from
Jan 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
262 changes: 149 additions & 113 deletions ElementX.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions ElementX/Sources/Application/AppCoordinator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class AppCoordinator: AppCoordinatorProtocol {
private var backgroundTask: BackgroundTaskProtocol?
private var isSuspended = false {
didSet {
MXLog.debug("didSet to: \(isSuspended)")
MXLog.info("didSet to: \(isSuspended)")
}
}

Expand Down Expand Up @@ -320,7 +320,7 @@ class AppCoordinator: AppCoordinatorProtocol {
}
.store(in: &cancellables)
} else {
MXLog.debug("Couldn't register to AppDelegate callbacks")
MXLog.error("Couldn't register to AppDelegate callbacks")
}
}
}
Expand Down Expand Up @@ -457,7 +457,7 @@ extension AppCoordinator: NotificationManagerDelegate {
}

func notificationTapped(_ service: NotificationManagerProtocol, content: UNNotificationContent) async {
MXLog.debug("[AppCoordinator] tappedNotification")
MXLog.info("[AppCoordinator] tappedNotification")

guard let roomId = content.userInfo[NotificationConstants.UserInfoKey.roomIdentifier] as? String else {
return
Expand All @@ -467,7 +467,7 @@ extension AppCoordinator: NotificationManagerDelegate {
}

func handleInlineReply(_ service: NotificationManagerProtocol, content: UNNotificationContent, replyText: String) async {
MXLog.debug("[AppCoordinator] handle notification reply")
MXLog.info("[AppCoordinator] handle notification reply")

guard let roomId = content.userInfo[NotificationConstants.UserInfoKey.roomIdentifier] as? String else {
return
Expand Down
63 changes: 11 additions & 52 deletions ElementX/Sources/Other/Logging/MXLog.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,25 @@ import Foundation
import SwiftyBeaver

/// Various MXLog configuration options. Used in conjunction with `MXLog.configure()`
@objc public class MXLogConfiguration: NSObject {
public class MXLogConfiguration: NSObject {
/// the desired log level. `.verbose` by default.
@objc public var logLevel = MXLogLevel.verbose
public var logLevel = MXLogLevel.verbose

/// whether logs should be written directly to files. `false` by default.
@objc public var redirectLogsToFiles = false
public var redirectLogsToFiles = false

/// the maximum total space to use for log files in bytes. `100MB` by default.
@objc public var logFilesSizeLimit: UInt = 100 * 1024 * 1024 // 100MB
public var logFilesSizeLimit: UInt = 100 * 1024 * 1024 // 100MB

/// the maximum number of log files to use before rolling. `50` by default.
@objc public var maxLogFilesCount: UInt = 50
public var maxLogFilesCount: UInt = 50

/// the subname for log files. Files will be named as 'console-[subLogName].log'. `nil` by default
@objc public var subLogName: String?
public var subLogName: String?
}

/// MXLog logging levels. Use .none to disable logging entirely.
@objc public enum MXLogLevel: UInt {
public enum MXLogLevel: UInt {
case none
case verbose
case debug
Expand All @@ -56,13 +56,13 @@ private var logger: SwiftyBeaver.Type = {
Its purpose is to provide a common entry for customizing logging and should be used throughout the code.
Please see `MXLog.h` for Objective-C options.
*/
@objc public class MXLog: NSObject {
public class MXLog: NSObject {
/// Method used to customize MXLog's behavior.
/// Called automatically when first accessing the logger with the default values.
/// Please see `MXLogConfiguration` for all available options.
/// - Parameters:
/// - configuration: the `MXLogConfiguration` instance to use
@objc public static func configure(_ configuration: MXLogConfiguration) {
public static func configure(_ configuration: MXLogConfiguration) {
configureLogger(logger, withConfiguration: configuration)
}

Expand All @@ -74,11 +74,6 @@ private var logger: SwiftyBeaver.Type = {
logger.verbose(message(), file, function, line: line, context: context)
}

@available(swift, obsoleted: 5.4)
@objc public static func logVerbose(_ message: String, file: String, function: String, line: Int) {
logger.verbose(message, file, function, line: line)
}

public static func debug(_ message: @autoclosure () -> Any,
file: String = #file,
function: String = #function,
Expand All @@ -87,11 +82,6 @@ private var logger: SwiftyBeaver.Type = {
logger.debug(message(), file, function, line: line, context: context)
}

@available(swift, obsoleted: 5.4)
@objc public static func logDebug(_ message: String, file: String, function: String, line: Int) {
logger.debug(message, file, function, line: line)
}

public static func info(_ message: @autoclosure () -> Any,
file: String = #file,
function: String = #function,
Expand All @@ -100,11 +90,6 @@ private var logger: SwiftyBeaver.Type = {
logger.info(message(), file, function, line: line, context: context)
}

@available(swift, obsoleted: 5.4)
@objc public static func logInfo(_ message: String, file: String, function: String, line: Int) {
logger.info(message, file, function, line: line)
}

public static func warning(_ message: @autoclosure () -> Any,
file: String = #file,
function: String = #function,
Expand All @@ -113,31 +98,17 @@ private var logger: SwiftyBeaver.Type = {
logger.warning(message(), file, function, line: line, context: context)
}

@available(swift, obsoleted: 5.4)
@objc public static func logWarning(_ message: String, file: String, function: String, line: Int) {
logger.warning(message, file, function, line: line)
}

/// Log error with additional details
///
/// - Parameters:
/// - message: Description of the error without any variables (this is to improve error aggregations by type)
/// - context: Additional context-dependent details about the issue
public static func error(_ message: String,
public static func error(_ message: @autoclosure () -> Any,
file: String = #file,
function: String = #function,
line: Int = #line,
context: Any? = nil) {
logger.error(message, file, function, line: line, context: context)
}

@available(swift, obsoleted: 5.4)
@objc public static func logError(_ message: String,
file: String,
function: String,
line: Int,
context: Any? = nil) {
logger.error(message, file, function, line: line, context: context)
logger.error(message(), file, function, line: line, context: context)
}

/// Log failure with additional details
Expand All @@ -159,18 +130,6 @@ private var logger: SwiftyBeaver.Type = {
#endif
}

@available(swift, obsoleted: 5.4)
@objc public static func logFailure(_ message: String,
file: String,
function: String,
line: Int,
context: Any? = nil) {
logger.error(message, file, function, line: line, context: context)
#if DEBUG
assertionFailure("\(message)")
#endif
}

// MARK: - Private

fileprivate static func configureLogger(_ logger: SwiftyBeaver.Type, withConfiguration configuration: MXLogConfiguration) {
Expand Down
12 changes: 6 additions & 6 deletions ElementX/Sources/Other/Logging/MXLogger.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,10 @@ class MXLogger {
let nsLogURL = logURL(for: "console\(subLogName).log")
freopen((nsLogURL as NSURL).fileSystemRepresentation, "w+", stderr)

MXLog.debug("redirectNSLogToFiles: true")
MXLog.info("redirectNSLogToFiles: true")
if !tempLog.isEmpty {
// We can now log into files
MXLog.debug(tempLog)
MXLog.info(tempLog)
}

removeExtraFiles(from: numberOfFiles)
Expand Down Expand Up @@ -138,7 +138,7 @@ class MXLogger {
}
}

MXLog.debug("logFiles: \(logFiles)")
MXLog.info("logFiles: \(logFiles)")

return logFiles
}
Expand Down Expand Up @@ -282,7 +282,7 @@ class MXLogger {

if fileManager.fileExists(atPath: logFile.path()) {
try? fileManager.removeItem(at: logFile)
MXLog.debug("removeExtraFilesFromCount: \(count). removeItemAt: \(logFile)\n")
MXLog.info("removeExtraFilesFromCount: \(count). removeItemAt: \(logFile)\n")
} else {
break
}
Expand Down Expand Up @@ -318,10 +318,10 @@ class MXLogger {
let sizeLimitString = sizeLimit.formatted(.byteCount(style: .binary))

if let indexExceedingSizeLimit {
MXLog.debug("removeFilesAfterSizeLimit: Remove files from index \(indexExceedingSizeLimit) because logs are too large (\(logSizeString) for a limit of \(sizeLimitString)\n")
MXLog.info("removeFilesAfterSizeLimit: Remove files from index \(indexExceedingSizeLimit) because logs are too large (\(logSizeString) for a limit of \(sizeLimitString)\n")
removeExtraFiles(from: UInt(indexExceedingSizeLimit))
} else {
MXLog.debug("removeFilesAfterSizeLimit: No need: \(logSizeString) for a limit of \(sizeLimitString)\n")
MXLog.info("removeFilesAfterSizeLimit: No need: \(logSizeString) for a limit of \(sizeLimitString)\n")
}
}
}
7 changes: 2 additions & 5 deletions ElementX/Sources/Other/Logging/RustTracing.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,11 @@ struct TracingConfiguration {
])

enum Target: String {
case hyper, sled, matrix_sdk_sled, matrix_sdk_ffi
case hyper, sled, matrix_sdk_sled, matrix_sdk_ffi, matrix_sdk_crypto
case matrix_sdk_http_client = "matrix_sdk::http_client"
case matrix_sdk_ffi_uniffi_api = "matrix_sdk_ffi::uniffi_api"
case matrix_sdk_sliding_sync = "matrix_sdk::sliding_sync"
case matrix_sdk_base_sliding_sync = "matrix_sdk_base::sliding_sync"
case matrix_sdk_crypto
case matrix_sdk_crypto_sync = "matrix_sdk_crypto::machine[receive_sync_changes]"
}

enum LogLevel: String { case error, warn, info, debug, trace }
Expand All @@ -52,8 +50,7 @@ struct TracingConfiguration {
.hyper: .warn,
.sled: .warn,
.matrix_sdk_sled: .warn,
.matrix_sdk_crypto: .debug,
.matrix_sdk_crypto_sync: .trace
.matrix_sdk_crypto: .debug
]

var filter: String {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,15 @@ final class AnalyticsPromptCoordinator: CoordinatorProtocol {

func start() {
viewModel.callback = { [weak self] result in
MXLog.debug("AnalyticsPromptViewModel did complete with result: \(result).")

guard let self else { return }

switch result {
case .enable:
MXLog.info("Enable Analytics")
Analytics.shared.optIn(with: self.parameters.userSession)
self.callback?()
case .disable:
MXLog.info("Disable Analytics")
Analytics.shared.optOut()
self.callback?()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ final class LoginCoordinator: CoordinatorProtocol {
func start() {
viewModel.callback = { [weak self] action in
guard let self else { return }
MXLog.debug("LoginViewModel did callback with result: \(action).")

switch action {
case .selectServer:
Expand Down Expand Up @@ -118,6 +117,8 @@ final class LoginCoordinator: CoordinatorProtocol {

/// Processes an error to either update the flow or display it to the user.
private func handleError(_ error: AuthenticationServiceError) {
MXLog.info("Error occurred: \(error)")

switch error {
case .invalidCredentials:
viewModel.displayError(.alert(ElementL10n.authInvalidLoginParam))
Expand Down Expand Up @@ -150,6 +151,7 @@ final class LoginCoordinator: CoordinatorProtocol {

/// Requests the authentication coordinator to log in using the specified credentials.
private func login(username: String, password: String) {
MXLog.info("Starting login with password.")
startLoading(isInteractionBlocking: true)

Task {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ final class ServerSelectionCoordinator: CoordinatorProtocol {
func start() {
viewModel.callback = { [weak self] action in
guard let self else { return }
MXLog.debug("ServerSelectionViewModel did callback with action: \(action).")

switch action {
case .confirm(let homeserverAddress):
Expand Down Expand Up @@ -87,9 +86,11 @@ final class ServerSelectionCoordinator: CoordinatorProtocol {
Task {
switch await authenticationService.configure(for: homeserverAddress) {
case .success:
MXLog.info("Selected homeserver: \(homeserverAddress)")
callback?(.updated)
stopLoading()
case .failure(let error):
MXLog.info("Invalid homeserver: \(homeserverAddress)")
stopLoading()
handleError(error)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ final class SoftLogoutCoordinator: CoordinatorProtocol {
func start() {
viewModel.callback = { [weak self] result in
guard let self else { return }
MXLog.debug("[SoftLogoutCoordinator] SoftLogoutViewModel did complete with result: \(result).")
MXLog.info("[SoftLogoutCoordinator] SoftLogoutViewModel did complete with result: \(result).")

switch result {
case .login(let password):
Expand Down Expand Up @@ -112,8 +112,6 @@ final class SoftLogoutCoordinator: CoordinatorProtocol {

/// Shows the forgot password screen.
@MainActor private func showForgotPasswordScreen() {
MXLog.debug("[SoftLogoutCoordinator] showForgotPasswordScreen")

viewModel.displayError(.alert("Not implemented."))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ final class BugReportCoordinator: CoordinatorProtocol {
func start() {
viewModel.callback = { [weak self] result in
guard let self else { return }
MXLog.debug("BugReportViewModel did complete with result: \(result).")
MXLog.info("BugReportViewModel did complete with result: \(result).")
switch result {
case .cancel:
self.completion?(.cancel)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ final class EmojiPickerScreenCoordinator: CoordinatorProtocol {
func start() {
viewModel.callback = { [weak self] action in
guard let self else { return }
MXLog.debug("EmojiPickerScreenViewModel did complete with result: \(action).")

switch action {
case let .emojiSelected(emoji: emoji):
self.callback?(.emojiSelected(emoji: emoji, itemId: self.parameters.itemId))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ final class FilePreviewCoordinator: CoordinatorProtocol {
func start() {
viewModel.callback = { [weak self] action in
guard let self else { return }
MXLog.debug("FilePreviewViewModel did complete with result: \(action).")

switch action {
case .cancel:
self.callback?(.cancel)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ final class OnboardingCoordinator: CoordinatorProtocol {

func start() {
viewModel.callback = { [weak self] action in
MXLog.debug("OnboardingViewModel did complete with result: \(action).")
guard let self else { return }

switch action {
case .login:
self.callback?(.login)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ final class RoomDetailsCoordinator: CoordinatorProtocol {
func start() {
viewModel.callback = { [weak self] action in
guard let self else { return }

switch action {
case .requestMemberDetailsPresentation(let members):
self.presentRoomMemberDetails(members)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ class RoomDetailsViewModel: RoomDetailsViewModelType, RoomDetailsViewModelProtoc
case .success(let members):
self.members = members
case .failure(let error):
MXLog.debug("Failed to retrieve room members: \(error)")
MXLog.error("Failed retrieving room members: \(error)")
state.bindings.alertInfo = AlertInfo(id: .alert(ElementL10n.unknownError))
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ final class RoomMemberDetailsCoordinator: CoordinatorProtocol {
func start() {
viewModel.callback = { [weak self] action in
guard let self else { return }
MXLog.debug("RoomMemberDetailsViewModel did complete with result: \(action).")

switch action {
case .cancel:
self.callback?(.cancel)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ class RoomMemberDetailsViewModel: RoomMemberDetailsViewModelType, RoomMemberDeta
state.members[index].avatar = image
}
case .failure(let error):
MXLog.debug("Failed to retrieve room member avatar: \(error)")
MXLog.error("Failed to retrieve room member avatar: \(error)")
}
}
}
Loading