Loging using OSLog
Tags: swift, oslog
Published: 2024-07-10 06:11:30

---
title: Loging using OSLog
published: true
date: 2024-07-05 15:06:22 UTC
tags: Swift,OSLog
canonical_url: https://wesleydegroot.nl/blog/OSLog
---

OSLog is a Swift API that provides a unified logging system for all Apple platforms.  
It is a replacement for the older `print` and `NSLog` functions.  
OSLog is a more efficient and secure logging system that provides better performance and privacy protection.  
In this article, we will explore the features of OSLog and how to use it in your Swift applications.

## Installation

To use `OSLog` in your Swift application, you need to import the `OSLog` module.  
You can do this by adding the following import statement to your Swift file:

```swift
import OSLog
```

Then you can use the `Logger` class to create a logger instance.  
The `Logger` class is a wrapper around the `OSLog` API that provides a more convenient way to log messages.

```swift
let logger = Logger(
    subsystem: "nl.wesleydegroot.demoApp",
    category: "myCategory"
)
```

The `subsystem` parameter is a string that identifies the subsystem that the logger belongs to.  
The `category` parameter is a string that identifies the category of the logger.

## Sample Use

```swift
import OSLog

let logger = Logger(
    subsystem: "nl.wesleydegroot.demoApp",
    category: "myCategory"
)

logger.fault("This is a fault") // Shows in red
logger.error("This is a error") // Shows in yellow
logger.warning("This is a warning") // Shows in yellow
logger.info("Information") // Shows in default color
logger.debug("Debug message") // Shows in default color
logger.trace("Trace message") // Shows in default color
```

## Caveats

Unfortunately, `OSLog` is only available on Apple platforms and it cannot be used within SwiftUI views.  
If you need to log messages within a SwiftUI view, use the view extension below:

```swift
import SwiftUI

extension View {
    func log(_ closure: () -> Void) -> some View {
         _ = closure()
         return self
     }
}
```

Now you can log messages within a SwiftUI view like this:

```swift
import SwiftUI
import OSLog

struct ContentView: View {
    let logger = Logger(
        subsystem: "nl.wesleydegroot.exampleapp",
        category: "MyCategory"
    )

    var body: some View {
        Text("Hello, World!")
            .log {
                logger.info("Hello, World!")
            }
    }
}
```

## Displaying Log Messages (in app)

If you want to display log messages in your app, you can use the `OSLog` API to log messages to the console.  
I've created a Swift Package to make this easier, you can find it [here (OSLogViewer)](https://github.com/0xWDG/OSLogViewer).

### How to use `OSLogViewer`:

```swift
import SwiftUI
import OSLogViewer

struct ContentView: View {
    var body: some View {
        NavigationView {
            // The default configuration will show the log messages.
            OSLogViewer()

            // Custom configuration
            // OSLogViewer(
            // subsystem: "nl.wesleydegroot.exampleapp",
            // since: Date().addingTimeInterval(-7200) // 2 hours
            // )
        }
    }
}
```

[Download Swift Playground](https://wesleydegroot.nl/resources/OSLog.swiftpm.zip)

### OSLogViewer Features

#### Simple Interface

![OSLog Viewer](https://wesleydegroot.nl/resources/OSLogViewer.png)

#### Beautiful export

```
This is the OSLog archive for exampleapp
Generated on 2/6/2024, 11:53
Generator https://github.com/0xWDG/OSLogViewer

Info message
ℹ️ 2/6/2024, 11:53 🏛️ exampleapp ⚙️ nl.wesleydegroot.exampleapp 🌐 myCategory

Error message
❗ 2/6/2024, 11:53 🏛️ exampleapp ⚙️ nl.wesleydegroot.exampleapp 🌐 myCategory

Error message
❗ 2/6/2024, 11:53 🏛️ exampleapp ⚙️ nl.wesleydegroot.exampleapp 🌐 myCategory

Critical message
‼️ 2/6/2024, 11:53 🏛️ exampleapp ⚙️ nl.wesleydegroot.exampleapp 🌐 myCategory

Log message
🔔 2/6/2024, 11:53 🏛️ exampleapp ⚙️ nl.wesleydegroot.exampleapp 🌐 myCategory

Log message
🔔 2/6/2024, 11:53 🏛️ exampleapp ⚙️ nl.wesleydegroot.exampleapp 🌐 myCategory
```

## Wrap up

OSLog is a more efficient and secure logging system that provides better performance and privacy protection.  
It is a great replacement for the older `print` and `NSLog` functions, that provides a unified logging system for all Apple platforms.

Resources:

- [https://github.com/0xWDG/OSLogViewer](https://github.com/0xWDG/OSLogViewer)
- [https://developer.apple.com/documentation/os/logging](https://developer.apple.com/documentation/os/logging)