Formatting Swift Log Entries for Readability
Yesterday, we explored how to filter log messages in Xcode. Today we're going to be working on making the messages more readable.
Standard Formatters
Logging uses interpolation, but there are additional arguments that can be provided. For example, Booleans can be formatted as .answer
.
Logger.spicy.trace("Was this salsa spicy? \(isSpicy, format: .answer)")
// Was this salsa spicy? YES
Of course, different data types have different formats available.
Int32
has the most available, including .byteCount
and .ipv4Address
.
Logger.spicy.trace("Color: \(color, format: .hex(includePrefix: true, uppercase: true, minDigits: 6))")
Logger.spicy.trace("Byte count: \(byteCount, format: .byteCount)")
Logger.spicy.trace("IP Address: \(ipAddress, format: .ipv4Address)")
// Color: 0x00FF00
// Byte count: 61.8 kB
// IP Address: 146.74.186.126
Enable logging via CustomStringConvertable
For custom types, implementing the CustomStringConvertable
protocol will allow interpolation to work in logging messages.
struct Sauce: CustomStringConvertible {
let name: String
let manufacturer: String
// MARK: - CustomStringConvertable
var description: String {
"\(name) by \(manufacturer)"
}
}
Logger.spicy.trace("Sauce: \(sauce)")
// Sauce: Awesome Sauce by Acme Inc
Coming up next
Tomorrow we'll be focused on protecting privacy of personally identifiable information (PII).