From 1c8fc8f585d7e90653f67a2d4a9a77e47790acaa Mon Sep 17 00:00:00 2001 From: Zach Nelson Date: Thu, 19 Nov 2026 11:59:00 -0600 Subject: [PATCH] Log through the unified log instead of NSLog --- CoreZen.xcodeproj/project.pbxproj | 22 +++++++++++ CoreZen/Categories/NSFileManager+CoreZen.m | 3 +- CoreZen/Database/Database+Private.h | 4 +- CoreZen/Database/Database.m | 21 ++++++---- CoreZen/Database/DatabaseQueue.m | 30 ++++++++------ CoreZen/Database/DatabaseSchema.m | 7 ++-- CoreZen/Database/ResultSet.m | 2 +- CoreZen/Domain/DomainObject.m | 4 +- CoreZen/Domain/ObjectRepository.m | 10 +++-- CoreZen/Logging/Log.h | 43 +++++++++++++++++++++ CoreZen/Logging/Log.m | 25 ++++++++++++ CoreZen/Media/LibAV/LibAVInfoController.m | 10 ++--- CoreZen/Media/LibAV/LibAVRenderController.m | 19 ++++----- CoreZen/Media/MPV/MPVPlayerController.m | 26 ++++++++----- CoreZen/Media/MPV/MPVRenderController.m | 3 +- CoreZen/Media/MediaFile.m | 5 ++- CoreZen/Media/MediaPlayer.m | 5 ++- CoreZen/Queue/WorkQueue.m | 3 +- CoreZenTests/Classes/TestLog.h | 22 +++++++++++ CoreZenTests/Classes/TestLog.m | 38 ++++++++++++++++++ CoreZenTests/DatabaseTests.m | 22 +++++++++++ CoreZenTests/MediaPlayerTests.m | 21 +++++++++- README.md | 8 ++++ 23 files changed, 289 insertions(+), 64 deletions(-) create mode 100644 CoreZen/Logging/Log.h create mode 100644 CoreZen/Logging/Log.m create mode 100644 CoreZenTests/Classes/TestLog.h create mode 100644 CoreZenTests/Classes/TestLog.m diff --git a/CoreZen.xcodeproj/project.pbxproj b/CoreZen.xcodeproj/project.pbxproj index 36c4e23..536a92e 100644 --- a/CoreZen.xcodeproj/project.pbxproj +++ b/CoreZen.xcodeproj/project.pbxproj @@ -7,6 +7,9 @@ objects = { /* Begin PBXBuildFile section */ + DD0000020000000000000001 /* Log.h in Headers */ = {isa = PBXBuildFile; fileRef = DD0000010000000000000001 /* Log.h */; }; + DD0000020000000000000002 /* Log.m in Sources */ = {isa = PBXBuildFile; fileRef = DD0000010000000000000002 /* Log.m */; }; + DD0000020000000000000004 /* TestLog.m in Sources */ = {isa = PBXBuildFile; fileRef = DD0000010000000000000004 /* TestLog.m */; }; 10E3163392F12AF956341355 /* licenses in Resources */ = {isa = PBXBuildFile; fileRef = CF0E6577750FB6561C55DB40 /* licenses */; }; 23E8171B92C816C235C1B1B2 /* FMDB-LICENSE.txt in Resources */ = {isa = PBXBuildFile; fileRef = A8C4E7FED8E6976453047D72 /* FMDB-LICENSE.txt */; }; AA0000020000000000000001 /* Database.h in Headers */ = {isa = PBXBuildFile; fileRef = AA0000010000000000000001 /* Database.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -186,6 +189,10 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + DD0000010000000000000001 /* Log.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Log.h; sourceTree = ""; }; + DD0000010000000000000002 /* Log.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = Log.m; sourceTree = ""; }; + DD0000010000000000000003 /* TestLog.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TestLog.h; sourceTree = ""; }; + DD0000010000000000000004 /* TestLog.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = TestLog.m; sourceTree = ""; }; CF0E6577750FB6561C55DB40 /* licenses */ = {isa = PBXFileReference; lastKnownFileType = folder; path = licenses; sourceTree = ""; }; A8C4E7FED8E6976453047D72 /* FMDB-LICENSE.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = "FMDB-LICENSE.txt"; sourceTree = ""; }; AA0000010000000000000001 /* Database.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Database.h; sourceTree = ""; }; @@ -500,6 +507,15 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + DD0000030000000000000001 /* Logging */ = { + isa = PBXGroup; + children = ( + DD0000010000000000000001 /* Log.h */, + DD0000010000000000000002 /* Log.m */, + ); + path = Logging; + sourceTree = ""; + }; 5309C39F2885A1DC00BC0AAE = { isa = PBXGroup; children = ( @@ -528,6 +544,7 @@ 5309C4112885B66000BC0AAE /* Database */, 538E05002885DCD300CE9DE7 /* Domain */, 5309C3EE2885A6C800BC0AAE /* Identifier */, + DD0000030000000000000001 /* Logging */, 5350F8BF2886192E00F8CA68 /* Media */, 5350FB0328889E5F00F8CA68 /* Node */, 5309C3E52885A37900BC0AAE /* Preferences */, @@ -703,6 +720,8 @@ 538E052D2885FB5400CE9DE7 /* TestIdentifiable.m */, CC00000128860A0000000006 /* TestTable.h */, CC00000128860A0000000007 /* TestTable.m */, + DD0000010000000000000003 /* TestLog.h */, + DD0000010000000000000004 /* TestLog.m */, ); path = Classes; sourceTree = ""; @@ -1063,6 +1082,7 @@ 5309C4292885D19400BC0AAE /* DatabaseTable.h in Headers */, AA0000020000000000000004 /* ResultSet.h in Headers */, AA0000020000000000000006 /* ResultSet+Private.h in Headers */, + DD0000020000000000000001 /* Log.h in Headers */, 5350F8C22886194200F8CA68 /* MediaFile.h in Headers */, 5309C3E82885A39C00BC0AAE /* PreferencesWindowController.h in Headers */, 538E05072885DD1D00CE9DE7 /* DomainCallbacks.h in Headers */, @@ -1227,6 +1247,7 @@ 5309C3E92885A39C00BC0AAE /* PreferencesWindowController.m in Sources */, 53964F0B288C4C48007B53EC /* MPVPlayerController.m in Sources */, 5331FE622922AD8700C15950 /* WorkQueue.m in Sources */, + DD0000020000000000000002 /* Log.m in Sources */, 5309C4222885CB1400BC0AAE /* DataTransferObject.m in Sources */, 5386706C28BFE16300FB15EB /* MediaPlayerControlsView.m in Sources */, 5396531D288CD19C007B53EC /* MediaPlayerView.m in Sources */, @@ -1277,6 +1298,7 @@ CC00000228860A0000000006 /* TestDomainObject.m in Sources */, 538E052E2885FB5400CE9DE7 /* TestIdentifiable.m in Sources */, CC00000228860A0000000005 /* TestTable.m in Sources */, + DD0000020000000000000004 /* TestLog.m in Sources */, 0313158D2D7374094EFBE6DC /* MediaTests.m in Sources */, B87FBFD38A588272C385E7BC /* MPVFunctionsTests.m in Sources */, 0E03AE27A6C781F30909CE0A /* MediaPlayerTests.m in Sources */, diff --git a/CoreZen/Categories/NSFileManager+CoreZen.m b/CoreZen/Categories/NSFileManager+CoreZen.m index 0b3d572..e9a807b 100644 --- a/CoreZen/Categories/NSFileManager+CoreZen.m +++ b/CoreZen/Categories/NSFileManager+CoreZen.m @@ -6,6 +6,7 @@ // #import "NSFileManager+CoreZen.h" +#import "Log.h" @implementation NSFileManager (CoreZen) @@ -41,7 +42,7 @@ - (NSURL *)zen_applicationSupportDirectory { NSError *error; NSURL *url = [self zen_findOrCreateURLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appendPathComponent:executableName create:YES error:&error]; if (!url) { - NSLog(@"Unable to find or create application support directory: %@", error); + os_log_error(ZENLogGeneral(), "Couldn't find or create the application support folder: %@", error.localizedDescription); } return url; } diff --git a/CoreZen/Database/Database+Private.h b/CoreZen/Database/Database+Private.h index 72f5f0a..9ce3c63 100644 --- a/CoreZen/Database/Database+Private.h +++ b/CoreZen/Database/Database+Private.h @@ -33,9 +33,9 @@ NSError *ZENDatabaseErrorMake(ZENDatabaseErrorCode code, NSString *description); // it failed, or a block canceled it), or nil if it can commit - (NSError *)rollbackError; -// Records a failed statement, which the open transaction must roll back for. +// Logs a failed statement, and records it, so the open transaction rolls back. // ZENResultSet calls it when stepping through rows fails. -- (void)statementFailed; +- (void)statementFailed:(NSString *)sql; - (void)setShouldCacheStatements:(BOOL)value; - (void)setTraceExecution:(BOOL)value; diff --git a/CoreZen/Database/Database.m b/CoreZen/Database/Database.m index d8d6351..ea7765e 100644 --- a/CoreZen/Database/Database.m +++ b/CoreZen/Database/Database.m @@ -8,6 +8,7 @@ #import "Database.h" #import "Database+Private.h" #import "ResultSet+Private.h" +#import "Log.h" #import @@ -48,7 +49,7 @@ - (BOOL)executeUpdate:(NSString *)sql, ... { BOOL result = [self.fmDatabase executeUpdate:sql withVAList:args]; va_end(args); if (!result) { - [self statementFailed]; + [self statementFailed:sql]; } return result; } @@ -56,16 +57,16 @@ - (BOOL)executeUpdate:(NSString *)sql, ... { - (BOOL)executeUpdate:(NSString *)sql withArgumentsInArray:(NSArray *)arguments { BOOL result = [self.fmDatabase executeUpdate:sql withArgumentsInArray:arguments]; if (!result) { - [self statementFailed]; + [self statementFailed:sql]; } return result; } #pragma mark - Queries -- (ZENResultSet *)wrapResultSet:(FMResultSet *)rs { +- (ZENResultSet *)wrapResultSet:(FMResultSet *)rs sql:(NSString *)sql { if (!rs) { - [self statementFailed]; + [self statementFailed:sql]; return nil; } return [ZENResultSet resultSetWithFMResultSet:rs database:self]; @@ -76,18 +77,18 @@ - (ZENResultSet *)executeQuery:(NSString *)sql, ... { va_start(args, sql); FMResultSet *rs = [self.fmDatabase executeQuery:sql withVAList:args]; va_end(args); - return [self wrapResultSet:rs]; + return [self wrapResultSet:rs sql:sql]; } - (ZENResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments { - return [self wrapResultSet:[self.fmDatabase executeQuery:sql withArgumentsInArray:arguments]]; + return [self wrapResultSet:[self.fmDatabase executeQuery:sql withArgumentsInArray:arguments] sql:sql]; } #pragma mark - Transactions - (void)cancelTransaction { if (!self.inTransaction) { - NSLog(@"WARNING: cancelTransaction called outside a transaction"); + os_log(ZENLogDatabase(), "cancelTransaction was called outside a transaction, so it did nothing"); return; } if (!_rollbackError) { @@ -106,7 +107,11 @@ - (NSError *)rollbackError { return _rollbackError; } -- (void)statementFailed { +- (void)statementFailed:(NSString *)sql { + // FMDB's own logging of this is off, so the message goes under CoreZen's + // subsystem. The statement's values are bound separately, so it holds only SQL. + os_log_error(ZENLogDatabase(), "A statement failed: %{public}@\n%{public}@", self.fmDatabase.lastErrorMessage, sql); + // Outside a transaction a failed statement has nothing to undo if (!_rollbackError && self.inTransaction) { NSString *description = [NSString stringWithFormat:@"A statement failed: %@", self.fmDatabase.lastErrorMessage]; diff --git a/CoreZen/Database/DatabaseQueue.m b/CoreZen/Database/DatabaseQueue.m index 9d32941..7061f9a 100644 --- a/CoreZen/Database/DatabaseQueue.m +++ b/CoreZen/Database/DatabaseQueue.m @@ -8,6 +8,7 @@ #import "DatabaseQueue+Private.h" #import "Database+Private.h" #import "ResultSet.h" +#import "Log.h" #import "WorkQueue.h" #import @@ -48,7 +49,6 @@ - (void)internalInit:(NSString *)queueLabel { - (instancetype)initInMemoryWithOptions:(ZENDatabaseQueueOptions)options { self = [super init]; if (self) { - NSLog(@"Database in memory"); _databaseURL = nil; _options = options; @@ -72,7 +72,6 @@ + (instancetype)databaseQueueInMemoryWithOptions:(ZENDatabaseQueueOptions)option - (instancetype)initWithURL:(NSURL *)URL options:(ZENDatabaseQueueOptions)options { self = [super init]; if (self) { - NSLog(@"Database at: %@", URL); _databaseURL = URL; _options = options; @@ -98,7 +97,7 @@ - (void)shutdown:(ZENDatabaseBlock)updateBlock { // A second shutdown can't run its block: the first closes the database, and // the work queue would run the block on the caller's thread, not in turn if (atomic_exchange(&_shutdownStarted, true)) { - NSLog(@"WARNING: Database queue %@ was already shut down, so its database is closed", self.workQueue.label); + os_log(ZENLogDatabase(), "Database queue %@ was already shut down, so this shutdown did nothing", self.workQueue.label); return; } @@ -123,16 +122,18 @@ - (ZENDatabase *)database { if (_database == nil) { FMDatabase *fmdb; if (self.databaseURL) { - NSLog(@"Opening database at %@", self.databaseURL); + os_log_info(ZENLogDatabase(), "Opening the database at %@", self.databaseURL.path); fmdb = [FMDatabase databaseWithURL:self.databaseURL]; } else { // No path makes a private in-memory database, which lasts until it closes - NSLog(@"Opening database in memory"); + os_log_info(ZENLogDatabase(), "Opening a database in memory"); fmdb = [FMDatabase databaseWithPath:nil]; } + // CoreZen logs failed statements itself, along with the rest of its messages + fmdb.logsErrors = NO; if (![fmdb open]) { - NSLog(@"ERROR: Failed to open database at %@", self.databaseURL); + os_log_error(ZENLogDatabase(), "Couldn't open the database at %@: %{public}@", self.databaseURL.path, fmdb.lastErrorMessage); return nil; } @@ -156,8 +157,8 @@ - (void)configureDatabase:(ZENDatabase *)database { NSString *mode = [rs next] ? [rs stringForColumnIndex:0] : nil; [rs close]; if (![mode isEqualToString:@"wal"]) { - NSLog(@"WARNING: %@ couldn't switch to a write-ahead log, so it keeps its %@ journal", - self.databaseURL.lastPathComponent, mode ?: @"current"); + os_log(ZENLogDatabase(), "%@ couldn't switch to a write-ahead log, so it keeps its %{public}@ journal", + self.databaseURL.lastPathComponent, mode ?: @"current"); } } @@ -194,8 +195,8 @@ - (NSError *)runTransaction:(ZENDatabaseBlock)updateBlock { } if (![database beginTransaction]) { - NSLog(@"ERROR: Couldn't begin a transaction, so each of its statements commits on its own: %@", - database.lastErrorMessage); + os_log_error(ZENLogDatabase(), "Couldn't begin a transaction, so each of its statements commits on its own: %{public}@", + database.lastErrorMessage); } updateBlock(database); @@ -206,13 +207,18 @@ - (NSError *)runTransaction:(ZENDatabaseBlock)updateBlock { } NSError *rollbackError = database.rollbackError; if (rollbackError) { - NSLog(@"Rolling back a transaction: %@", rollbackError.localizedDescription); + // A canceled transaction is rolled back on purpose; anything else is a failure + if (rollbackError.code == ZENDatabaseErrorTransactionCanceled) { + os_log_info(ZENLogDatabase(), "Rolling back a transaction: %{public}@", rollbackError.localizedDescription); + } else { + os_log_error(ZENLogDatabase(), "Rolling back a transaction: %{public}@", rollbackError.localizedDescription); + } [database rollback]; return rollbackError; } if (![database commit]) { NSString *description = [NSString stringWithFormat:@"Couldn't commit the transaction: %@", database.lastErrorMessage]; - NSLog(@"ERROR: %@, so rolling it back", description); + os_log_error(ZENLogDatabase(), "%{public}@, so rolling it back", description); // A failed commit can leave the transaction open, which would swallow the next one if (database.inTransaction) { [database rollback]; diff --git a/CoreZen/Database/DatabaseSchema.m b/CoreZen/Database/DatabaseSchema.m index e2db368..7755d3a 100644 --- a/CoreZen/Database/DatabaseSchema.m +++ b/CoreZen/Database/DatabaseSchema.m @@ -10,6 +10,7 @@ #import "Database+Private.h" #import "ResultSet.h" #import "ObjectIdentifier+Private.h" +#import "Log.h" @interface ZENDatabaseSchema () @@ -49,7 +50,7 @@ - (void)initializeDatabase:(ZENDatabase *)database { BOOL versionChanged = [self updateDatabaseSchema:database]; NSError *rollbackError = database.rollbackError; if (rollbackError) { - NSLog(@"ERROR: Rolling back the schema update: %@", rollbackError.localizedDescription); + os_log_error(ZENLogDatabase(), "Rolling back the schema update: %{public}@", rollbackError.localizedDescription); } if (ownsTransaction) { if (versionChanged && !rollbackError) { @@ -98,7 +99,7 @@ - (BOOL)updateDatabaseSchema:(ZENDatabase *)database { BOOL versionChanged = (schemaVersion != startingVersion); if (versionChanged) { - NSLog(@"Schema updated from version %lu to %lu", startingVersion, schemaVersion); + os_log_info(ZENLogDatabase(), "Schema updated from version %lu to %lu", startingVersion, schemaVersion); NSString *statement = [NSString stringWithFormat:@"PRAGMA user_version = %lu", schemaVersion]; [database executeUpdate:statement]; } @@ -125,7 +126,7 @@ - (void)initializeIdentifiers:(ZENDatabase *)database { [rs close]; } if (largestTableName) { - NSLog(@"Largest identifier is %lli (in %@)", largestIdentifier, largestTableName); + os_log_info(ZENLogDatabase(), "Largest identifier is %lli (in %{public}@)", largestIdentifier, largestTableName); ZENRaiseLargestObjectIdentifier(largestIdentifier); } } diff --git a/CoreZen/Database/ResultSet.m b/CoreZen/Database/ResultSet.m index 0b02aac..835e5cc 100644 --- a/CoreZen/Database/ResultSet.m +++ b/CoreZen/Database/ResultSet.m @@ -32,7 +32,7 @@ - (BOOL)next { NSError *error = nil; BOOL hasRow = [self.fmResultSet nextWithError:&error]; if (!hasRow && error) { - [self.database statementFailed]; + [self.database statementFailed:self.fmResultSet.query ?: @""]; } return hasRow; } diff --git a/CoreZen/Domain/DomainObject.m b/CoreZen/Domain/DomainObject.m index 846dbb2..eaa7b4e 100644 --- a/CoreZen/Domain/DomainObject.m +++ b/CoreZen/Domain/DomainObject.m @@ -8,6 +8,7 @@ #import "DomainObject.h" #import "DomainCommon.h" #import "WorkQueue.h" +#import "Log.h" @interface ZENDomainObject () @@ -61,7 +62,8 @@ + (void)asyncInit:(NSArray *)objects } dispatch_group_leave(group); } else { - NSLog(@"WARNING: %@ called its performAsyncInit: completion more than once", domainObject); + os_log(ZENLogDomain(), "%{public}@ %lld called its performAsyncInit: completion more than once", + NSStringFromClass([domainObject class]), domainObject.identifier); } }]; }); diff --git a/CoreZen/Domain/ObjectRepository.m b/CoreZen/Domain/ObjectRepository.m index 307b602..ec20c30 100644 --- a/CoreZen/Domain/ObjectRepository.m +++ b/CoreZen/Domain/ObjectRepository.m @@ -12,6 +12,7 @@ #import "Database+Private.h" #import "ResultSet.h" #import "DomainCommon.h" +#import "Log.h" #import @@ -167,7 +168,8 @@ - (void)cacheAndStartAsyncInit:(NSArray *)objects { if (error) { // Drop the object, so fetches leave it out. A later fetch creates it // again from the database and retries its init. - NSLog(@"Async init failed for %@: %@", object, error); + os_log(ZENLogDomain(), "Async init failed for %{public}@ %lld, so fetches leave it out: %@", + NSStringFromClass([object class]), object.identifier, error.localizedDescription); if ([self.cache cachedObject:object.identifier] == object) { [self.cache removeObject:object.identifier]; } @@ -331,7 +333,7 @@ - (void)write:(BOOL (^)(ZENDatabase *database))write error = ZENDatabaseErrorMake(ZENDatabaseErrorWriteFailed, @"The table couldn't write the object"); } if (error) { - NSLog(@"ERROR: A write to %@ wasn't saved: %@", [[self.table class] tableName], error.localizedDescription); + os_log_error(ZENLogDomain(), "A write to %{public}@ wasn't saved: %{public}@", [[self.table class] tableName], error.localizedDescription); } else { // Still on the database queue, so the cache keeps step with the // database for the next block that runs there @@ -463,7 +465,7 @@ + (void)performWrites:(void(NS_NOESCAPE ^)(ZENRepositoryWriteBatch *batch))build description = [NSString stringWithFormat:@"A write batch has more than one write for object %lld in %@", write.identifier, tableName]; } if (description) { - NSLog(@"ERROR: %@", description); + os_log_error(ZENLogDomain(), "%{public}@", description); ZENCallAsyncCompletionBlockOnThreadPool(completion, ZENDatabaseErrorMake(ZENDatabaseErrorWriteFailed, description)); return; } @@ -491,7 +493,7 @@ + (void)performWrites:(void(NS_NOESCAPE ^)(ZENRepositoryWriteBatch *batch))build error = writeError; } if (error) { - NSLog(@"ERROR: A write batch wasn't saved: %@", error.localizedDescription); + os_log_error(ZENLogDomain(), "A write batch wasn't saved: %{public}@", error.localizedDescription); ZENCallAsyncCompletionBlockOnThreadPool(completion, error); return; } diff --git a/CoreZen/Logging/Log.h b/CoreZen/Logging/Log.h new file mode 100644 index 0000000..b963d51 --- /dev/null +++ b/CoreZen/Logging/Log.h @@ -0,0 +1,43 @@ +// +// Log.h +// CoreZen +// + +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +// CoreZen logs to the unified log, under the subsystem com.zdnelson.CoreZen, +// with a category for each part of the framework. An app's developer can then +// show or hide them in Console, or stream them with: +// +// log stream --predicate 'subsystem == "com.zdnelson.CoreZen"' +// +// Levels: +// - error: something failed, such as a write that wasn't saved +// - default: worth noticing but harmless, such as a method called twice +// - info: routine, such as a database opening +// The unified log keeps info messages only in memory unless asked to keep them. +// +// Text that can name the user's files, like a path, a URL or a message from mpv, +// is logged as private, which the unified log hides unless the Mac is set to +// show private data. Text CoreZen or SQLite writes, like an SQL statement or an +// error message, is public. + +// ZENDatabaseQueue, ZENDatabase and ZENDatabaseSchema +os_log_t ZENLogDatabase(void); + +// Repositories and domain objects +os_log_t ZENLogDomain(void); + +// Media files, and the frames rendered from them +os_log_t ZENLogMedia(void); + +// The media player, and mpv +os_log_t ZENLogPlayer(void); + +// Everything else +os_log_t ZENLogGeneral(void); + +NS_ASSUME_NONNULL_END diff --git a/CoreZen/Logging/Log.m b/CoreZen/Logging/Log.m new file mode 100644 index 0000000..1578202 --- /dev/null +++ b/CoreZen/Logging/Log.m @@ -0,0 +1,25 @@ +// +// Log.m +// CoreZen +// + +#import "Log.h" + +static const char *const kZENLogSubsystem = "com.zdnelson.CoreZen"; + +// Each category's log is made once, on first use, and kept +#define ZEN_LOG_CATEGORY(function, category) \ + os_log_t function(void) { \ + static os_log_t log; \ + static dispatch_once_t once; \ + dispatch_once(&once, ^{ \ + log = os_log_create(kZENLogSubsystem, category); \ + }); \ + return log; \ + } + +ZEN_LOG_CATEGORY(ZENLogDatabase, "Database") +ZEN_LOG_CATEGORY(ZENLogDomain, "Domain") +ZEN_LOG_CATEGORY(ZENLogMedia, "Media") +ZEN_LOG_CATEGORY(ZENLogPlayer, "Player") +ZEN_LOG_CATEGORY(ZENLogGeneral, "General") diff --git a/CoreZen/Media/LibAV/LibAVInfoController.m b/CoreZen/Media/LibAV/LibAVInfoController.m index fc9d878..83d4008 100644 --- a/CoreZen/Media/LibAV/LibAVInfoController.m +++ b/CoreZen/Media/LibAV/LibAVInfoController.m @@ -7,6 +7,7 @@ #import "LibAVInfoController.h" #import "LibAVRenderController.h" +#import "Log.h" #import @@ -21,9 +22,8 @@ void ZENLogAVFindBestStreamError(NSString *filePath, int returnCode, enum AVMediaType mediaType) { const char *streamType = av_get_media_type_string(mediaType); - char reason[AV_ERROR_MAX_STRING_SIZE]; - av_strerror(returnCode, reason, sizeof(reason)); - NSLog(@"av_find_best_stream(%@, %s) failed: %s", filePath, streamType ? streamType : "unknown", reason); + os_log_error(ZENLogMedia(), "Couldn't find the best %{public}s stream in %@: %{public}s (%d)", + streamType ? streamType : "unknown", filePath, av_err2str(returnCode), returnCode); } // A codec's name as a string, or nil if the codec or its name is missing @@ -87,13 +87,13 @@ - (void)avInit:(NSString *)mediaPath { ZENLogAVFindBestStreamError(mediaPath, audioStreamIndex, AVMEDIA_TYPE_AUDIO); } } else { - NSLog(@"avformat_find_stream_info(%@) failed, result: %d", mediaPath, result); + os_log_error(ZENLogMedia(), "avformat_find_stream_info failed for %@: %{public}s (%d)", mediaPath, av_err2str(result), result); } } else { // avformat_open_input() documentation: // Note that a user-supplied AVFormatContext will be freed on failure. _formatContext = NULL; - NSLog(@"avformat_open_input(%@) failed, result: %d", mediaPath, result); + os_log_error(ZENLogMedia(), "avformat_open_input failed for %@: %{public}s (%d)", mediaPath, av_err2str(result), result); } } diff --git a/CoreZen/Media/LibAV/LibAVRenderController.m b/CoreZen/Media/LibAV/LibAVRenderController.m index e33914c..dec5450 100644 --- a/CoreZen/Media/LibAV/LibAVRenderController.m +++ b/CoreZen/Media/LibAV/LibAVRenderController.m @@ -8,6 +8,7 @@ #import "LibAVRenderController.h" #import "LibAVInfoController.h" #import "WorkQueue.h" +#import "Log.h" @import Cocoa; @@ -57,18 +58,18 @@ @implementation ZENLibAVRenderController - (void)avInitWithCodec:(const AVCodec *)codec stream:(const AVStream *)stream { if (!codec || !stream) { - NSLog(@"avInitWithCodec: codec or stream is NULL"); + os_log_error(ZENLogMedia(), "Can't render frames without a video codec and stream"); return; } AVCodecContext *codecContext = avcodec_alloc_context3(codec); if (!codecContext) { - NSLog(@"avcodec_alloc_context3 failed"); + os_log_error(ZENLogMedia(), "avcodec_alloc_context3 failed"); return; } avcodec_parameters_to_context(codecContext, stream->codecpar); if (codecContext->pix_fmt < 0 || codecContext->pix_fmt >= AV_PIX_FMT_NB) { - NSLog(@"Video codec pixel format is invalid"); + os_log_error(ZENLogMedia(), "The video codec's pixel format is invalid"); avcodec_free_context(&codecContext); return; } @@ -78,7 +79,7 @@ - (void)avInitWithCodec:(const AVCodec *)codec int result = avcodec_open2(codecContext, codec, NULL); if (result < 0) { - NSLog(@"avcodec_open2 failed, result: %d", result); + os_log_error(ZENLogMedia(), "avcodec_open2 failed: %{public}s (%d)", av_err2str(result), result); avcodec_free_context(&codecContext); return; } @@ -120,7 +121,7 @@ - (BOOL)renderRawFrame:(AVFrame *)frame int result = av_seek_frame(formatContext, streamIndex, timestamp, AVSEEK_FLAG_BACKWARD); if (result < 0) { - NSLog(@"av_seek_frame failed: %d", result); + os_log_error(ZENLogMedia(), "av_seek_frame failed: %{public}s (%d)", av_err2str(result), result); return NO; } @@ -130,7 +131,7 @@ - (BOOL)renderRawFrame:(AVFrame *)frame AVPacket *packet = av_packet_alloc(); if (!packet) { - NSLog(@"av_packet_alloc failed"); + os_log_error(ZENLogMedia(), "av_packet_alloc failed"); return NO; } @@ -157,7 +158,7 @@ - (BOOL)renderRawFrame:(AVFrame *)frame // AVERROR_EOF only means the stream ended without another frame if (result < 0 && result != AVERROR_EOF) { - NSLog(@"Decoding a frame failed: %d", result); + os_log_error(ZENLogMedia(), "Decoding a frame failed: %{public}s (%d)", av_err2str(result), result); } return (result >= 0); } @@ -223,10 +224,10 @@ - (BOOL)resizeRawFrame:(AVFrame **)frame success = YES; } else { - NSLog(@"sws_scale_frame failed: %d", result); + os_log_error(ZENLogMedia(), "sws_scale_frame failed: %{public}s (%d)", av_err2str(result), result); } } else { - NSLog(@"av_frame_get_buffer failed: %d", result); + os_log_error(ZENLogMedia(), "av_frame_get_buffer failed: %{public}s (%d)", av_err2str(result), result); } av_frame_free(&frameToFree); diff --git a/CoreZen/Media/MPV/MPVPlayerController.m b/CoreZen/Media/MPV/MPVPlayerController.m index 47a75b5..d066fa6 100644 --- a/CoreZen/Media/MPV/MPVPlayerController.m +++ b/CoreZen/Media/MPV/MPVPlayerController.m @@ -9,6 +9,7 @@ #import "MPVFunctions.h" #import "MPVConstants.h" #import "MediaPlayer+Private.h" +#import "Log.h" #import @@ -88,7 +89,7 @@ - (instancetype)initWithPlayer:(ZENMediaPlayer *)player { // Create MPV handle (initialization happens after configuration) _mpvHandle = mpv_create(); if (!_mpvHandle) { - NSLog(@"ERROR: mpv_create() failed"); + os_log_error(ZENLogPlayer(), "mpv_create failed"); return nil; } @@ -223,10 +224,15 @@ - (ZENMPVCommandResult)mpvSeek:(double)target flags:(const char *const)flags { if (error >= 0) { return ZENMPVCommandResultAccepted; } - NSLog(@"mpv seek %s %s failed: %s", targetArgument, flags, mpv_error_string(error)); // mpv reports a seek before the file has loaded as a generic command error, // and a bad target such as NaN as an invalid parameter - return (error == MPV_ERROR_COMMAND) ? ZENMPVCommandResultNotReady : ZENMPVCommandResultRejected; + if (error == MPV_ERROR_COMMAND) { + // The player tries it again once the file has loaded + os_log_info(ZENLogPlayer(), "mpv isn't ready for seek %{public}s %{public}s: %{public}s", targetArgument, flags, mpv_error_string(error)); + return ZENMPVCommandResultNotReady; + } + os_log(ZENLogPlayer(), "mpv rejected seek %{public}s %{public}s: %{public}s", targetArgument, flags, mpv_error_string(error)); + return ZENMPVCommandResultRejected; } - (ZENMPVCommandResult)seekBySeconds:(double)seconds { @@ -264,7 +270,12 @@ - (void)mpvHandleEvents { switch (eid) { case MPV_EVENT_LOG_MESSAGE: { mpv_event_log_message *msg = event->data; - NSLog(@"MPV_EVENT_LOG_MESSAGE: [%s] <%s> %s", msg->prefix, msg->level, msg->text); + // Fatal and error messages are errors, and warnings are worth noticing. The + // text can name the file, so it's private. (The log drops its final newline.) + os_log_type_t type = (msg->log_level <= MPV_LOG_LEVEL_ERROR) ? OS_LOG_TYPE_ERROR + : (msg->log_level <= MPV_LOG_LEVEL_WARN) ? OS_LOG_TYPE_DEFAULT + : OS_LOG_TYPE_INFO; + os_log_with_type(ZENLogPlayer(), type, "mpv [%{public}s] %{public}s: %s", msg->prefix, msg->level, msg->text); break; } case MPV_EVENT_START_FILE: { @@ -340,13 +351,9 @@ - (void)mpvHandleEvents { } } - // mpv_event_property *property = event->data; - // NSLog(@"MPV_EVENT_PROPERTY_CHANGE (%llu): %s", observerID, property->name); - if (propertyName && valueNode && observerID == self.identifier) { if (zen_mpv_compare_strings(kMPVProperty_pause, propertyName)) { BOOL paused = (BOOL)valueNode->u.flag; - // NSLog(@"Paused: %d", paused); dispatch_async(dispatch_get_main_queue(), ^{ self.player.paused = paused; }); @@ -370,7 +377,6 @@ - (void)mpvHandleEvents { // system representation, so convert it back the same way if (valueNode->format == MPV_FORMAT_STRING && valueNode->u.string) { NSURL *url = [NSURL fileURLWithFileSystemRepresentation:valueNode->u.string isDirectory:NO relativeToURL:nil]; - // NSLog(@"Path: %@", url); dispatch_async(dispatch_get_main_queue(), ^{ self.player.fileURL = url; }); @@ -384,7 +390,7 @@ - (void)mpvHandleEvents { break; } case MPV_EVENT_QUEUE_OVERFLOW: { - NSLog(@"WARNING: mpv's event queue overflowed, so some of its events were lost"); + os_log(ZENLogPlayer(), "mpv's event queue overflowed, so some of its events were lost"); break; } default: { diff --git a/CoreZen/Media/MPV/MPVRenderController.m b/CoreZen/Media/MPV/MPVRenderController.m index 311dcfb..8b71014 100644 --- a/CoreZen/Media/MPV/MPVRenderController.m +++ b/CoreZen/Media/MPV/MPVRenderController.m @@ -10,6 +10,7 @@ #import "MPVFunctions.h" #import "MediaPlayer+Private.h" #import "MediaPlayerView+Private.h" +#import "Log.h" @import Darwin.POSIX.pthread; @import OpenGL.GL; @@ -111,7 +112,7 @@ - (void)initRenderContext { int error = mpv_render_context_create(&_mpvRenderContext, self.mpvHandleFromPlayerView, renderParams); if (error < 0) { - NSLog(@"ERROR: mpv_render_context_create failed: %d", error); + os_log_error(ZENLogPlayer(), "mpv_render_context_create failed: %{public}s (%d)", mpv_error_string(error), error); [self.playerView unlockViewContext]; return; } diff --git a/CoreZen/Media/MediaFile.m b/CoreZen/Media/MediaFile.m index 2beb9d4..a4f0d19 100644 --- a/CoreZen/Media/MediaFile.m +++ b/CoreZen/Media/MediaFile.m @@ -9,6 +9,7 @@ #import "LibAVInfoController.h" #import "LibAVRenderController.h" #import "ObjectCache.h" +#import "Log.h" ZENObjectCache *ZENGetWeakMediaFileCache(void) { static ZENObjectCache *cache = nil; @@ -49,7 +50,7 @@ - (instancetype)initWithURL:(NSURL *)url { - (void)dealloc { if (!self.terminated) { - NSLog(@"WARNING: ZENMediaFile -terminateMediaFile was not called before -dealloc (%@)", self.fileURL); + os_log(ZENLogMedia(), "terminateMediaFile wasn't called before the media file for %@ was released", self.fileURL.path); [self terminateMediaFile]; } } @@ -61,7 +62,7 @@ + (instancetype)mediaFileWithURL:(NSURL *)url { - (void)terminateMediaFile { if (self.terminated) { - NSLog(@"WARNING: ZENMediaFile -terminateMediaFile called more than once (%@)", self.fileURL); + os_log(ZENLogMedia(), "terminateMediaFile was called more than once for %@", self.fileURL.path); } else { // mediaInfoController owns the lazily created frameRenderController // and will terminate it here if it was ever created diff --git a/CoreZen/Media/MediaPlayer.m b/CoreZen/Media/MediaPlayer.m index a4a0bf6..9610709 100644 --- a/CoreZen/Media/MediaPlayer.m +++ b/CoreZen/Media/MediaPlayer.m @@ -9,6 +9,7 @@ #import "MediaPlayerView+Private.h" #import "MPVPlayerController.h" #import "ObjectCache.h" +#import "Log.h" ZENObjectCache *ZENGetWeakMediaPlayerCache(void) { static ZENObjectCache *cache = nil; @@ -73,14 +74,14 @@ - (instancetype)init { - (void)dealloc { if (!self.terminated) { - NSLog(@"WARNING: ZENMediaPlayer -terminatePlayer was not called before -dealloc (%@)", self.fileURL); + os_log(ZENLogPlayer(), "terminatePlayer wasn't called before the player for %@ was released", self.fileURL.path); [self terminatePlayer]; } } - (void)terminatePlayer { if (self.terminated) { - NSLog(@"WARNING: ZENMediaPlayer -terminatePlayer called more than once (%@)", self.fileURL); + os_log(ZENLogPlayer(), "terminatePlayer was called more than once for %@", self.fileURL.path); } else { if (self.playerView) { [self.playerView terminatePlayerView]; diff --git a/CoreZen/Queue/WorkQueue.m b/CoreZen/Queue/WorkQueue.m index b612ebc..7a257af 100644 --- a/CoreZen/Queue/WorkQueue.m +++ b/CoreZen/Queue/WorkQueue.m @@ -6,6 +6,7 @@ // #import "WorkQueue+Private.h" +#import "Log.h" #import @@ -178,7 +179,7 @@ - (ZENWorkQueueToken *)async:(ZENWorkQueueCancelBlock)block { - (void)terminate:(ZENWorkQueueBlock)block { if (![self.terminateToken terminate]) { - NSLog(@"WARNING: ZENWorkQueue %@ terminated more than once", self.label); + os_log(ZENLogGeneral(), "Work queue %@ was terminated more than once", self.label); block(); return; } diff --git a/CoreZenTests/Classes/TestLog.h b/CoreZenTests/Classes/TestLog.h new file mode 100644 index 0000000..8f78234 --- /dev/null +++ b/CoreZenTests/Classes/TestLog.h @@ -0,0 +1,22 @@ +// +// TestLog.h +// CoreZenTests +// + +#import + +@import OSLog; + +NS_ASSUME_NONNULL_BEGIN + +// Everything this process has logged since date, oldest first, CoreZen's messages +// and others'. Reading the log takes a second or two, so a test reads it once. +NSArray *ZENLogEntriesSince(NSDate *date); + +// The entries CoreZen logged in category, at level, whose message contains text +NSArray *ZENCoreZenLogEntries(NSArray *entries, + NSString *category, + OSLogEntryLogLevel level, + NSString *text); + +NS_ASSUME_NONNULL_END diff --git a/CoreZenTests/Classes/TestLog.m b/CoreZenTests/Classes/TestLog.m new file mode 100644 index 0000000..2d7fd8c --- /dev/null +++ b/CoreZenTests/Classes/TestLog.m @@ -0,0 +1,38 @@ +// +// TestLog.m +// CoreZenTests +// + +#import "TestLog.h" + +NSArray *ZENLogEntriesSince(NSDate *date) { + NSError *error = nil; + OSLogStore *store = [OSLogStore storeWithScope:OSLogStoreCurrentProcessIdentifier error:&error]; + if (!store) { + NSLog(@"Couldn't open this process's log: %@", error); + return @[]; + } + OSLogEnumerator *entries = [store entriesEnumeratorWithOptions:0 + position:[store positionWithDate:date] + predicate:nil + error:&error]; + NSMutableArray *logEntries = [NSMutableArray array]; + for (OSLogEntry *entry in entries) { + // The position is approximate, so it can start a little early + if ([entry isKindOfClass:[OSLogEntryLog class]] && [entry.date compare:date] != NSOrderedAscending) { + [logEntries addObject:(OSLogEntryLog *)entry]; + } + } + return logEntries; +} + +NSArray *ZENCoreZenLogEntries(NSArray *entries, + NSString *category, + OSLogEntryLogLevel level, + NSString *text) { + NSIndexSet *matches = [entries indexesOfObjectsPassingTest:^BOOL(OSLogEntryLog *entry, NSUInteger index, BOOL *stop) { + return [entry.subsystem isEqualToString:@"com.zdnelson.CoreZen"] && [entry.category isEqualToString:category] && + entry.level == level && [entry.composedMessage containsString:text]; + }]; + return [entries objectsAtIndexes:matches]; +} diff --git a/CoreZenTests/DatabaseTests.m b/CoreZenTests/DatabaseTests.m index ccd6eca..58ffb9f 100644 --- a/CoreZenTests/DatabaseTests.m +++ b/CoreZenTests/DatabaseTests.m @@ -11,6 +11,7 @@ #import "TestDTO.h" #import "TestTable.h" +#import "TestLog.h" #import "DatabaseQueue+Private.h" #import @@ -888,6 +889,27 @@ - (void)testForeignKeysAreNotEnforcedByDefault { [queue shutdown]; } +#pragma mark - Logging + +- (void)testDatabaseLogsUnderCoreZensSubsystem { + NSDate *start = [NSDate date]; + ZENDatabaseQueue *queue = [ZENDatabaseQueue databaseQueueWithURL:[self temporaryDatabaseURL]]; + [queue fetchSync:^(ZENDatabase *database) { + XCTAssertNil([database executeQuery:@"SELECT name FROM no_such_table;"]); + }]; + [queue shutdown]; + NSArray *entries = ZENLogEntriesSince(start); + + // Something routine is info, and a failure is an error, with the SQL that failed + XCTAssertEqual(ZENCoreZenLogEntries(entries, @"Database", OSLogEntryLogLevelInfo, @"Opening the database at").count, 1u); + NSString *failure = @"A statement failed: no such table: no_such_table\nSELECT name FROM no_such_table;"; + XCTAssertEqual(ZENCoreZenLogEntries(entries, @"Database", OSLogEntryLogLevelError, failure).count, 1u); + + // FMDB doesn't log the failure a second time + NSPredicate *fmdbErrors = [NSPredicate predicateWithFormat:@"composedMessage BEGINSWITH 'DB Error'"]; + XCTAssertEqual([entries filteredArrayUsingPredicate:fmdbErrors].count, 0u); +} + #pragma mark - Trace Execution // ZENDatabase keeps its FMDatabase private, so these read FMDB's setting by key path diff --git a/CoreZenTests/MediaPlayerTests.m b/CoreZenTests/MediaPlayerTests.m index fa86897..3bf75fe 100644 --- a/CoreZenTests/MediaPlayerTests.m +++ b/CoreZenTests/MediaPlayerTests.m @@ -8,6 +8,8 @@ @import CoreAudio; @import CoreZen; +#import "TestLog.h" + static const NSTimeInterval kPlayerTimeout = 10.0; // Without a player view mpv has no video output, so it can only play the @@ -234,17 +236,32 @@ - (void)testMissingFileFails { XCTAssertTrue([error.localizedDescription containsString:@"missing.mp4"], @"%@", error.localizedDescription); } -- (void)testFileThatIsNotVideoFails { +// A file of random bytes, with a video's name +- (NSURL *)fileThatIsNotVideo { NSURL *url = [self.temporaryDirectory URLByAppendingPathComponent:@"not-a-video.mp4"]; uint8_t bytes[4096]; arc4random_buf(bytes, sizeof(bytes)); XCTAssertTrue([[NSData dataWithBytes:bytes length:sizeof(bytes)] writeToURL:url atomically:YES]); + return url; +} - [self.player loadFileURL:url]; +- (void)testFileThatIsNotVideoFails { + [self.player loadFileURL:[self fileThatIsNotVideo]]; [self waitForStatus:ZENMediaPlayerStatusFailed]; XCTAssertNotNil(self.player.error); } +- (void)testMpvErrorsAreLoggedAsErrors { + NSDate *start = [NSDate date]; + [self.player loadFileURL:[self fileThatIsNotVideo]]; + [self waitForStatus:ZENMediaPlayerStatusFailed]; + + // mpv logs why it couldn't play the file, at its error level. The reason + // itself is private, so it can show as . + NSArray *errors = ZENCoreZenLogEntries(ZENLogEntriesSince(start), @"Player", OSLogEntryLogLevelError, @"mpv [cplayer] error: "); + XCTAssertGreaterThan(errors.count, 0u); +} + - (void)testReplacingFileGoesStraightToLoading { // mpv reports the file it's replacing as stopped after it starts on the next // one, which mustn't make the player look stopped while the next one loads diff --git a/README.md b/README.md index 55306ae..2d7fa36 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,14 @@ See [`Scripts/update_instructions.md`](https://github.com/znelson/CoreZen/blob/m The framework bundles both in its `Resources` folder, as `FMDB-LICENSE.txt` and `licenses/`, so an app that embeds it ships them. Such an app should point to them, for example from its About window, and credit FreeType there as its license asks; the credit line is at the end of `NOTICES.md`. +### Logging + +CoreZen logs to the unified log, under the subsystem `com.zdnelson.CoreZen`, in the categories Database, Domain, Media, Player and General. Failures are errors, harmless surprises like a method called twice are default messages, and routine events like a database opening are info. Paths, URLs and mpv's messages are private, since they can name the user's files. To watch them: + +``` +log stream --level info --predicate 'subsystem == "com.zdnelson.CoreZen"' +``` + ## What's In CoreZen.framework? `CoreZen` has three parts: a persistence layer for a domain model stored in SQLite, media playback and frame rendering built on mpv and FFmpeg, and smaller AppKit and Foundation helpers. The public headers say which values can be `nil`.