Various logging fixes (#164)

Various logging fixes:
* imported the ObjCWrapper and updated the MXLogger. Also added back support for app containers
* updated MXLog.swift from El and fixed/improved its logging format
* updated most app log strings
* Remove unnecessary swiftlint rule
* Various tweaks following code review
* Added back type annoation on MXLogger logFiles method
* Fix generated Swift-ObjC header name
This commit is contained in:
Stefan Ceriu
2022-08-30 18:05:21 +03:00
committed by GitHub
parent c92e6c2092
commit 39be67cec6
24 changed files with 288 additions and 102 deletions
+2 -2
View File
@@ -327,7 +327,7 @@ class AppCoordinator: AuthenticationCoordinatorDelegate, Coordinator {
}
private func processScreenshotDetection(image: UIImage?, error: Error?) {
MXLog.debug("[AppCoordinator] processScreenshotDetection: \(String(describing: image)), error: \(String(describing: error))")
MXLog.debug("Detected screenshot: \(String(describing: image)), error: \(String(describing: error))")
let alert = UIAlertController(title: ElementL10n.screenshotDetectedTitle,
message: ElementL10n.screenshotDetectedMessage,
@@ -363,7 +363,7 @@ class AppCoordinator: AuthenticationCoordinatorDelegate, Coordinator {
@objc
private func dismissBugReportScreen() {
MXLog.debug("[AppCoorrdinator] dismissBugReportScreen")
MXLog.debug("dismissBugReportScreen")
guard let bugReportCoordinator = childCoordinators.first(where: { $0 is BugReportCoordinator }) else {
return
@@ -20,9 +20,7 @@ import Foundation
public extension DTHTMLElement {
/// Sanitize the element using the given parameters.
/// - Parameters:
/// - allowedHTMLTags: An array of tags that are allowed. All other tags will be removed.
/// - font: The default font to use when resetting the content of any unsupported tags.
/// - imageHandler: An optional image handler to be run on `img` tags (if allowed) to update the `src` attribute.
@objc func sanitize(font: UIFont) {
if let name = name, !Self.allowedHTMLTags.contains(name) {
// This is an unsupported tag.
+49
View File
@@ -0,0 +1,49 @@
//
// Copyright 2021 The Matrix.org Foundation C.I.C
//
// 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 "MXLogObjcWrapper.h"
#define MXLogVerbose(message, ...) { \
[MXLogObjcWrapper logVerbose:[NSString stringWithFormat: message, ##__VA_ARGS__] file:@__FILE__ function:[NSString stringWithFormat:@"%s", __FUNCTION__] line:__LINE__]; \
}
#define MXLogDebug(message, ...) { \
[MXLogObjcWrapper logDebug:[NSString stringWithFormat: message, ##__VA_ARGS__] file:@__FILE__ function:[NSString stringWithFormat:@"%s", __FUNCTION__] line:__LINE__]; \
}
#define MXLogInfo(message, ...) { \
[MXLogObjcWrapper logInfo:[NSString stringWithFormat: message, ##__VA_ARGS__] file:@__FILE__ function:[NSString stringWithFormat:@"%s", __FUNCTION__] line:__LINE__]; \
}
#define MXLogWarning(message, ...) { \
[MXLogObjcWrapper logWarning:[NSString stringWithFormat: message, ##__VA_ARGS__] file:@__FILE__ function:[NSString stringWithFormat:@"%s", __FUNCTION__] line:__LINE__]; \
}
#define MXLogError(message) { \
[MXLogObjcWrapper logError:message file:@__FILE__ function:[NSString stringWithFormat:@"%s", __FUNCTION__] line:__LINE__ context:nil]; \
}
#define MXLogErrorDetails(message, details) { \
[MXLogObjcWrapper logError:message file:@__FILE__ function:[NSString stringWithFormat:@"%s", __FUNCTION__] line:__LINE__ context:details]; \
}
#define MXLogFailure(message) { \
[MXLogObjcWrapper logFailure:message file:@__FILE__ function:[NSString stringWithFormat:@"%s", __FUNCTION__] line:__LINE__ context:nil]; \
}
#define MXLogFailureDetails(message, details) { \
[MXLogObjcWrapper logFailure:message file:@__FILE__ function:[NSString stringWithFormat:@"%s", __FUNCTION__] line:__LINE__ context:details]; \
}
+55 -29
View File
@@ -67,8 +67,8 @@ private var logger: SwiftyBeaver.Type = {
}
public static func verbose(_ message: @autoclosure () -> Any,
_ file: String = #file,
_ function: String = #function,
file: String = #file,
function: String = #function,
line: Int = #line,
context: Any? = nil) {
logger.verbose(message(), file, function, line: line, context: context)
@@ -80,8 +80,8 @@ private var logger: SwiftyBeaver.Type = {
}
public static func debug(_ message: @autoclosure () -> Any,
_ file: String = #file,
_ function: String = #function,
file: String = #file,
function: String = #function,
line: Int = #line,
context: Any? = nil) {
logger.debug(message(), file, function, line: line, context: context)
@@ -93,8 +93,8 @@ private var logger: SwiftyBeaver.Type = {
}
public static func info(_ message: @autoclosure () -> Any,
_ file: String = #file,
_ function: String = #function,
file: String = #file,
function: String = #function,
line: Int = #line,
context: Any? = nil) {
logger.info(message(), file, function, line: line, context: context)
@@ -106,8 +106,8 @@ private var logger: SwiftyBeaver.Type = {
}
public static func warning(_ message: @autoclosure () -> Any,
_ file: String = #file,
_ function: String = #function,
file: String = #file,
function: String = #function,
line: Int = #line,
context: Any? = nil) {
logger.warning(message(), file, function, line: line, context: context)
@@ -118,32 +118,57 @@ private var logger: SwiftyBeaver.Type = {
logger.warning(message, file, function, line: line)
}
public static func error(_ message: @autoclosure () -> Any,
_ file: String = #file,
_ function: String = #function,
/// 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,
file: String = #file,
function: String = #function,
line: Int = #line,
context: Any? = nil) {
logger.error(message(), file, function, line: line, context: context)
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) {
logger.error(message, file, function, line: line)
@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)
}
public static func failure(_ message: @autoclosure () -> Any,
_ file: String = #file,
_ function: String = #function,
/// Log failure with additional details
///
/// A failure is any type of programming error which should never occur in production. In `DEBUG` configuration
/// any failure will raise `assertionFailure`
///
/// - 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 failure(_ message: String,
file: String = #file,
function: String = #function,
line: Int = #line,
context: Any? = nil) {
logger.error(message(), file, function, line: line, context: context)
assertionFailure("\(message())")
logger.error(message, file, function, line: line, context: context)
#if DEBUG
assertionFailure("\(message)")
#endif
}
@available(swift, obsoleted: 5.4)
@objc public static func logFailure(_ message: String, file: String, function: String, line: Int) {
logger.error(message, file, function, line: line)
assertionFailure(message)
@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
@@ -152,24 +177,27 @@ private var logger: SwiftyBeaver.Type = {
if let subLogName = configuration.subLogName {
MXLogger.setSubLogName(subLogName)
}
MXLogger.redirectNSLog(toFiles: configuration.redirectLogsToFiles,
numberOfFiles: configuration.maxLogFilesCount,
sizeLimit: configuration.logFilesSizeLimit)
guard configuration.logLevel != .none else {
logger.removeAllDestinations()
return
}
logger.removeAllDestinations()
let consoleDestination = ConsoleDestination()
consoleDestination.useNSLog = true
consoleDestination.asynchronously = false
consoleDestination.format = "$M"
consoleDestination.format = "$C$N.$F:$l $M $X$c" // See https://docs.swiftybeaver.com/article/20-custom-format
consoleDestination.levelColor.verbose = ""
consoleDestination.levelColor.debug = ""
consoleDestination.levelColor.info = ""
consoleDestination.levelColor.warning = "⚠️"
consoleDestination.levelColor.error = "🚨"
consoleDestination.levelColor.warning = "⚠️ "
consoleDestination.levelColor.error = "🚨 "
switch configuration.logLevel {
case .verbose:
@@ -185,8 +213,6 @@ private var logger: SwiftyBeaver.Type = {
case .none:
break
}
logger.removeAllDestinations()
logger.addDestination(consoleDestination)
}
}
@@ -0,0 +1,40 @@
//
// Copyright 2021 The Matrix.org Foundation C.I.C
//
// 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 <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
An `MXLog` Objective-C wrapper used to allow calling Swift methods from the variadic macros defined in `MXLog.h`
*/
@interface MXLogObjcWrapper : NSObject
+ (void)logVerbose:(NSString *)message file:(NSString *)file function:(NSString *)function line:(NSUInteger)line;
+ (void)logDebug:(NSString *)message file:(NSString *)file function:(NSString *)function line:(NSUInteger)line;
+ (void)logInfo:(NSString *)message file:(NSString *)file function:(NSString *)function line:(NSUInteger)line;
+ (void)logWarning:(NSString *)message file:(NSString *)file function:(NSString *)function line:(NSUInteger)line;
+ (void)logError:(NSString *)message file:(NSString *)file function:(NSString *)function line:(NSUInteger)line context:(nullable id)context;
+ (void)logFailure:(NSString *)message file:(NSString *)file function:(NSString *)function line:(NSUInteger)line context:(nullable id)context;
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,52 @@
//
// Copyright 2021 The Matrix.org Foundation C.I.C
//
// 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 "MXLogObjcWrapper.h"
#import "GeneratedInterface-Swift.h"
@implementation MXLogObjcWrapper
+ (void)logVerbose:(NSString *)message file:(NSString *)file function:(NSString *)function line:(NSUInteger)line
{
[MXLog logVerbose:message file:file function:function line:line];
}
+ (void)logDebug:(NSString *)message file:(NSString *)file function:(NSString *)function line:(NSUInteger)line
{
[MXLog logDebug:message file:file function:function line:line];
}
+ (void)logInfo:(NSString *)message file:(NSString *)file function:(NSString *)function line:(NSUInteger)line
{
[MXLog logInfo:message file:file function:function line:line];
}
+ (void)logWarning:(NSString *)message file:(NSString *)file function:(NSString *)function line:(NSUInteger)line
{
[MXLog logWarning:message file:file function:function line:line];
}
+ (void)logError:(NSString *)message file:(NSString *)file function:(NSString *)function line:(NSUInteger)line context:(id)context
{
[MXLog logError:message file:file function:function line:line context:context];
}
+ (void)logFailure:(NSString *)message file:(NSString *)file function:(NSString *)function line:(NSUInteger)line context:(id)context
{
[MXLog logFailure:message file:file function:function line:line context:context];
}
@end
+29 -29
View File
@@ -16,7 +16,8 @@
*/
#import "MXLogger.h"
#import <UIKit/UIKit.h>
#import "MXLog.h"
#import "GeneratedInterface-Swift.h"
// stderr so it can be restored
int stderrSave = 0;
@@ -80,24 +81,24 @@ static NSString *subLogName;
if ([fileManager fileExistsAtPath:nsLogPathOlder])
{
// Temp log
[log appendFormat:@"[MXLogger] redirectNSLogToFiles: removeItemAtPath: %@\n", nsLogPathOlder];
[log appendFormat:@"removeItemAtPath: %@\n", nsLogPathOlder];
NSError *error;
[fileManager removeItemAtPath:nsLogPathOlder error:&error];
if (error)
{
[log appendFormat:@"[MXLogger] ERROR: removeItemAtPath: %@. Error: %@\n", nsLogPathOlder, error];
[log appendFormat:@"removeItemAtPath: %@. Error: %@\n", nsLogPathOlder, error];
}
}
// Temp log
[log appendFormat:@"[MXLogger] redirectNSLogToFiles: moveItemAtPath: %@ toPath: %@\n", nsLogPathCurrent, nsLogPathOlder];
[log appendFormat:@"moveItemAtPath: %@ toPath: %@\n", nsLogPathCurrent, nsLogPathOlder];
NSError *error;
[fileManager moveItemAtPath:nsLogPathCurrent toPath:nsLogPathOlder error:&error];
if (error)
{
[log appendFormat:@"[MXLogger] ERROR: moveItemAtPath: %@ toPath: %@. Error: %@\n", nsLogPathCurrent, nsLogPathOlder, error];
[log appendFormat:@"moveItemAtPath: %@ toPath: %@. Error: %@\n", nsLogPathCurrent, nsLogPathOlder, error];
}
}
}
@@ -108,11 +109,11 @@ static NSString *subLogName;
NSString *nsLogPath = [logsFolderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"console%@.log", subLogName]];
freopen([nsLogPath fileSystemRepresentation], "w+", stderr);
// MXLogDebug(@"[MXLogger] redirectNSLogToFiles: YES");
MXLogDebug(@"redirectNSLogToFiles: YES");
if (log.length)
{
// We can now log into files
// MXLogDebug(@"%@", log);
MXLogDebug(@"%@", log);
}
[self removeExtraFilesFromCount:numberOfFiles];
@@ -162,7 +163,7 @@ static NSString *subLogName;
}
}
// MXLogDebug(@"[MXLogger] logFiles: %@", logFiles);
MXLogDebug(@"logFiles: %@", logFiles);
return logFiles;
}
@@ -200,13 +201,12 @@ static void handleUncaughtException(NSException *exception)
NSString *version = [[NSProcessInfo processInfo] operatingSystemVersionString];
#endif
NSArray *backtrace = [exception callStackSymbols];
NSString *description = [NSString stringWithFormat:@"%.0f - %@\n%@\nApplication: %@ (%@)\nApplication version: %@\nMatrix SDK version: %@\nBuild: %@\n%@ %@\n\nMain thread: %@\n%@\n",
NSString *description = [NSString stringWithFormat:@"%.0f - %@\n%@\nApplication: %@ (%@)\nApplication version: %@\nBuild: %@\n%@ %@\n\nMain thread: %@\n%@\n",
[[NSDate date] timeIntervalSince1970],
[NSDate date],
exception.description,
app, appId,
appVersion,
@"",
buildVersion,
model, version,
[NSThread isMainThread] ? @"YES" : @"NO",
@@ -220,8 +220,9 @@ static void handleUncaughtException(NSException *exception)
encoding:NSStringEncodingConversionAllowLossy
error:nil];
NSLog(@"[MXLogger] handleUncaughtException:\n%@", description);
// MXLogError(@"[MXLogger] handleUncaughtException:\n%@", description);
MXLogErrorDetails(@"handleUncaughtException", @{
@"description": description ?: @"unknown"
});
}
// Signals emitted by the app are handled here
@@ -302,16 +303,16 @@ static NSString* crashLogPath(void)
{
NSString *logsFolderPath = nil;
// NSURL *sharedContainerURL = [[NSFileManager defaultManager] applicationGroupContainerURL];
// if (sharedContainerURL)
// {
// logsFolderPath = [sharedContainerURL path];
// }
// else
// {
NSURL *sharedContainerURL = [[NSFileManager defaultManager] appGroupContainerURL];
if (sharedContainerURL)
{
logsFolderPath = [sharedContainerURL path];
}
else
{
NSArray<NSURL *> *paths = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
logsFolderPath = paths[0].path;
// }
}
return logsFolderPath;
}
@@ -332,7 +333,7 @@ static NSString* crashLogPath(void)
if ([fileManager fileExistsAtPath:logFile])
{
[fileManager removeItemAtPath:logFile error:nil];
// MXLogDebug(@"[MXLogger] removeExtraFilesFromCount: %@. removeItemAtPath: %@\n", @(count), logFile);
MXLogDebug(@"removeExtraFilesFromCount: %@. removeItemAtPath: %@\n", @(count), logFile);
}
else
{
@@ -374,19 +375,18 @@ static NSString* crashLogPath(void)
if (removeFiles)
{
// MXLogDebug(@"[MXLogger] removeFilesAfterSizeLimit: Remove files from index %@ because logs are too large (%@ for a limit of %@)\n",
// @(index),
// [NSByteCountFormatter stringFromByteCount:logSize countStyle:NSByteCountFormatterCountStyleBinary],
// [NSByteCountFormatter stringFromByteCount:sizeLimit countStyle:NSByteCountFormatterCountStyleBinary]);
MXLogDebug(@"removeFilesAfterSizeLimit: Remove files from index %@ because logs are too large (%@ for a limit of %@)\n",
@(index),
[NSByteCountFormatter stringFromByteCount:logSize countStyle:NSByteCountFormatterCountStyleBinary],
[NSByteCountFormatter stringFromByteCount:sizeLimit countStyle:NSByteCountFormatterCountStyleBinary]);
[self removeExtraFilesFromCount:index];
}
else
{
// MXLogDebug(@"[MXLogger] removeFilesAfterSizeLimit: No need: %@ for a limit of %@\n",
// [NSByteCountFormatter stringFromByteCount:logSize countStyle:NSByteCountFormatterCountStyleBinary],
// [NSByteCountFormatter stringFromByteCount:sizeLimit countStyle:NSByteCountFormatterCountStyleBinary]);
MXLogDebug(@"removeFilesAfterSizeLimit: No need: %@ for a limit of %@\n",
[NSByteCountFormatter stringFromByteCount:logSize countStyle:NSByteCountFormatterCountStyleBinary],
[NSByteCountFormatter stringFromByteCount:sizeLimit countStyle:NSByteCountFormatterCountStyleBinary]);
}
}
@end
@@ -67,17 +67,17 @@ final class NavigationRouter: NSObject, NavigationRouterType {
// MARK: - Public
func present(_ module: Presentable, animated: Bool = true) {
MXLog.debug("[NavigationRouter] Present \(module)")
MXLog.debug("Present \(module)")
navigationController.present(module.toPresentable(), animated: animated, completion: nil)
}
func dismissModule(animated: Bool = true, completion: (() -> Void)? = nil) {
MXLog.debug("[NavigationRouter] Dismiss presented module")
MXLog.debug("Dismiss presented module")
navigationController.dismiss(animated: animated, completion: completion)
}
func setRootModule(_ module: Presentable, hideNavigationBar: Bool = false, animated: Bool = false, popCompletion: (() -> Void)? = nil) {
MXLog.debug("[NavigationRouter] Set root module \(module)")
MXLog.debug("Set root module \(module)")
let controller = module.toPresentable()
@@ -116,7 +116,7 @@ final class NavigationRouter: NSObject, NavigationRouterType {
}
func setModules(_ modules: [NavigationModule], hideNavigationBar: Bool, animated: Bool) {
MXLog.debug("[NavigationRouter] Set modules \(modules)")
MXLog.debug("Set modules \(modules)")
let controllers = modules.map { module -> UIViewController in
let controller = module.presentable.toPresentable()
@@ -154,7 +154,7 @@ final class NavigationRouter: NSObject, NavigationRouterType {
}
func popToRootModule(animated: Bool) {
MXLog.debug("[NavigationRouter] Pop to root module")
MXLog.debug("Pop to root module")
let controllers = navigationController.viewControllers
@@ -174,7 +174,7 @@ final class NavigationRouter: NSObject, NavigationRouterType {
}
func popToModule(_ module: Presentable, animated: Bool) {
MXLog.debug("[NavigationRouter] Pop to module \(module)")
MXLog.debug("Pop to module \(module)")
let controller = module.toPresentable()
let controllersBeforePop = navigationController.viewControllers
@@ -195,7 +195,7 @@ final class NavigationRouter: NSObject, NavigationRouterType {
}
func push(_ module: Presentable, animated: Bool = true, popCompletion: (() -> Void)? = nil) {
MXLog.debug("[NavigationRouter] Push module \(module)")
MXLog.debug("Push module \(module)")
let controller = module.toPresentable()
@@ -219,7 +219,7 @@ final class NavigationRouter: NSObject, NavigationRouterType {
}
func push(_ modules: [NavigationModule], animated: Bool) {
MXLog.debug("[NavigationRouter] Push modules \(modules)")
MXLog.debug("Push modules \(modules)")
// Avoid pushing any UINavigationController onto stack
guard modules.first(where: { $0.presentable.toPresentable() is UINavigationController }) == nil else {
@@ -249,7 +249,7 @@ final class NavigationRouter: NSObject, NavigationRouterType {
}
func popModule(animated: Bool = true) {
MXLog.debug("[NavigationRouter] Pop module")
MXLog.debug("Pop module")
if let lastController = navigationController.viewControllers.last {
willPopViewController(lastController)
@@ -261,7 +261,7 @@ final class NavigationRouter: NSObject, NavigationRouterType {
}
func popAllModules(animated: Bool) {
MXLog.debug("[NavigationRouter] Pop all modules")
MXLog.debug("Pop all modules")
let controllersToPop = navigationController.viewControllers.reversed()
@@ -360,7 +360,7 @@ extension NavigationRouter: UINavigationControllerDelegate {
return
}
MXLog.debug("[NavigationRouter] Popped module: \(poppedViewController)")
MXLog.debug("Popped module: \(poppedViewController)")
didPopViewController(poppedViewController)
}
@@ -95,7 +95,7 @@ class AuthenticationCoordinator: Coordinator, Presentable {
case .updated:
self.showLoginScreen()
case .dismiss:
MXLog.failure("[AuthenticationCoordinator] ServerSelectionScreen is requesting dismiss when part of a stack.")
MXLog.failure("ServerSelectionScreen is requesting dismiss when part of a stack.")
}
}
@@ -76,11 +76,11 @@ final class LoginCoordinator: Coordinator, Presentable {
// MARK: - Public
func start() {
MXLog.debug("[LoginCoordinator] did start.")
MXLog.debug("Did start.")
loginViewModel.callback = { [weak self] action in
guard let self = self else { return }
MXLog.debug("[LoginCoordinator] LoginViewModel did callback with result: \(action).")
MXLog.debug("LoginViewModel did callback with result: \(action).")
switch action {
case .selectServer:
@@ -204,7 +204,7 @@ final class LoginCoordinator: Coordinator, Presentable {
/// Presents the server selection screen as a modal.
private func presentServerSelectionScreen() {
MXLog.debug("[LoginCoordinator] presentServerSelectionScreen")
MXLog.debug("PresentServerSelectionScreen")
let parameters = ServerSelectionCoordinatorParameters(authenticationService: authenticationService,
hasModalPresentation: true)
let coordinator = ServerSelectionCoordinator(parameters: parameters)
@@ -64,11 +64,11 @@ final class ServerSelectionCoordinator: Coordinator, Presentable {
// MARK: - Public
func start() {
MXLog.debug("[ServerSelectionCoordinator] did start.")
MXLog.debug("Did start.")
serverSelectionViewModel.callback = { [weak self] action in
guard let self = self else { return }
MXLog.debug("[ServerSelectionCoordinator] ServerSelectionViewModel did callback with action: \(action).")
MXLog.debug("ServerSelectionViewModel did callback with action: \(action).")
switch action {
case .confirm(let homeserverAddress):
@@ -57,10 +57,10 @@ final class BugReportCoordinator: Coordinator, Presentable {
// MARK: - Public
func start() {
MXLog.debug("[BugReportCoordinator] did start.")
MXLog.debug("Did start.")
bugReportViewModel.callback = { [weak self] result in
guard let self = self else { return }
MXLog.debug("[BugReportCoordinator] BugReportViewModel did complete with result: \(result).")
MXLog.debug("BugReportViewModel did complete with result: \(result).")
switch result {
case .submitStarted:
self.startLoading()
@@ -47,10 +47,10 @@ class BugReportViewModel: BugReportViewModelType, BugReportViewModelProtocol {
includeCrashLog: true,
githubLabels: BuildSettings.bugReportGHLabels,
files: files)
MXLog.info("[BugReportViewModel] submitBugReport succeeded, result: \(result.reportUrl)")
MXLog.info("SubmitBugReport succeeded, result: \(result.reportUrl)")
callback?(.submitFinished)
} catch {
MXLog.error("[BugReportViewModel] submitBugReport failed: \(error)")
MXLog.error("SubmitBugReport failed: \(error)")
callback?(.submitFailed(error: error))
}
}
@@ -49,7 +49,7 @@ final class SessionVerificationCoordinator: Coordinator, Presentable {
// MARK: - Public
func start() {
MXLog.debug("[SessionVerificationCoordinator] did start.")
MXLog.debug("Did start.")
sessionVerificationViewModel.callback = { [weak self] action in
guard let self = self else { return }
@@ -51,7 +51,7 @@ class SessionVerificationViewModel: SessionVerificationViewModelType, SessionVer
switch callback {
case .receivedVerificationData(let emojis):
guard self.stateMachine.state == .requestingVerification else {
MXLog.warning("[SessionVerificationViewModel] callbacks: Ignoring receivedVerificationData due to invalid state.")
MXLog.warning("Callbacks: Ignoring receivedVerificationData due to invalid state.")
return
}
@@ -58,7 +58,7 @@ final class SettingsCoordinator: Coordinator, Presentable {
settingsViewModel.callback = { [weak self] result in
guard let self = self else { return }
MXLog.debug("[SettingsCoordinator] SettingsViewModel did complete with result: \(result).")
MXLog.debug("SettingsViewModel did complete with result: \(result).")
switch result {
case .reportBug:
self.presentBugReportScreen()
@@ -47,9 +47,9 @@ final class SplashScreenCoordinator: Coordinator, Presentable {
// MARK: - Public
func start() {
MXLog.debug("[SplashScreenCoordinator] did start.")
MXLog.debug("Did start.")
splashScreenViewModel.callback = { [weak self] action in
MXLog.debug("[SplashScreenCoordinator] SplashScreenViewModel did complete with result: \(action).")
MXLog.debug("SplashScreenViewModel did complete with result: \(action).")
guard let self = self else { return }
switch action {
case .login:
@@ -57,7 +57,7 @@ class UIKitBackgroundTask: BackgroundTaskProtocol {
}
if identifier == .invalid {
MXLog.verbose("[UIKitBackgroundTask] Do not start background task: \(name), as OS declined")
MXLog.verbose("Do not start background task: \(name), as OS declined")
// call expiration handler immediately
expirationHandler?(self)
return nil
@@ -68,7 +68,7 @@ class UIKitBackgroundTask: BackgroundTaskProtocol {
reuse()
}
MXLog.verbose("[UIKitBackgroundTask] Start background task #\(identifier.rawValue) - \(name)")
MXLog.verbose("Start background task #\(identifier.rawValue) - \(name)")
}
func reuse() {
@@ -91,7 +91,7 @@ class UIKitBackgroundTask: BackgroundTaskProtocol {
private func endTask() {
if identifier != .invalid {
MXLog.verbose("[UIKitBackgroundTask] End background task #\(identifier.rawValue) - \(name) after \(readableElapsedTime)")
MXLog.verbose("End background task #\(identifier.rawValue) - \(name) after \(readableElapsedTime)")
application.endBackgroundTask(identifier)
identifier = .invalid
@@ -32,12 +32,12 @@ class UIKitBackgroundTaskService: BackgroundTaskServiceProtocol {
isReusable: Bool,
expirationHandler: (() -> Void)?) -> BackgroundTaskProtocol? {
guard let application = application else {
MXLog.verbose("[UIKitBackgroundTaskService] Do not start background task: \(name). Application is nil")
MXLog.verbose("Do not start background task: \(name). Application is nil")
return nil
}
if avoidStartingNewTasks(for: application) {
MXLog.verbose("[UIKitBackgroundTaskService] Do not start background task: \(name), as not enough time exists")
MXLog.verbose("Do not start background task: \(name), as not enough time exists")
// call expiration handler immediately
expirationHandler?()
return nil
@@ -78,7 +78,7 @@ class UIKitBackgroundTaskService: BackgroundTaskServiceProtocol {
let appState = application.applicationState
let remainingTime = readableBackgroundTimeRemaining(application.backgroundTimeRemaining)
MXLog.verbose("[UIKitBackgroundTaskService] Background task \(name) \(created ? "started" : "reused") with app state: \(appState) and estimated background time remaining: \(remainingTime)")
MXLog.verbose("Background task \(name) \(created ? "started" : "reused") with app state: \(appState) and estimated background time remaining: \(remainingTime)")
return result
}
@@ -30,6 +30,7 @@ class BugReportService: BugReportServiceProtocol {
private let sentryEndpoint: String
private let applicationId: String
private let session: URLSession
private var lastCrashEventId: String?
init(withBaseUrlString baseUrlString: String,
sentryEndpoint: String,
@@ -63,8 +64,9 @@ class BugReportService: BugReportServiceProtocol {
return event
}
options.onCrashedLastRun = { event in
options.onCrashedLastRun = { [weak self] event in
MXLog.debug("Sentry detected application was crashed: \(event)")
self?.lastCrashEventId = event.eventId.sentryIdString
}
}
@@ -84,12 +86,13 @@ class BugReportService: BugReportServiceProtocol {
SentrySDK.crash()
}
// swiftlint: disable function_body_length
func submitBugReport(text: String,
includeLogs: Bool,
includeCrashLog: Bool,
githubLabels: [String],
files: [URL]) async throws -> SubmitBugReportResponse {
MXLog.debug("[BugReportService] submitBugReport")
MXLog.debug("submitBugReport")
var params = [
MultipartFormData(key: "text", type: .text(value: text))
@@ -106,6 +109,11 @@ class BugReportService: BugReportServiceProtocol {
params.append(MultipartFormData(key: "compressed-log", type: .file(url: url)))
}
}
if let crashEventId = lastCrashEventId {
params.append(MultipartFormData(key: "crash_report", type: .text(value: "<https://sentry.tools.element.io/organizations/element/issues/?project=44&query=\(crashEventId)>")))
}
for url in files {
params.append(MultipartFormData(key: "file", type: .file(url: url)))
}
@@ -142,9 +150,11 @@ class BugReportService: BugReportServiceProtocol {
if !result.reportUrl.isEmpty {
MXLogger.deleteCrashLog()
lastCrashEventId = nil
}
return result
}
} // swiftlint: enable function_body_length
// MARK: - Private
@@ -179,7 +189,7 @@ class BugReportService: BugReportServiceProtocol {
private func zipFiles(includeLogs: Bool,
includeCrashLog: Bool) async throws -> [URL] {
MXLog.debug("[BugReportService] zipFiles: includeLogs: \(includeLogs), includeCrashLog: \(includeCrashLog)")
MXLog.debug("zipFiles: includeLogs: \(includeLogs), includeCrashLog: \(includeCrashLog)")
var filesToCompress: [URL] = []
if includeLogs, let logFiles = MXLogger.logFiles() {
@@ -217,7 +227,7 @@ class BugReportService: BugReportServiceProtocol {
zippedFiles.append(zippedFileURL)
}
MXLog.debug("[BugReportService] zipFiles: totalSize: \(totalSize), totalZippedSize: \(totalZippedSize)")
MXLog.debug("zipFiles: totalSize: \(totalSize), totalZippedSize: \(totalZippedSize)")
return zippedFiles
}
@@ -18,7 +18,7 @@ import Foundation
extension FileManager {
/// The URL of the primary app group container.
var appGroupContainerURL: URL? {
@objc var appGroupContainerURL: URL? {
containerURL(forSecurityApplicationGroupIdentifier: ElementInfoPlist.appGroupIdentifier)
}
}