Skip to content

Commit

Permalink
Add Logger helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
grdsdev committed May 18, 2022
0 parents commit 919fd95
Show file tree
Hide file tree
Showing 6 changed files with 200 additions and 0 deletions.
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
.DS_Store
/.build
/Packages
/*.xcodeproj
xcuserdata/
DerivedData/
.swiftpm/config/registries.json
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
.netrc
23 changes: 23 additions & 0 deletions Package.resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"pins" : [
{
"identity" : "swift-custom-dump",
"kind" : "remoteSourceControl",
"location" : "https://github.com/pointfreeco/swift-custom-dump",
"state" : {
"revision" : "c4f78db9b90ca57b7b6abc2223e235242739ea3c",
"version" : "0.4.0"
}
},
{
"identity" : "xctest-dynamic-overlay",
"kind" : "remoteSourceControl",
"location" : "https://github.com/pointfreeco/xctest-dynamic-overlay",
"state" : {
"revision" : "50a70a9d3583fe228ce672e8923010c8df2deddd",
"version" : "0.2.1"
}
}
],
"version" : 2
}
26 changes: 26 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// swift-tools-version: 5.6

import PackageDescription

let package = Package(
name: "DebuggingHelpers",
platforms: [.macOS(.v11), .iOS(.v14)],
products: [
.library(
name: "DebuggingHelpers",
targets: ["DebuggingHelpers"])
],
dependencies: [
.package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "0.4.0")
],
targets: [
.target(
name: "DebuggingHelpers",
dependencies: [
.product(name: "CustomDump", package: "swift-custom-dump")
]),
.testTarget(
name: "DebuggingHelpersTests",
dependencies: ["DebuggingHelpers"]),
]
)
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# DebuggingHelpers

A description of this package.
120 changes: 120 additions & 0 deletions Sources/DebuggingHelpers/Logger.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import CustomDump
import OSLog

extension Logger {
/// Logger instance specific for the current module.
/// - Parameters:
/// - bundleIdentifier: The bundleID for this application, defaults to `Bundle.main.bundleIdentifier`.
/// - fileID: The fileID where this method was called, this is used for automatically extracting the module name, this should not be overriden.
/// - Returns: Logger instance specific for the current module.
public static func module(
bundleIdentifier: String = Bundle.main.bundleIdentifier ?? "",
_ fileID: String = #fileID
) -> Logger {
Logger(
subsystem: bundleIdentifier,
category: fileID.components(separatedBy: "/")[0]
)
}

/// Globally enable/disable tracing.
public static var tracingEnabled = true

@discardableResult
public func tracing<R>(
_ name: String = "",
function: String = #function,
file: StaticString = #fileID,
line: UInt = #line,
block: () async throws -> R
) async rethrows -> R {
guard Logger.tracingEnabled else {
return try await block()
}

var messageComponents: [String] = []

if !name.isEmpty {
messageComponents.append("[\(name)]")
}

messageComponents.append("\(file).\(function):\(line)")
let message = messageComponents.joined(separator: " ")

self.trace("Start: \(message)")
do {
let result = try await block()
var output = ""
customDump(result, to: &output)
self.debug("End: \(message) | Success: \(output)")
return result
} catch {
self.debug("End: \(message) | Failure: \(error.localizedDescription)")
throw error
}
}

@discardableResult
public func tracing<R>(
_ name: String = "",
function: String = #function,
file: StaticString = #fileID,
line: UInt = #line,
block: () throws -> R
) rethrows -> R {
guard Logger.tracingEnabled else {
return try block()
}

var messageComponents: [String] = []

if !name.isEmpty {
messageComponents.append("[\(name)]")
}

messageComponents.append("\(file).\(function):\(line)")
let message = messageComponents.joined(separator: " ")

self.trace("Start: \(message)")
do {
let result = try block()
var output = ""
customDump(result, to: &output)
self.debug("End: \(message) | Success: \(output)")
return result
} catch {
self.debug("End: \(message) | Failure: \(error.localizedDescription)")
throw error
}
}

@available(iOS 15.0, *)
public static func export(
bundleIdentifier: String = Bundle.main.bundleIdentifier ?? ""
) async throws -> [OSLogEntryLog] {
let store = try OSLogStore(scope: .currentProcessIdentifier)
return try store.getEntries(
matching: NSPredicate(format: "subsystem = %@", bundleIdentifier)
)
.compactMap { $0 as? OSLogEntryLog }
}

@available(iOS 15.0, *)
public static func export(
bundleIdentifier: String = Bundle.main.bundleIdentifier ?? "",
to url: URL? = nil
) async throws -> URL {
let content = try await export(bundleIdentifier: bundleIdentifier)
.map { "[\($0.date.ISO8601Format())] [\($0.category)] \($0.composedMessage)" }
.joined(separator: "\n")

let url =
url
?? URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(
"\(Date().ISO8601Format()).log")

let data = content.data(using: .utf8)!
try data.write(to: url)
return url
}
}
19 changes: 19 additions & 0 deletions Tests/DebuggingHelpersTests/DebuggingHelpersTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import CustomDump
import OSLog
import XCTest

@testable import DebuggingHelpers

final class DebuggingHelpersTests: XCTestCase {
func testLoggerModule() async throws {
let logger = Logger.module(bundleIdentifier: "co.binaryscraping.swift-debugging-helpers")
logger.info("Run test: \(#function)")

if #available(iOS 15.0, *) {
let entries: [OSLogEntryLog] = try await Logger.export(
bundleIdentifier: "co.binaryscraping.swift-debugging-helpers")
XCTAssertEqual(entries[0].category, "DebuggingHelpersTests")
XCTAssertEqual(entries[0].subsystem, "co.binaryscraping.swift-debugging-helpers")
}
}
}

0 comments on commit 919fd95

Please sign in to comment.