In your demo app, first import OSLog and set up a few loggers for different categories. Set them up in the AppMain.swift file so they’ll be visible everywhere in the app.
import OSLog
let movementLogger = Logger(subsystem: "com.example.bragbookapp", category: "movement")
let imageLogger = Logger(subsystem: "com.example.bragbookapp", category: "images")
These examples are contrived because this demo app doesn’t have much code.
Now, in ContentView.swift, add some log messages.
First, add one when the user clicks the back button:
movementLogger.log("backwards button clicked")
Next, add one when the user clicks the forward button:
movementLogger.log("forwards button clicked")
Using the other logger, log the name of the new image when either button is clicked. Add this code in both places:
imageLogger.log("\(dogImages[currentImage])")
Now, when you run the app, as you click on the forward and backward buttons, you’ll see the log messages in the Xcode console. You only see the message by default, but you can add the metadata using the toggle button on the bottom left.
Enable the category and timestamp and see how that data now appears in the log entries.
Now, stop the app and change the levels of the log messages. Make the movement messages level error and the image log messages level fault.
movementLogger.log(level: .error, "forwards button clicked")
imageLogger.log(level: .fault, "\(dogImages[currentImage])")
Rerun the app and see how the messages are color-coded.
Unlike when you added #warning to your code earlier, setting a message to a higher severity doesn’t impact your app at all.
Open Console.app. Notice on the left that you see your Mac and your device or simulator. Click the device or simulator where you’re running the demo app, then click Start to start the logging. Oh my, that’s a lot of messages!
In the search text area, type:
subsystem: com.example.bragbookapp
Now you see that your log is filtered. Bring the simulator to the front and generate some more log messages by clicking the buttons. Notice that the messages that were color-coded in the Xcode log are also color-coded in the console.
You might not want to retype the filter when you’re working with something a lot. Notice that below the filter is a Save button. Click that and give it a name.
See how the name appears at the top. Now, in the console, whenever you want to use that filter again, you can tap it in the toolbar; you don’t need to retype.
Control-click on any log entries to filter the list further. For instance, you could hide or show the category.