Skip to content

Commit

Permalink
Improve Log
Browse files Browse the repository at this point in the history
  • Loading branch information
Alkenso committed Dec 10, 2024
1 parent a2c6a03 commit c775bb9
Show file tree
Hide file tree
Showing 3 changed files with 104 additions and 2 deletions.
84 changes: 83 additions & 1 deletion Sources/SpellbookFoundation/Common/SpellbookLog.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
// SOFTWARE.

import Foundation
import os

public protocol SpellbookLog {
func _custom(
Expand Down Expand Up @@ -116,6 +117,59 @@ extension SpellbookLog {
context: context
)
}

@discardableResult
public func `try`<R>(
level: SpellbookLogLevel = .error,
_ message: @autoclosure () -> Any,
assert: Bool = false,
file: StaticString = #file,
function: StaticString = #function,
line: Int = #line,
context: Any? = nil,
body: () throws -> R
) -> R? {
do {
return try body()
} catch {
custom(
level: level,
message: "\(message()). Error: \(error)",
assert: assert,
file: file,
function: function,
line: line,
context: context
)
return nil
}
}

@discardableResult
public func `try`<R>(
level: SpellbookLogLevel = .error,
assert: Bool = false,
file: StaticString = #file,
function: StaticString = #function,
line: Int = #line,
context: Any? = nil,
body: () throws -> R
) -> R? {
do {
return try body()
} catch {
custom(
level: level,
message: "\(error)",
assert: assert,
file: file,
function: function,
line: line,
context: context
)
return nil
}
}
}

public enum SpellbookLogLevel: Int, Hashable {
Expand Down Expand Up @@ -164,6 +218,7 @@ public struct SpellbookLogRecord {
public var file: StaticString
public var function: StaticString
public var line: Int
public var date: Date
public var context: Any?

public init(
Expand All @@ -173,6 +228,7 @@ public struct SpellbookLogRecord {
file: StaticString,
function: StaticString,
line: Int,
date: Date,
context: Any?
) {
self.source = source
Expand All @@ -181,10 +237,26 @@ public struct SpellbookLogRecord {
self.file = file
self.function = function
self.line = line
self.date = date
self.context = context
}
}

extension SpellbookLogRecord {
public var fullDescription: String {
let date = Self.dateFormatter.string(from: date)
let file = String("\(file)").lastPathComponent.deletingPathExtension
return "\(date) \(file).\(function):\(line) [\(source)] \(level.description.uppercased()): \(message)"
}

private static let dateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSSSS ZZZZZ"
return formatter
}()
}

public struct SpellbookLogSource {
/// Subsystem is usually a big component or a feature of the product.
/// For example, `SpellbookFoundation`.
Expand Down Expand Up @@ -224,6 +296,16 @@ public struct SpellbookLogDestination {
}
}

extension SpellbookLogDestination {
public static func print(minLevel: SpellbookLogLevel = .info) -> Self {
.init(minLevel: minLevel) { Swift.print($0.fullDescription) }
}

public static func nslog(minLevel: SpellbookLogLevel = .info) -> Self {
.init(minLevel: minLevel) { NSLog($0.fullDescription) }
}
}

public final class SpellbookLogger {
public init(name: String, useQueue: Bool = true) {
queue = useQueue ? DispatchQueue(label: "SpellbookLog.\(name).queue") : nil
Expand Down Expand Up @@ -318,7 +400,7 @@ extension SpellbookLogger: SpellbookLog {

let record = SpellbookLogRecord(
source: source, level: level, message: "\(message())",
file: file, function: function, line: line, context: context
file: file, function: function, line: line, date: Date(), context: context
)
queue.async {
destinations.forEach { $0.log(record) }
Expand Down
2 changes: 1 addition & 1 deletion Sources/SpellbookTestUtils/TestError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

import Foundation

public struct TestError: Error {
public struct TestError: Error, CustomStringConvertible {
public let description: String
public let underlyingError: Error?

Expand Down
20 changes: 20 additions & 0 deletions Tests/SpellbookTests/Common/SBLogTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -139,4 +139,24 @@ final class SBLogTests: XCTestCase {

waitForExpectations(timeout: 0.1)
}

func test_try() {
let log = SpellbookLogger(name: "test")
let exp = expectation(description: "logged")
exp.expectedFulfillmentCount = 2
var records: [SpellbookLogRecord] = []
log.destinations.append(.init {
records.append($0)
exp.fulfill()
})

log.try(level: .error, "foo failed") { throw TestError("foo error") }
XCTAssertEqual(log.try(level: .warning, "bar not failed") { 10 }, 10)
log.try { throw TestError("baz error") }

waitForExpectations()

XCTAssertTrue(records.contains { $0.message == "foo failed. Error: foo error" })
XCTAssertTrue(records.contains { $0.message == "baz error" })
}
}

0 comments on commit c775bb9

Please sign in to comment.