Created
March 1, 2021 21:14
-
-
Save manas-sharma-1683/65d2e22a24fb98be349979c2da095832 to your computer and use it in GitHub Desktop.
Unified swift logging.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os.log | |
import Foundation | |
@propertyWrapper | |
struct Redactable<Value: Codable & Hashable>: Codable, Hashable, CustomLeafReflectable, | |
CustomStringConvertible, CustomDebugStringConvertible, CustomPlaygroundDisplayConvertible { | |
private let value: Value | |
var isRedactionEnabled = true | |
var projectedValue: Self { | |
get { | |
return self | |
} set {} | |
} | |
var wrappedValue: Value { | |
get { | |
return value | |
} set {} | |
} | |
var playgroundDescription: Any { | |
return "<redacted>" | |
} | |
var description: String { | |
return isRedactionEnabled ? "<redacted>" : String(describing: value) | |
} | |
var debugDescription: String { | |
return isRedactionEnabled ? "<redacted>" : String(describing: value) | |
} | |
var customMirror: Mirror { | |
return isRedactionEnabled ? Mirror(reflecting: "<redacted>") : Mirror(reflecting: value) | |
} | |
init(wrappedValue: Value) { | |
self.value = wrappedValue | |
} | |
} | |
/* Usage */ | |
struct Person: Codable, Hashable { | |
let name: String | |
@Redactable | |
private(set) var creditCardNumber: String | |
} | |
let person = Person(name: "Manas", creditCardNumber: "1234-1234-1255-2114") | |
print(person) // prints Person(name: "Manas", _creditCardNumber: <redacted>) | |
print(person.$creditCardNumber) // prints <redacted> | |
dump(person) | |
/* | |
prints | |
Person | |
- name: "Manas" | |
- _creditCardNumber: <redacted> | |
*/ | |
debugPrint(person) // prints Person(name: "Manas", _creditCardNumber: <redacted>) | |
os_log("%@", String(describing: person)) // prints Person(name: "Manas", _creditCardNumber: <redacted>) | |
/* | |
* If you print print(person.creditCardNumber), the string will not be redacted. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment