/
Logger+LogError.swift
63 lines (60 loc) 路 2.73 KB
/
Logger+LogError.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
extension Logger {
/// Reports an `Error` to this `Logger`, first checking if it is `Debuggable`
/// for improved debug info.
///
/// - parameters:
/// - error: `Error` to log.
/// - verbose: If `true`, extra lines of debug information will be printed containing
/// things like suggested fixes, possible causes, or other info.
/// Defaults to `true`.
public func report(
error e: Error,
request: Request? = nil,
verbose: Bool = true,
file: String = #file,
function: String = #function,
line: UInt = #line,
column: UInt = #column
) {
switch e {
case let debuggable as Debuggable:
let requestString: String
if let request = request {
requestString = " \(request.http.method) \(request.http.urlString)"
} else {
requestString = ""
}
let errorString = "\(debuggable.fullIdentifier):\(requestString) \(debuggable.reason)"
if let source = debuggable.sourceLocation {
error(errorString, file: source.file.lastPart, function: source.function, line: source.line, column: source.column)
} else {
error(errorString, file: file.lastPart, function: function, line: line, column: column)
}
if verbose, debuggable.suggestedFixes.count > 0 {
let str = "Suggested fixes for \(debuggable.fullIdentifier): " + debuggable.suggestedFixes.joined(separator: " ")
debug(str, file: file.lastPart, function: function, line: line, column: column)
}
if verbose, debuggable.possibleCauses.count > 0 {
let str = "Possible causes for \(debuggable.fullIdentifier): " + debuggable.possibleCauses.joined(separator: " ")
debug(str, file: file.lastPart, function: function, line: line, column: column)
}
default:
let reason: String
switch e {
case let localized as LocalizedError: reason = localized.localizedDescription
case let convertible as CustomStringConvertible: reason = convertible.description
default: reason = "\(e)"
}
error(reason, file: file.lastPart, function: function, line: line, column: column)
if verbose {
let str = "Conform `\(type(of: e))` to `Debuggable` for better debug info."
debug(str, file: file.lastPart, function: function, line: line, column: column)
}
}
}
}
private extension String {
var lastPart: String {
return split(separator: "/").last.map(String.init) ?? self
}
}