OSLog is a unified logging system for the reading of historical data.

Posts under OSLog tag

166 Posts

Post

Replies

Boosts

Views

Activity

Can I access system logs from Swift (I want logs for previous runs of my application)
Hi folks, For accessing the logs, I’m using OSLogStore object. I want to be able to read logs from any previous run of my application. I can of course do this: // Open the log store. var logStore = try OSLogStore(scope: .currentProcessIdentifier) But this only allows me to retrieve logs from my current running process. I can also do this: // Open the log store. var logStore = try OSLogStore(scope: .system) But this only works if my App Sandbox entitlement is false. I tried disabling the sandbox, and I was able to get to all the logs (which is good) but according to this page: https://developer.apple.com/documentation/security/app_sandbox/ it says: To distribute a macOS app through the Mac App Store, you must enable the App Sandbox capability Since we are planning on distributing our app on the store, this presents a big problem for me. (I didn't try submitting to TestFlight to see if it's really the case). I don’t know if there are exclusions or ways around this – I don’t see an entitlement that I can add which would allow access to the logs. Does anyone know a way around this? Thanks, David
2
0
1.8k
Jan ’24
/usr/bin/log sometimes does not work through NSTask
Our application (which happens to run in an admin account, thus there's no problem authenticating) collects logs calling /usr/bin/log through NSTask. Usually this works all right, but sometimes all we get is the header Timestamp Thread Type Activity PID TTL and nothing else. The tool finishes with a zero result code, we get nothing on stderr and just the header above on stdout, with a proper EOF (as determined by a zero-length availableData read from an NSFileHandle through the stdout pipe). At the same moment, if the /usr/bin/log tool is run manually in a Terminal window with precisely the same arguments in the same user account the application runs in, we get the logs all right. Any idea what might be the culprit and how to fix the problem? Thanks!
0
0
774
Jan ’24
os_log wrapper crashed when using "%s"
I am trying to wrap os_log for logging in my iOS app like so: import Foundation import OSLog enum LogCategory: String, CaseIterable { case viewCycle case tracking case api } struct Log { private static let logs = { return LogCategory.allCases .reduce(into: [LogCategory: OSLog]()) { dict, category in dict[category] = OSLog(subsystem: Bundle.main.bundleIdentifier ?? "BIMB", category: category.rawValue) } }() static func debug(category: LogCategory, message: StaticString, _ args: CVarArg...) { logImpl(category: category, message: message, type: .debug, args) } static func info(category: LogCategory, message: StaticString, _ args: CVarArg...) { logImpl(category: category, message: message, type: .info, args) } static func notice(category: LogCategory, message: StaticString, _ args: CVarArg...) { logImpl(category: category, message: message, type: .default, args) } static func warning(category: LogCategory, message: StaticString, _ args: CVarArg...) { logImpl(category: category, message: message, type: .default, args) } static func error(category: LogCategory, message: StaticString, _ args: CVarArg...) { logImpl(category: category, message: message, type: .error, args) } static func critical(category: LogCategory, message: StaticString, _ args: CVarArg...) { logImpl(category: category, message: message, type: .fault, args) } private static func logImpl(category: LogCategory, message: StaticString, type: OSLogType, _ args: CVarArg...) { guard let log = logs[category] else { return } os_log(message, log: log, type: type, args) } } The problem is if I did this: Log.debug(category: .tracking, message: "Device ID: %s.", UIDevice.current.identifierForVendor?.uuidString ?? "unknown") it always crashed with this error: 2023-12-13 12:33:35.173798+0700 bimb-authenticate-ios[62740:928633] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Swift.__SwiftDeferredNSArray UTF8String]: unrecognized selector sent to instance 0x600000dcbbc0' But if I just do it with os_log like this: os_log("Device ID: %s.", log: OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "tracking"), type: .debug, UIDevice.current.identifierForVendor?.uuidString ?? "unknown") it worked fine. Also if I changed %@ in my wrapper instead, it didn't crash, but the idfv is shown inside a pair of brackets like this: Device ID: ( "C0F906C8-CD73-44F6-86A1-A587248680D3" ).` But with os_log it is shown normally like this: Device ID: C0F906C8-CD73-44F6-86A1-A587248680D3. Can you tell me what's wrong here? And how do I fix this? Thanks. NOTE: This is using os_log since the minimum version is iOS 11. I don't know why people advising me with using Logger instead.
1
0
1k
Dec ’23
OSLog Line Numbers & Source File Only Shown On Mouse Hover in Tiny Text?
For awhile I've wrapped OSLog in my own macros to include the line number and source file the logging statement originates from in debug mode because OSLog didn't include that info in console output (until recently). Now I noticed the source code file and line number of the logging statement isn't being shown (I have all the metadata switches turned on in Xcode's console "Metadata Options" popover). Then I realized it is being shown, only on mouse hover over the logging statement in very tiny text. The text is barely readable (on mouse hover). Why would viewing the line number require me to move the mouse cursor over a logging statement? It doesn't look pretty at all (hiding information behind mouse hover) and even if it did look pretty, this is the console for programmers and we don't care about such nonsense.
1
0
1.1k
Dec ’23
NSLog unreliable in Xcode 15 Console
I'm finding that in Xcode 15, NSLog statements (from Objective-C, in this case) will sometimes appear in Xcode's Console and sometimes will not. This is making it difficult to debug using our existing logging, which for our REST API requests and responses has been working well for about ten years and is a tough thing to lose. Is there any way I can restore reliable handling of NSLog in Xcode 15's Console without having to rewrite all (over 200) of our uses of NSLog to use OSLog? Note: I am aware that Xcode 15's Console sometimes takes more than 30 seconds to start tracking app output, but it appears that in some cases the content of individual NSLog statements never will appear. (If this 30 second delay is news to anyone, it may be related to a spam of identical warnings that are okay which occur on launch of our app. I have suspected that Xcode 15 just gets a bit flustered with identical messages and gives up for a bit.) Thank you!
6
0
3.8k
Dec ’23
How to disable dimming on the screen, and print os_log on the content screen
I have created an iOS .ipa file to run some tests, and all the test cases have os_log implemented for tracing. However, there is an issue; my tests take over 20 seconds to run, and the screen starts to dim. Consequently, the execution stops. Once I reactivate the screen, the tests resume. I added [UIApplication.sharedApplication setIdleTimerDisabled:YES]; to the code, but it doesn't resolve the problem. I've used os_log to trace all the test case results. I wonder if it's possible to display all the os_log messages from runTest on the app main screen as well. int main(int argc, char** argv) { //Separate thread to runTest, os_log implemented there std::thread thread_obj(runTests, argc, argv); int applicationReturn; @autoreleasepool { [UIApplication.sharedApplication setIdleTimerDisabled:YES]; applicationReturn = UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } thread_obj.join(); [UIApplication.sharedApplication setIdleTimerDisabled:NO]; return applicationReturn; }
3
0
898
Nov ’23
os_log private not shown in Ventura
Lately, I've switched from NSLog to the new os_log. My problem is, whatever I try, I can't see the private values in my 13.6 (22G120). My test line is trivial os_log(OS_LOG_DEFAULT,"private shown: %@", [NSString stringWithFormat:@"OK"]); and it prints (both in Xcode and in Console) private shown: <private> I did install in Settings the appropriate profile (as found here, copied down, changed just my company info) — in vain, it did not help, not even after restarting my computer. For the record, the profile is shown below. Can anybody see what am I doing wrong and why it does not work? Thanks! <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>ConsentText</key> <dict> <key>default</key> <string>This will enable showing private strings and data in Unified Logs.</string> </dict> <key>PayloadContent</key> <array> <dict> <key>PayloadDisplayName</key> <string>ManagedClient logging</string> <key>PayloadEnabled</key> <true/> <key>PayloadIdentifier</key> <string>com.apple.system.logging.89AE58D8-0A4A-448B-8AE0-761DEE2D007F</string> <key>PayloadType</key> <string>com.apple.system.logging</string> <key>PayloadUUID</key> <string>89AE58D8-0A4A-448B-8AE0-761DEE2D007F</string> <key>PayloadVersion</key> <integer>1</integer> <key>System</key> <dict> <key>Enable-Private-Data</key> <true/> </dict> </dict> </array> <key>PayloadDescription</key> <string>Allows showing private log messages.</string> <key>PayloadDisplayName</key> <string>Allow Private Logs</string> <key>PayloadIdentifier</key> <string>cz.ocs.enable.private.logs</string> <key>PayloadOrganization</key> <string>OCSoftware</string> <key>PayloadRemovalDisallowed</key> <false/> <key>PayloadType</key> <string>Configuration</string> <key>PayloadUUID</key> <string>529DF49A-6CB3-4DE9-A29F-4C41EC88BFDD</string> <key>PayloadVersion</key> <integer>1</integer> </dict> </plist>
4
0
2k
Nov ’23
Exporting from OSLogStore doesn't respect privacy.
When exporting OSLog entries from OSLogStore, composedMessage doesn't seem to respect the given privacy marker. This feels like a bug to me, but it maybe a case of me holding it wrong. Here's an example: import UIKit import OSLog class ViewController: UIViewController { let logger = Logger(subsystem: "com.example.project", category: "ViewController") override func viewDidLoad() { super.viewDidLoad() logger.info("Top secret number \(42, privacy: .private)") do { let store = try OSLogStore(scope: .currentProcessIdentifier) let postion = store.position(timeIntervalSinceLatestBoot: 1) let logs = try store.getEntries(at: postion) .compactMap { $0 as? OSLogEntryLog } .filter { $0.subsystem == "com.example.project" } .map { $0.composedMessage } // Prints: // Logger: ["Top secret number 42"] print("Logger: \(logs)") } catch { print(error) } } } Is there a more appropriate way to format the text ready for sharing?
2
0
1k
Nov ’23
NSLog no longer sh
I use a macro to do logging: #define LOG(fmt, ...) NSLog((fmt), ##VA_ARGS); which means I can write code like: LOG(@"radius=%.1f", fRadius) Up until Xcode 15 the %.1f would be respected and display fRadius to one decimal place. But since Xcode 15 it seems to ignore that and just display all decimal places regardless. Anyone know why, and how to fix that?
4
1
993
Nov ’23
Can I use OSLogStore to access logs from earlier runs of my app?
I understand that in iOS 15 and macOS Monterey, I can easily access the log system to get log entries for my app like this: let store = try OSLogStore(scope: .currentProcessIdentifier) I can then query store for the log entries. However, as it says right in the name, the store is only for current process, i.e current run of my app. When I try to get entries, I only get entries from the current run, even if I specify an earlier time like this: guard let positionDate = Calendar.current.date(byAdding: .day, value: -7, to: Date()) else { return } let position = store.position(date: positionDate) let predicate = NSPredicate(format: "subsystem == 'com.exampl.emyAppSubsystem'") let entries = try store.getEntries(with: [], at: position, matching: predicate) for entry in entries { print("Entry: \(entry.date) \(entry.composedMessage)") } Is there any way to access log entries for earlier runs of my app, e.g from days or weeks ago? Either on macOS or iOS?
7
0
4.6k
Nov ’23
Silencing OS subsystem signposts on iOS
Environment Context: iOS 17.0 Simulator Xcode 15.0 In the above environment, I'm noticing in Instruments that the OS subsystem com.apple.VectorKit is emitting os_signpost events at a rate of ~2.8 events/ms. This large amount of data logging seems to be triggering warnings of: 'Data stream: 1 log/signpost messages lost due to high rates' ...when trying to capture other system logging data. (In the attached screenshot, notice the warning sign icons right outside the selected time series.) This is preventing me from being able to successfully log my own signpost data and profile my application. As well, this subsystem's data is unnecessary for my purposes and distracting. I have tried to disable logging for this subsystem in the Simulator by running the following from the macOS host: % xcrun simctl spawn booted log config --subsystem com.apple.VectorKit --mode level:off ...and confirmed it with: % xcrun simctl spawn booted log config --subsystem com.apple.VectorKit --status Mode for 'com.apple.VectorKit' OFF PERSIST_OFF ...however, when running Instruments after the above output, this data does not actually get disabled. How can I disable this subsystem's logging? Feedback Assistant report: FB13292000
1
0
869
Oct ’23
os_log crashing in MacOS 14 Sonoma
minimum is to create an os_log once in the parent, then, after fork, use an existing os_log instance or create a new one. Here's my reproduction sample. It looks like an OS bug, So what is the workaround till its solved and releases. #include <os/log.h> #include <stdio.h> #include <errno.h> #define USE_SWIFT_LOGGER 0 // set to 1 to use Logger() instead of os_log() #define USE_SHARED_LOG 0 // set to 1 to use a shared os_log instance instead of allocating one for each os_log() call #if USE_SWIFT_LOGGER // log messages using Swift's Logger class instead of calling os_log_... directly #include "forktest-Swift.h" #define LOG(msg) log_using_logger([NSString stringWithUTF8String:msg]) const char * logMethod = "Swift's Logger"; #elif USE_SHARED_LOG // use a shared os_log instance for all log messages static os_log_t log = os_log_create("com.ivanti.forktest", "foo"); #define LOG(msg) os_log_debug(log, msg) const char * logMethod = "shared log"; #else // create a new os_log instance for each log message #define LOG(msg) os_log_debug(os_log_create("com.ivanti.forktest", "foo"), msg) const char * logMethod = "new log instance for each message"; #endif static void forkTest() { int pid = fork(); if (pid < 0) { fprintf(stderr, "fork failed: %s\n", strerror(errno)); exit(1); } else if (pid == 0) { printf("in child process...\n"); LOG("in child process..."); printf("child process done\n"); } else { printf("child process pid: %d\n", pid); } } int main(int arc, const char ** argv) { printf("Log method: %s\n", logMethod); LOG("entering main..."); forkTest(); LOG("leaving main..."); return 0; }
3
0
1.1k
Oct ’23
os_log Unified Logging not anymore tide to stderr in iOS 17?
Currently I have a setup which duplicates the stderr STDERR_FILENO pipe into a separate one. Then by setting up a readabilityHandler (on the new Pipe) I can capture the logged data and either store it inside a File, adjust/modify the data etc. Since iOS 17 this is not possible anymore (previous versions worked iOS 16)? I cannot find any documentation on why or what changed on the os_log side. private func setupPipes() { inputPipe.fileHandleForReading.readabilityHandler = { [weak self] handler in guard let strongSelf = self else { return } let data = handler.availableData strongSelf.queue.async(flags: .barrier) { guard let fileHandle = try? FileHandle(forWritingTo: strongSelf.filePath) else { return } fileHandle.seekToEndOfFile() fileHandle.write(data) try? fileHandle.close() } strongSelf.outputPipe.fileHandleForWriting.write(data) } dup2(STDERR_FILENO, outputPipe.fileHandleForWriting.fileDescriptor) dup2(inputPipe.fileHandleForWriting.fileDescriptor, STDERR_FILENO) }
8
0
2.4k
Oct ’23
OSLog in Swift macro doesn't persist original file/line number
I need to log to OSLog and into a file in parallel (due to OSLogStore not being able to provide old logs (FB13191608)). In Objective-C I can accomplish this with a macro using __FILE__ and __LINE__ in the macro implementation which still reference the position in the original code. I tried to create a Swift macro to make this work from Swift. However, log() takes the file and line number of the macro definition file instead of the position in the calling code. So when I click on the metadata link, I'm taken to the macro instead of the calling location. Is there any solution to that? #file and #line are correctly set in the macro but there’s no way to specify file and line number to the log() function (FB13204310).
5
0
1.7k
Oct ’23
Xcode 15 Structured log always redacting <private> strings
This is the opposite of https://developer.apple.com/forums/thread/726354 really, and I've read both of the Recording Private Data in the System Log and Your Friend, the System Log threads, but I still can't solve my problem. The structured log always seems to redact private values to If I set OS_ACTIVITY_DT_MODE=1 in my environment (it's not set anymore by Xcode, at least not for my projects) then the logs are unredacted as I would expect, but structured logging is turned off. Is there a way to have the unredacted strings in the log when the app is running under Xcode and still get the nice structured log output? I don't want the unredacted logs when the app runs normally, but I'd like them under Xcode. At the moment, I'm having to explicitly make everything public, which defeats the whole purpose of the system.
5
0
2.7k
Oct ’23
Structured logging with emoji or objectdescription
When running the code below, only the first entry gets logged. Structured logging seems not to work when there are emoticons or object descriptions in the message. Is this by design? let logger = Logger(subsystem: "TestSystem", category: "TestCategory") logger.log("👍") // Result = 👍 let someEmoji:String = "👎" logger.log("\(someEmoji)") // Result = empty log line let someObjectDescription:String = String(describing:self) logger.log("\(someObjectDescription)") // Result = empty log line
3
0
1.3k
Oct ’23
How to use a freestanding macro with OSLog
I'm trying to create a macro that adds the file and line to a string that I use with OSLog. However, I only get warnings that either the String is not in the format of OSLogMessage or not an interpolated string. The Macro looks like this at the moment: public struct LocMacro: ExpressionMacro { public static func expansion( of node: some FreestandingMacroExpansionSyntax, in context: some MacroExpansionContext ) -> ExprSyntax { guard let argument = node.argumentList.first?.expression.as(StringLiteralExprSyntax.self)?.segments else { fatalError("compiler bug: the macro does not have any StringLiteralExprSyntax arguments.") } guard let file = context.location(of: node)?.file.as(StringLiteralExprSyntax.self)?.segments, let line = context.location(of: node)?.line.as(IntegerLiteralExprSyntax.self) else { fatalError("compiler bug: the macro is unable to retrieve file and line numbers") } return "\"\(argument) - \(file):\(line)\"" } } and here the exposed macro: @freestanding(expression) public macro loc(_ text: String) -> String = #externalMacro(module: "LxoMacrosMacros", type: "LocMacro") I want to use it like this: import LxoMacros import OSLog let logger = Logger() let someNumber = 17 logger.debug(#loc("Working with some number \(someNumber)")) which should expand to: logger.debug("Working with some number \(someNumber) - MyFile.swift:8") Is there a way to change the macro so that it returns the correct type? When expending the macro it does show the right string, which works with print() and so on, but assuming since the Logger uses some sort of compiler check as well, it doesn't seem to work together as expected.
2
0
1.2k
Oct ’23
os_log doesn't log file/line to Xcode 15 console for C++ code
Since this api requires &__dso_handle instead of the standard file/line/func, I had to modify my entire log system to pass this down from the macro call sites. I have many callbacks that typically just forward data from other C++ libraries that never supply a dso_handle. so it's great how this logging system breaks most logger systems and doesn't have a warning level to match fault/error. I have the forwarded threadName, timestamp, etc and no where to store that in os_log. syslog was more powerful and clear than os_log, but I'm sure it's now too late to head down a more reasonable path.. So I pass the &__dso_handle all the way to the log command and hand it into the macro #define my_os_log_with_type(dso, log, type, format, ...) __extension__({ \ os_log_t _log_tmp = (log); \ os_log_type_t _type_tmp = (type); \ if (os_log_type_enabled(_log_tmp, _type_tmp)) { \ OS_LOG_CALL_WITH_FORMAT(_os_log_impl, \ ((void*)dso, _log_tmp, _type_tmp), format, ##__VA_ARGS__); \ } \ }) Logger.mm // This doesn't work, logging the dso from the callsite. No file/line. my_os_log_with_type(entry.dso, os_log_create( "com.foo", entry.tag), logLevel(entry.level)), "%{public}s", text ); // This does work, but who wants to jump to the forwarding log implementation? os_log_with_type(os_log_create( "com.foo", entry.tag), logLevel(entry.level)), "%{public}s", text );
7
0
2.2k
Sep ’23
Can I access system logs from Swift (I want logs for previous runs of my application)
Hi folks, For accessing the logs, I’m using OSLogStore object. I want to be able to read logs from any previous run of my application. I can of course do this: // Open the log store. var logStore = try OSLogStore(scope: .currentProcessIdentifier) But this only allows me to retrieve logs from my current running process. I can also do this: // Open the log store. var logStore = try OSLogStore(scope: .system) But this only works if my App Sandbox entitlement is false. I tried disabling the sandbox, and I was able to get to all the logs (which is good) but according to this page: https://developer.apple.com/documentation/security/app_sandbox/ it says: To distribute a macOS app through the Mac App Store, you must enable the App Sandbox capability Since we are planning on distributing our app on the store, this presents a big problem for me. (I didn't try submitting to TestFlight to see if it's really the case). I don’t know if there are exclusions or ways around this – I don’t see an entitlement that I can add which would allow access to the logs. Does anyone know a way around this? Thanks, David
Replies
2
Boosts
0
Views
1.8k
Activity
Jan ’24
How to reuse console filter when open a new Windows tab?
Love the new console. but every time I open a new tab, it clear the console filter. I have some info level log that is from Bluetooth and other. I want to collect those logs but I don't want those in the Console. How can I keep the filter as copied to new window tab, like the search panel.
Replies
0
Boosts
1
Views
714
Activity
Jan ’24
/usr/bin/log sometimes does not work through NSTask
Our application (which happens to run in an admin account, thus there's no problem authenticating) collects logs calling /usr/bin/log through NSTask. Usually this works all right, but sometimes all we get is the header Timestamp Thread Type Activity PID TTL and nothing else. The tool finishes with a zero result code, we get nothing on stderr and just the header above on stdout, with a proper EOF (as determined by a zero-length availableData read from an NSFileHandle through the stdout pipe). At the same moment, if the /usr/bin/log tool is run manually in a Terminal window with precisely the same arguments in the same user account the application runs in, we get the logs all right. Any idea what might be the culprit and how to fix the problem? Thanks!
Replies
0
Boosts
0
Views
774
Activity
Jan ’24
os_log wrapper crashed when using "%s"
I am trying to wrap os_log for logging in my iOS app like so: import Foundation import OSLog enum LogCategory: String, CaseIterable { case viewCycle case tracking case api } struct Log { private static let logs = { return LogCategory.allCases .reduce(into: [LogCategory: OSLog]()) { dict, category in dict[category] = OSLog(subsystem: Bundle.main.bundleIdentifier ?? "BIMB", category: category.rawValue) } }() static func debug(category: LogCategory, message: StaticString, _ args: CVarArg...) { logImpl(category: category, message: message, type: .debug, args) } static func info(category: LogCategory, message: StaticString, _ args: CVarArg...) { logImpl(category: category, message: message, type: .info, args) } static func notice(category: LogCategory, message: StaticString, _ args: CVarArg...) { logImpl(category: category, message: message, type: .default, args) } static func warning(category: LogCategory, message: StaticString, _ args: CVarArg...) { logImpl(category: category, message: message, type: .default, args) } static func error(category: LogCategory, message: StaticString, _ args: CVarArg...) { logImpl(category: category, message: message, type: .error, args) } static func critical(category: LogCategory, message: StaticString, _ args: CVarArg...) { logImpl(category: category, message: message, type: .fault, args) } private static func logImpl(category: LogCategory, message: StaticString, type: OSLogType, _ args: CVarArg...) { guard let log = logs[category] else { return } os_log(message, log: log, type: type, args) } } The problem is if I did this: Log.debug(category: .tracking, message: "Device ID: %s.", UIDevice.current.identifierForVendor?.uuidString ?? "unknown") it always crashed with this error: 2023-12-13 12:33:35.173798+0700 bimb-authenticate-ios[62740:928633] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Swift.__SwiftDeferredNSArray UTF8String]: unrecognized selector sent to instance 0x600000dcbbc0' But if I just do it with os_log like this: os_log("Device ID: %s.", log: OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "tracking"), type: .debug, UIDevice.current.identifierForVendor?.uuidString ?? "unknown") it worked fine. Also if I changed %@ in my wrapper instead, it didn't crash, but the idfv is shown inside a pair of brackets like this: Device ID: ( "C0F906C8-CD73-44F6-86A1-A587248680D3" ).` But with os_log it is shown normally like this: Device ID: C0F906C8-CD73-44F6-86A1-A587248680D3. Can you tell me what's wrong here? And how do I fix this? Thanks. NOTE: This is using os_log since the minimum version is iOS 11. I don't know why people advising me with using Logger instead.
Replies
1
Boosts
0
Views
1k
Activity
Dec ’23
OSLog Line Numbers & Source File Only Shown On Mouse Hover in Tiny Text?
For awhile I've wrapped OSLog in my own macros to include the line number and source file the logging statement originates from in debug mode because OSLog didn't include that info in console output (until recently). Now I noticed the source code file and line number of the logging statement isn't being shown (I have all the metadata switches turned on in Xcode's console "Metadata Options" popover). Then I realized it is being shown, only on mouse hover over the logging statement in very tiny text. The text is barely readable (on mouse hover). Why would viewing the line number require me to move the mouse cursor over a logging statement? It doesn't look pretty at all (hiding information behind mouse hover) and even if it did look pretty, this is the console for programmers and we don't care about such nonsense.
Replies
1
Boosts
0
Views
1.1k
Activity
Dec ’23
NSLog unreliable in Xcode 15 Console
I'm finding that in Xcode 15, NSLog statements (from Objective-C, in this case) will sometimes appear in Xcode's Console and sometimes will not. This is making it difficult to debug using our existing logging, which for our REST API requests and responses has been working well for about ten years and is a tough thing to lose. Is there any way I can restore reliable handling of NSLog in Xcode 15's Console without having to rewrite all (over 200) of our uses of NSLog to use OSLog? Note: I am aware that Xcode 15's Console sometimes takes more than 30 seconds to start tracking app output, but it appears that in some cases the content of individual NSLog statements never will appear. (If this 30 second delay is news to anyone, it may be related to a spam of identical warnings that are okay which occur on launch of our app. I have suspected that Xcode 15 just gets a bit flustered with identical messages and gives up for a bit.) Thank you!
Replies
6
Boosts
0
Views
3.8k
Activity
Dec ’23
How to disable dimming on the screen, and print os_log on the content screen
I have created an iOS .ipa file to run some tests, and all the test cases have os_log implemented for tracing. However, there is an issue; my tests take over 20 seconds to run, and the screen starts to dim. Consequently, the execution stops. Once I reactivate the screen, the tests resume. I added [UIApplication.sharedApplication setIdleTimerDisabled:YES]; to the code, but it doesn't resolve the problem. I've used os_log to trace all the test case results. I wonder if it's possible to display all the os_log messages from runTest on the app main screen as well. int main(int argc, char** argv) { //Separate thread to runTest, os_log implemented there std::thread thread_obj(runTests, argc, argv); int applicationReturn; @autoreleasepool { [UIApplication.sharedApplication setIdleTimerDisabled:YES]; applicationReturn = UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } thread_obj.join(); [UIApplication.sharedApplication setIdleTimerDisabled:NO]; return applicationReturn; }
Replies
3
Boosts
0
Views
898
Activity
Nov ’23
os_log private not shown in Ventura
Lately, I've switched from NSLog to the new os_log. My problem is, whatever I try, I can't see the private values in my 13.6 (22G120). My test line is trivial os_log(OS_LOG_DEFAULT,"private shown: %@", [NSString stringWithFormat:@"OK"]); and it prints (both in Xcode and in Console) private shown: <private> I did install in Settings the appropriate profile (as found here, copied down, changed just my company info) — in vain, it did not help, not even after restarting my computer. For the record, the profile is shown below. Can anybody see what am I doing wrong and why it does not work? Thanks! <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>ConsentText</key> <dict> <key>default</key> <string>This will enable showing private strings and data in Unified Logs.</string> </dict> <key>PayloadContent</key> <array> <dict> <key>PayloadDisplayName</key> <string>ManagedClient logging</string> <key>PayloadEnabled</key> <true/> <key>PayloadIdentifier</key> <string>com.apple.system.logging.89AE58D8-0A4A-448B-8AE0-761DEE2D007F</string> <key>PayloadType</key> <string>com.apple.system.logging</string> <key>PayloadUUID</key> <string>89AE58D8-0A4A-448B-8AE0-761DEE2D007F</string> <key>PayloadVersion</key> <integer>1</integer> <key>System</key> <dict> <key>Enable-Private-Data</key> <true/> </dict> </dict> </array> <key>PayloadDescription</key> <string>Allows showing private log messages.</string> <key>PayloadDisplayName</key> <string>Allow Private Logs</string> <key>PayloadIdentifier</key> <string>cz.ocs.enable.private.logs</string> <key>PayloadOrganization</key> <string>OCSoftware</string> <key>PayloadRemovalDisallowed</key> <false/> <key>PayloadType</key> <string>Configuration</string> <key>PayloadUUID</key> <string>529DF49A-6CB3-4DE9-A29F-4C41EC88BFDD</string> <key>PayloadVersion</key> <integer>1</integer> </dict> </plist>
Replies
4
Boosts
0
Views
2k
Activity
Nov ’23
Exporting from OSLogStore doesn't respect privacy.
When exporting OSLog entries from OSLogStore, composedMessage doesn't seem to respect the given privacy marker. This feels like a bug to me, but it maybe a case of me holding it wrong. Here's an example: import UIKit import OSLog class ViewController: UIViewController { let logger = Logger(subsystem: "com.example.project", category: "ViewController") override func viewDidLoad() { super.viewDidLoad() logger.info("Top secret number \(42, privacy: .private)") do { let store = try OSLogStore(scope: .currentProcessIdentifier) let postion = store.position(timeIntervalSinceLatestBoot: 1) let logs = try store.getEntries(at: postion) .compactMap { $0 as? OSLogEntryLog } .filter { $0.subsystem == "com.example.project" } .map { $0.composedMessage } // Prints: // Logger: ["Top secret number 42"] print("Logger: \(logs)") } catch { print(error) } } } Is there a more appropriate way to format the text ready for sharing?
Replies
2
Boosts
0
Views
1k
Activity
Nov ’23
NSLog no longer sh
I use a macro to do logging: #define LOG(fmt, ...) NSLog((fmt), ##VA_ARGS); which means I can write code like: LOG(@"radius=%.1f", fRadius) Up until Xcode 15 the %.1f would be respected and display fRadius to one decimal place. But since Xcode 15 it seems to ignore that and just display all decimal places regardless. Anyone know why, and how to fix that?
Replies
4
Boosts
1
Views
993
Activity
Nov ’23
Can I use OSLogStore to access logs from earlier runs of my app?
I understand that in iOS 15 and macOS Monterey, I can easily access the log system to get log entries for my app like this: let store = try OSLogStore(scope: .currentProcessIdentifier) I can then query store for the log entries. However, as it says right in the name, the store is only for current process, i.e current run of my app. When I try to get entries, I only get entries from the current run, even if I specify an earlier time like this: guard let positionDate = Calendar.current.date(byAdding: .day, value: -7, to: Date()) else { return } let position = store.position(date: positionDate) let predicate = NSPredicate(format: "subsystem == 'com.exampl.emyAppSubsystem'") let entries = try store.getEntries(with: [], at: position, matching: predicate) for entry in entries { print("Entry: \(entry.date) \(entry.composedMessage)") } Is there any way to access log entries for earlier runs of my app, e.g from days or weeks ago? Either on macOS or iOS?
Replies
7
Boosts
0
Views
4.6k
Activity
Nov ’23
Silencing OS subsystem signposts on iOS
Environment Context: iOS 17.0 Simulator Xcode 15.0 In the above environment, I'm noticing in Instruments that the OS subsystem com.apple.VectorKit is emitting os_signpost events at a rate of ~2.8 events/ms. This large amount of data logging seems to be triggering warnings of: 'Data stream: 1 log/signpost messages lost due to high rates' ...when trying to capture other system logging data. (In the attached screenshot, notice the warning sign icons right outside the selected time series.) This is preventing me from being able to successfully log my own signpost data and profile my application. As well, this subsystem's data is unnecessary for my purposes and distracting. I have tried to disable logging for this subsystem in the Simulator by running the following from the macOS host: % xcrun simctl spawn booted log config --subsystem com.apple.VectorKit --mode level:off ...and confirmed it with: % xcrun simctl spawn booted log config --subsystem com.apple.VectorKit --status Mode for 'com.apple.VectorKit' OFF PERSIST_OFF ...however, when running Instruments after the above output, this data does not actually get disabled. How can I disable this subsystem's logging? Feedback Assistant report: FB13292000
Replies
1
Boosts
0
Views
869
Activity
Oct ’23
os_log crashing in MacOS 14 Sonoma
minimum is to create an os_log once in the parent, then, after fork, use an existing os_log instance or create a new one. Here's my reproduction sample. It looks like an OS bug, So what is the workaround till its solved and releases. #include <os/log.h> #include <stdio.h> #include <errno.h> #define USE_SWIFT_LOGGER 0 // set to 1 to use Logger() instead of os_log() #define USE_SHARED_LOG 0 // set to 1 to use a shared os_log instance instead of allocating one for each os_log() call #if USE_SWIFT_LOGGER // log messages using Swift's Logger class instead of calling os_log_... directly #include "forktest-Swift.h" #define LOG(msg) log_using_logger([NSString stringWithUTF8String:msg]) const char * logMethod = "Swift's Logger"; #elif USE_SHARED_LOG // use a shared os_log instance for all log messages static os_log_t log = os_log_create("com.ivanti.forktest", "foo"); #define LOG(msg) os_log_debug(log, msg) const char * logMethod = "shared log"; #else // create a new os_log instance for each log message #define LOG(msg) os_log_debug(os_log_create("com.ivanti.forktest", "foo"), msg) const char * logMethod = "new log instance for each message"; #endif static void forkTest() { int pid = fork(); if (pid < 0) { fprintf(stderr, "fork failed: %s\n", strerror(errno)); exit(1); } else if (pid == 0) { printf("in child process...\n"); LOG("in child process..."); printf("child process done\n"); } else { printf("child process pid: %d\n", pid); } } int main(int arc, const char ** argv) { printf("Log method: %s\n", logMethod); LOG("entering main..."); forkTest(); LOG("leaving main..."); return 0; }
Replies
3
Boosts
0
Views
1.1k
Activity
Oct ’23
os_log Unified Logging not anymore tide to stderr in iOS 17?
Currently I have a setup which duplicates the stderr STDERR_FILENO pipe into a separate one. Then by setting up a readabilityHandler (on the new Pipe) I can capture the logged data and either store it inside a File, adjust/modify the data etc. Since iOS 17 this is not possible anymore (previous versions worked iOS 16)? I cannot find any documentation on why or what changed on the os_log side. private func setupPipes() { inputPipe.fileHandleForReading.readabilityHandler = { [weak self] handler in guard let strongSelf = self else { return } let data = handler.availableData strongSelf.queue.async(flags: .barrier) { guard let fileHandle = try? FileHandle(forWritingTo: strongSelf.filePath) else { return } fileHandle.seekToEndOfFile() fileHandle.write(data) try? fileHandle.close() } strongSelf.outputPipe.fileHandleForWriting.write(data) } dup2(STDERR_FILENO, outputPipe.fileHandleForWriting.fileDescriptor) dup2(inputPipe.fileHandleForWriting.fileDescriptor, STDERR_FILENO) }
Replies
8
Boosts
0
Views
2.4k
Activity
Oct ’23
OSLog in Swift macro doesn't persist original file/line number
I need to log to OSLog and into a file in parallel (due to OSLogStore not being able to provide old logs (FB13191608)). In Objective-C I can accomplish this with a macro using __FILE__ and __LINE__ in the macro implementation which still reference the position in the original code. I tried to create a Swift macro to make this work from Swift. However, log() takes the file and line number of the macro definition file instead of the position in the calling code. So when I click on the metadata link, I'm taken to the macro instead of the calling location. Is there any solution to that? #file and #line are correctly set in the macro but there’s no way to specify file and line number to the log() function (FB13204310).
Replies
5
Boosts
0
Views
1.7k
Activity
Oct ’23
Xcode 15 Structured log always redacting <private> strings
This is the opposite of https://developer.apple.com/forums/thread/726354 really, and I've read both of the Recording Private Data in the System Log and Your Friend, the System Log threads, but I still can't solve my problem. The structured log always seems to redact private values to If I set OS_ACTIVITY_DT_MODE=1 in my environment (it's not set anymore by Xcode, at least not for my projects) then the logs are unredacted as I would expect, but structured logging is turned off. Is there a way to have the unredacted strings in the log when the app is running under Xcode and still get the nice structured log output? I don't want the unredacted logs when the app runs normally, but I'd like them under Xcode. At the moment, I'm having to explicitly make everything public, which defeats the whole purpose of the system.
Replies
5
Boosts
0
Views
2.7k
Activity
Oct ’23
Reduce log verbosity in Xcode debugger
Is it possible to reduce the verbosity of logs from os_log when debugging an application? Specifically, can I filter to specific subsystems and / or exclude DEBUG logs using configuration?
Replies
4
Boosts
0
Views
8.7k
Activity
Oct ’23
Structured logging with emoji or objectdescription
When running the code below, only the first entry gets logged. Structured logging seems not to work when there are emoticons or object descriptions in the message. Is this by design? let logger = Logger(subsystem: "TestSystem", category: "TestCategory") logger.log("👍") // Result = 👍 let someEmoji:String = "👎" logger.log("\(someEmoji)") // Result = empty log line let someObjectDescription:String = String(describing:self) logger.log("\(someObjectDescription)") // Result = empty log line
Replies
3
Boosts
0
Views
1.3k
Activity
Oct ’23
How to use a freestanding macro with OSLog
I'm trying to create a macro that adds the file and line to a string that I use with OSLog. However, I only get warnings that either the String is not in the format of OSLogMessage or not an interpolated string. The Macro looks like this at the moment: public struct LocMacro: ExpressionMacro { public static func expansion( of node: some FreestandingMacroExpansionSyntax, in context: some MacroExpansionContext ) -> ExprSyntax { guard let argument = node.argumentList.first?.expression.as(StringLiteralExprSyntax.self)?.segments else { fatalError("compiler bug: the macro does not have any StringLiteralExprSyntax arguments.") } guard let file = context.location(of: node)?.file.as(StringLiteralExprSyntax.self)?.segments, let line = context.location(of: node)?.line.as(IntegerLiteralExprSyntax.self) else { fatalError("compiler bug: the macro is unable to retrieve file and line numbers") } return "\"\(argument) - \(file):\(line)\"" } } and here the exposed macro: @freestanding(expression) public macro loc(_ text: String) -> String = #externalMacro(module: "LxoMacrosMacros", type: "LocMacro") I want to use it like this: import LxoMacros import OSLog let logger = Logger() let someNumber = 17 logger.debug(#loc("Working with some number \(someNumber)")) which should expand to: logger.debug("Working with some number \(someNumber) - MyFile.swift:8") Is there a way to change the macro so that it returns the correct type? When expending the macro it does show the right string, which works with print() and so on, but assuming since the Logger uses some sort of compiler check as well, it doesn't seem to work together as expected.
Replies
2
Boosts
0
Views
1.2k
Activity
Oct ’23
os_log doesn't log file/line to Xcode 15 console for C++ code
Since this api requires &__dso_handle instead of the standard file/line/func, I had to modify my entire log system to pass this down from the macro call sites. I have many callbacks that typically just forward data from other C++ libraries that never supply a dso_handle. so it's great how this logging system breaks most logger systems and doesn't have a warning level to match fault/error. I have the forwarded threadName, timestamp, etc and no where to store that in os_log. syslog was more powerful and clear than os_log, but I'm sure it's now too late to head down a more reasonable path.. So I pass the &__dso_handle all the way to the log command and hand it into the macro #define my_os_log_with_type(dso, log, type, format, ...) __extension__({ \ os_log_t _log_tmp = (log); \ os_log_type_t _type_tmp = (type); \ if (os_log_type_enabled(_log_tmp, _type_tmp)) { \ OS_LOG_CALL_WITH_FORMAT(_os_log_impl, \ ((void*)dso, _log_tmp, _type_tmp), format, ##__VA_ARGS__); \ } \ }) Logger.mm // This doesn't work, logging the dso from the callsite. No file/line. my_os_log_with_type(entry.dso, os_log_create( "com.foo", entry.tag), logLevel(entry.level)), "%{public}s", text ); // This does work, but who wants to jump to the forwarding log implementation? os_log_with_type(os_log_create( "com.foo", entry.tag), logLevel(entry.level)), "%{public}s", text );
Replies
7
Boosts
0
Views
2.2k
Activity
Sep ’23