Improvements to logging (#457)

* Use `.info` logging in most places.
* Remove old objc logging support.
* Fix table view controller.
* Make sure timeline item content isn't logged.
* Add tests.
This commit is contained in:
Doug
2023-01-17 09:28:01 +00:00
committed by GitHub
parent 4b56e4af73
commit c8937505d7
57 changed files with 542 additions and 275 deletions
@@ -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)")
}
}
@@ -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")
}
}
}
@@ -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
@@ -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
+11 -52
View File
@@ -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
@@ -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)
}
@@ -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,
@@ -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,
@@ -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,
@@ -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
@@ -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) {
@@ -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)
@@ -138,7 +138,7 @@ class MXLogger {
}
}
MXLog.debug("logFiles: \(logFiles)")
MXLog.info("logFiles: \(logFiles)")
return logFiles
}
@@ -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
}
@@ -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")
}
}
}
@@ -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 }
@@ -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 {
@@ -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?()
}
@@ -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:
@@ -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))
@@ -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 {
@@ -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):
@@ -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)
}
@@ -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):
@@ -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."))
}
@@ -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)
@@ -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))
@@ -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)
@@ -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)
@@ -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)
@@ -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))
}
}
@@ -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)
@@ -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)")
}
}
}
@@ -49,10 +49,10 @@ final class RoomScreenCoordinator: CoordinatorProtocol {
// MARK: - Public
func start() {
viewModel?.callback = { [weak self] result in
viewModel?.callback = { [weak self] action in
guard let self else { return }
MXLog.debug("RoomScreenViewModel did complete with result: \(result).")
switch result {
switch action {
case .displayRoomDetails:
self.displayRoomDetails()
case .displayVideo(let fileURL, let title), .displayFile(let fileURL, let title):
@@ -103,8 +103,8 @@ final class RoomScreenCoordinator: CoordinatorProtocol {
coordinator.callback = { [weak self] action in
switch action {
case let .emojiSelected(emoji: emoji, itemId: itemId):
MXLog.debug("Selected \(emoji) for \(itemId)")
self?.navigationStackCoordinator.setSheetCoordinator(nil)
MXLog.debug("Save \(emoji) for \(itemId)")
Task {
await timelineController.sendReaction(emoji, for: itemId)
}
@@ -242,8 +242,6 @@ class TimelineTableViewController: UIViewController {
updateTopPadding()
guard snapshot.numberOfItems != previousLayout.numberOfItems else { return }
if previousLayout.isBottomVisible {
scrollToBottom(animated: false)
} else if let pinnedItem = previousLayout.pinnedItem {
@@ -357,15 +355,19 @@ class TimelineTableViewController: UIViewController {
extension TimelineTableViewController: UITableViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let isAtBottom = isAtBottom()
// Only update the binding on changes to avoid needlessly recomputing the hierarchy when scrolling.
if scrollToBottomButtonVisible != isAtBottom {
// Dispatch to fix runtime warning about making changes during a view update.
DispatchQueue.main.async { self.scrollToBottomButtonVisible = isAtBottom }
}
paginateBackwardsPublisher.send(())
// Dispatch to fix runtime warning about making changes during a view update.
DispatchQueue.main.async { [weak self] in
guard let self else { return }
let isAtBottom = self.isAtBottom()
// Only update the binding on changes to avoid needlessly recomputing the hierarchy when scrolling.
if self.scrollToBottomButtonVisible != isAtBottom {
self.scrollToBottomButtonVisible = isAtBottom
}
}
}
// MARK: ScrollViewAdapter Methods
@@ -40,10 +40,10 @@ final class SettingsCoordinator: CoordinatorProtocol {
self.parameters = parameters
viewModel = SettingsViewModel(withUserSession: parameters.userSession)
viewModel.callback = { [weak self] result in
viewModel.callback = { [weak self] action in
guard let self else { return }
MXLog.debug("SettingsViewModel did complete with result: \(result).")
switch result {
switch action {
case .close:
self.callback?(.dismiss)
case .toggleAnalytics:
@@ -71,7 +71,7 @@ class Analytics {
client.stop()
// monitoringClient.stop()
MXLog.debug("Stopped.")
MXLog.info("Stopped.")
}
/// Starts the analytics client if the user has opted in, otherwise does nothing.
@@ -84,7 +84,7 @@ class Analytics {
// Sanity check in case something went wrong.
guard client.isRunning else { return }
MXLog.debug("Started.")
MXLog.info("Started.")
// Catch and log crashes
// MXLogger.logCrashes(true)
@@ -121,7 +121,7 @@ class Analytics {
client.reset()
// monitoringClient.reset()
MXLog.debug("Reset.")
MXLog.info("Reset.")
ServiceLocator.shared.settings.isIdentifiedForAnalytics = false
// Stop collecting crash logs
@@ -146,7 +146,7 @@ class Analytics {
}
client.identify(id: id)
MXLog.debug("Identified.")
MXLog.info("Identified.")
ServiceLocator.shared.settings.isIdentifiedForAnalytics = true
}
@@ -59,7 +59,7 @@ class AnalyticsService {
let newSettings = AnalyticsSettings.new(currentEvent: settings)
switch await userSession.clientProxy.setAccountData(content: newSettings, type: AnalyticsSettings.eventType) {
case .failure:
MXLog.warning("Failed to update analytics settings.")
MXLog.error("Failed to update analytics settings.")
return .failure(.accountDataFailure)
case .success:
MXLog.debug("Successfully updated analytics settings in account data.")
@@ -88,7 +88,7 @@ class AuthenticationServiceProxy: AuthenticationServiceProxyProtocol {
let client = try authenticationService.restoreWithAccessToken(token: token, deviceId: deviceID)
return await userSession(for: client)
} catch {
MXLog.debug(error)
MXLog.error(error)
return .failure(.failedLoggingIn)
}
}
@@ -58,7 +58,7 @@ class UIKitBackgroundTask: BackgroundTaskProtocol {
}
if identifier == .invalid {
MXLog.verbose("Do not start background task: \(name), as OS declined")
MXLog.info("Do not start background task: \(name), as OS declined")
// call expiration handler immediately
expirationHandler?(self)
return nil
@@ -69,7 +69,7 @@ class UIKitBackgroundTask: BackgroundTaskProtocol {
reuse()
}
MXLog.verbose("Start background task #\(identifier.rawValue) - \(name)")
MXLog.info("Start background task #\(identifier.rawValue) - \(name)")
}
func reuse() {
@@ -92,7 +92,7 @@ class UIKitBackgroundTask: BackgroundTaskProtocol {
private func endTask() {
if identifier != .invalid {
MXLog.verbose("End background task #\(identifier.rawValue) - \(name) after \(readableElapsedTime)")
MXLog.info("End background task #\(identifier.rawValue) - \(name) after \(readableElapsedTime)")
application.endBackgroundTask(identifier)
identifier = .invalid
@@ -36,12 +36,12 @@ class UIKitBackgroundTaskService: BackgroundTaskServiceProtocol {
isReusable: Bool,
expirationHandler: (() -> Void)?) -> BackgroundTaskProtocol? {
guard let application else {
MXLog.verbose("Do not start background task: \(name). Application is nil")
MXLog.error("Do not start background task: \(name). Application is nil")
return nil
}
if avoidStartingNewTasks(for: application) {
MXLog.verbose("Do not start background task: \(name), as not enough time exists")
MXLog.info("Do not start background task: \(name), as not enough time exists")
// call expiration handler immediately
expirationHandler?()
return nil
@@ -82,7 +82,7 @@ class UIKitBackgroundTaskService: BackgroundTaskServiceProtocol {
let appState = application.applicationState
let remainingTime = readableBackgroundTimeRemaining(application.backgroundTimeRemaining)
MXLog.verbose("Background task \(name) \(created ? "started" : "reused") with app state: \(appState) and estimated background time remaining: \(remainingTime)")
MXLog.info("Background task \(name) \(created ? "started" : "reused") with app state: \(appState) and estimated background time remaining: \(remainingTime)")
return result
}
@@ -53,7 +53,7 @@ class BugReportService: BugReportServiceProtocol {
}
options.onCrashedLastRun = { [weak self] event in
MXLog.debug("Sentry detected application was crashed: \(event)")
MXLog.error("Sentry detected application was crashed: \(event)")
self?.lastCrashEventId = event.eventId.sentryIdString
}
}
@@ -79,11 +79,7 @@ class BugReportService: BugReportServiceProtocol {
includeCrashLog: Bool,
githubLabels: [String],
files: [URL]) async throws -> SubmitBugReportResponse {
MXLog.debug("submitBugReport")
var params = [
MultipartFormData(key: "text", type: .text(value: text))
]
var params = [MultipartFormData(key: "text", type: .text(value: text))]
params.append(contentsOf: defaultParams)
for label in githubLabels {
params.append(MultipartFormData(key: "label", type: .text(value: label)))
@@ -140,6 +136,8 @@ class BugReportService: BugReportServiceProtocol {
lastCrashEventId = nil
}
MXLog.info("Feedback submitted.")
return result
}
@@ -176,7 +174,7 @@ class BugReportService: BugReportServiceProtocol {
private func zipFiles(includeLogs: Bool,
includeCrashLog: Bool) async throws -> [URL] {
MXLog.debug("zipFiles: includeLogs: \(includeLogs), includeCrashLog: \(includeCrashLog)")
MXLog.info("zipFiles: includeLogs: \(includeLogs), includeCrashLog: \(includeCrashLog)")
var filesToCompress: [URL] = []
if includeLogs {
@@ -213,7 +211,7 @@ class BugReportService: BugReportServiceProtocol {
zippedFiles.append(zippedFileURL)
}
MXLog.debug("zipFiles: totalSize: \(totalSize), totalZippedSize: \(totalZippedSize)")
MXLog.info("zipFiles: totalSize: \(totalSize), totalZippedSize: \(totalZippedSize)")
return zippedFiles
}
@@ -31,21 +31,21 @@ private class SlidingSyncViewObserver: SlidingSyncViewRoomListObserver, SlidingS
// MARK: - SlidingSyncViewRoomListObserver
func didReceiveUpdate(diff: SlidingSyncViewRoomsListDiff) {
MXLog.verbose("Received room diff")
MXLog.info("Received room diff")
roomListDiffPublisher.send(diff)
}
// MARK: - SlidingSyncViewStateObserver
func didReceiveUpdate(newState: SlidingSyncState) {
MXLog.verbose("Updated state: \(newState)")
MXLog.info("Updated state: \(newState)")
stateUpdatePublisher.send(newState)
}
// MARK: - SlidingSyncViewRoomsCountObserver
func didReceiveUpdate(count: UInt32) {
MXLog.verbose("Updated room count: \(count)")
MXLog.info("Updated room count: \(count)")
countUpdatePublisher.send(UInt(count))
}
}
@@ -49,12 +49,12 @@ class NotificationManager: NSObject, NotificationManagerProtocol {
Task {
do {
let granted = try await notificationCenter.requestAuthorization(options: [.alert, .sound, .badge])
MXLog.debug("[NotificationManager] permission granted: \(granted)")
MXLog.info("[NotificationManager] permission granted: \(granted)")
await MainActor.run {
self.delegate?.authorizationStatusUpdated(self, granted: granted)
}
} catch {
MXLog.debug("[NotificationManager] request authorization failed: \(error)")
MXLog.error("[NotificationManager] request authorization failed: \(error)")
}
}
}
@@ -76,9 +76,9 @@ class NotificationManager: NSObject, NotificationManagerProtocol {
trigger: nil)
do {
try await notificationCenter.add(request)
MXLog.debug("[NotificationManager] show local notification succeeded")
MXLog.info("[NotificationManager] show local notification succeeded")
} catch {
MXLog.debug("[NotificationManager] show local notification failed: \(error)")
MXLog.error("[NotificationManager] show local notification failed: \(error)")
}
}
@@ -102,10 +102,10 @@ class NotificationManager: NSObject, NotificationManagerProtocol {
]
]
])
MXLog.debug("[NotificationManager] set pusher succeeded")
MXLog.info("[NotificationManager] set pusher succeeded")
return true
} catch {
MXLog.debug("[NotificationManager] set pusher failed: \(error)")
MXLog.error("[NotificationManager] set pusher failed: \(error)")
return false
}
}
@@ -83,7 +83,7 @@ class RoomSummaryProvider: RoomSummaryProviderProtocol {
MXLog.verbose("Updating \(identifiers.count) rooms")
guard statePublisher.value == .live else {
MXLog.verbose("Sliding sync not live yet, ignoring.")
MXLog.warning("Sliding sync not live yet, ignoring update.")
return
}
@@ -53,7 +53,8 @@ class RoomTimelineProvider: RoomTimelineProviderProtocol {
switch await roomProxy.addTimelineListener(listener: roomTimelineListener) {
case .failure:
MXLog.error("Failed adding timeline listener on room with identifier: \(await roomProxy.id)")
let roomID = await roomProxy.id
MXLog.error("Failed adding timeline listener on room with identifier: \(roomID)")
default:
break
}
@@ -146,6 +146,7 @@ class RoomTimelineController: RoomTimelineControllerProtocol {
}
func sendMessage(_ message: String) async {
MXLog.info("Send message in \(roomId)")
switch await timelineProvider.sendMessage(message) {
default:
break
@@ -153,6 +154,7 @@ class RoomTimelineController: RoomTimelineControllerProtocol {
}
func sendReply(_ message: String, to itemId: String) async {
MXLog.info("Send reply in \(roomId)")
switch await timelineProvider.sendMessage(message, inReplyToItemId: itemId) {
default:
break
@@ -160,6 +162,7 @@ class RoomTimelineController: RoomTimelineControllerProtocol {
}
func sendReaction(_ reaction: String, for itemId: String) async {
MXLog.info("Send reaction in \(roomId)")
switch await timelineProvider.sendReaction(reaction, for: itemId) {
default:
break
@@ -167,6 +170,7 @@ class RoomTimelineController: RoomTimelineControllerProtocol {
}
func editMessage(_ newMessage: String, of itemId: String) async {
MXLog.info("Edit message in \(roomId)")
switch await timelineProvider.editMessage(newMessage, originalItemId: itemId) {
default:
break
@@ -174,6 +178,7 @@ class RoomTimelineController: RoomTimelineControllerProtocol {
}
func redact(_ eventID: String) async {
MXLog.info("Send redaction in \(roomId)")
switch await timelineProvider.redact(eventID) {
default:
break
@@ -0,0 +1,55 @@
//
// Copyright 2023 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import MatrixRustSDK
// MARK: Redact message content from logs
extension EmoteMessageContent: CustomStringConvertible {
public var description: String {
String(describing: Self.self)
}
}
extension FileMessageContent: CustomStringConvertible {
public var description: String {
String(describing: Self.self)
}
}
extension ImageMessageContent: CustomStringConvertible {
public var description: String {
String(describing: Self.self)
}
}
extension NoticeMessageContent: CustomStringConvertible {
public var description: String {
String(describing: Self.self)
}
}
extension TextMessageContent: CustomStringConvertible {
public var description: String {
String(describing: Self.self)
}
}
extension VideoMessageContent: CustomStringConvertible {
public var description: String {
String(describing: Self.self)
}
}
@@ -19,7 +19,8 @@ import Foundation
import MatrixRustSDK
/// A protocol that contains the base `m.room.message` event content properties.
protocol MessageContentProtocol: RoomMessageEventContentProtocol {
/// The `CustomStringConvertible` conformance is to redact specific properties from the logs.
protocol MessageContentProtocol: RoomMessageEventContentProtocol, CustomStringConvertible {
var body: String { get }
}
@@ -14,7 +14,6 @@
// limitations under the License.
//
import Foundation
import UIKit
struct EmoteRoomTimelineItem: EventBasedTimelineItemProtocol, Identifiable, Hashable {
@@ -32,3 +31,11 @@ struct EmoteRoomTimelineItem: EventBasedTimelineItemProtocol, Identifiable, Hash
var properties = RoomTimelineItemProperties()
}
// MARK: - Redact content from logs
extension EmoteRoomTimelineItem: CustomStringConvertible {
var description: String {
"\(String(describing: Self.self)): id: \(id), timestamp: \(timestamp), isOutgoing: \(isOutgoing), properties: \(properties)"
}
}
@@ -14,7 +14,6 @@
// limitations under the License.
//
import Foundation
import UIKit
struct FileRoomTimelineItem: EventBasedTimelineItemProtocol, Identifiable, Hashable {
@@ -35,3 +34,11 @@ struct FileRoomTimelineItem: EventBasedTimelineItemProtocol, Identifiable, Hasha
var properties = RoomTimelineItemProperties()
}
// MARK: - Redact content from logs
extension FileRoomTimelineItem: CustomStringConvertible {
var description: String {
"\(String(describing: Self.self)): id: \(id), timestamp: \(timestamp), isOutgoing: \(isOutgoing), properties: \(properties)"
}
}
@@ -14,7 +14,6 @@
// limitations under the License.
//
import Foundation
import UIKit
struct ImageRoomTimelineItem: EventBasedTimelineItemProtocol, Identifiable, Hashable {
@@ -40,3 +39,11 @@ struct ImageRoomTimelineItem: EventBasedTimelineItemProtocol, Identifiable, Hash
var properties = RoomTimelineItemProperties()
}
// MARK: - Redact content from logs
extension ImageRoomTimelineItem: CustomStringConvertible {
var description: String {
"\(String(describing: Self.self)): id: \(id), timestamp: \(timestamp), isOutgoing: \(isOutgoing), properties: \(properties)"
}
}
@@ -14,7 +14,6 @@
// limitations under the License.
//
import Foundation
import UIKit
struct NoticeRoomTimelineItem: EventBasedTimelineItemProtocol, Identifiable, Hashable {
@@ -32,3 +31,11 @@ struct NoticeRoomTimelineItem: EventBasedTimelineItemProtocol, Identifiable, Has
var properties = RoomTimelineItemProperties()
}
// MARK: - Redact content from logs
extension NoticeRoomTimelineItem: CustomStringConvertible {
var description: String {
"\(String(describing: Self.self)): id: \(id), timestamp: \(timestamp), isOutgoing: \(isOutgoing), properties: \(properties)"
}
}
@@ -14,7 +14,6 @@
// limitations under the License.
//
import Foundation
import UIKit
struct TextRoomTimelineItem: EventBasedTimelineItemProtocol, Identifiable, Hashable {
@@ -32,3 +31,11 @@ struct TextRoomTimelineItem: EventBasedTimelineItemProtocol, Identifiable, Hasha
var properties = RoomTimelineItemProperties()
}
// MARK: - Redact content from logs
extension TextRoomTimelineItem: CustomStringConvertible {
var description: String {
"\(String(describing: Self.self)): id: \(id), timestamp: \(timestamp), isOutgoing: \(isOutgoing), properties: \(properties)"
}
}
@@ -14,7 +14,6 @@
// limitations under the License.
//
import Foundation
import UIKit
struct VideoRoomTimelineItem: EventBasedTimelineItemProtocol, Identifiable, Hashable {
@@ -42,3 +41,11 @@ struct VideoRoomTimelineItem: EventBasedTimelineItemProtocol, Identifiable, Hash
var properties = RoomTimelineItemProperties()
}
// MARK: - Redact content from logs
extension VideoRoomTimelineItem: CustomStringConvertible {
var description: String {
"\(String(describing: Self.self)): id: \(id), timestamp: \(timestamp), isOutgoing: \(isOutgoing), properties: \(properties)"
}
}
@@ -33,7 +33,7 @@ class UserSessionStore: UserSessionStoreProtocol {
accessGroup: InfoPlistReader.target.keychainAccessGroupIdentifier)
self.backgroundTaskService = backgroundTaskService
baseDirectory = .sessionsBaseDirectory
MXLog.debug("Setup base directory at: \(baseDirectory)")
MXLog.info("Setup base directory at: \(baseDirectory)")
}
/// Deletes all data stored in the shared container and keychain