Skip to content
Permalink
Browse files

Add log level field to formatters

  • Loading branch information...
jnewc committed May 10, 2019
1 parent 69f89ef commit e33c775fc679e71e0a0a8553b0a80ffa37e27b6c
@@ -10,7 +10,7 @@ import Foundation

public protocol LogFormatter {

func format(message: String, metadata: LogMetadata) -> String
func format(message: String, logLevel: LogLevel, metadata: LogMetadata) -> String

}

@@ -36,7 +36,7 @@ open class BasicLogFormatter: LogFormatter {
return "[\(metadata.filename)\(metadata.function):\(metadata.line)] "
}

public func format(message: String, metadata: LogMetadata) -> String {
public func format(message: String, logLevel: LogLevel, metadata: LogMetadata) -> String {
return "\(prefix(for: metadata))\(prefix)\(message)\(suffix)"
}
}
@@ -48,11 +48,11 @@ open class DateLogFormatter: BasicLogFormatter {

let dateFormatter = DateFormatter()

override public func format(message: String, metadata: LogMetadata) -> String {
override public func format(message: String, logLevel: LogLevel, metadata: LogMetadata) -> String {
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateFormatter.string(from: Date())
self.prefix = date
return super.format(message: " \(message)", metadata: metadata)
return super.format(message: " \(message)", logLevel: logLevel, metadata: metadata)
}

}
@@ -61,20 +61,20 @@ open class DateLogFormatter: BasicLogFormatter {
public protocol BatchFormatter: LogFormatter {

func format (batch: [(String, LogMetadata)]) -> String
func format (batch: [(String, LogLevel, LogMetadata)]) -> String

}

// MARK: NewLineBatchFormatter
public class NewLineBatchFormatter: BatchFormatter {

public func format(message: String, metadata: LogMetadata) -> String {
public func format(message: String, logLevel: LogLevel, metadata: LogMetadata) -> String {
return message
}

public func format(batch: [(String, LogMetadata)]) -> String {
return batch.map({ format(message: $0.0, metadata: $0.1) }).joined(separator: "\n")
public func format(batch: [(String, LogLevel, LogMetadata)]) -> String {
return batch.map({ format(message: $0.0, logLevel: $0.1, metadata: $0.2) }).joined(separator: "\n")
}

}
@@ -92,7 +92,7 @@ public extension Logger {
func debug(_ message: String, file: StaticString = #file, line: UInt = #line, function: StaticString = #function) {
guard enabled(.debug) else { return }
let metadata = LogMetadata(file: file, line: line, function: function)
log(format(message, metadata), logLevel: .debug, metadata: metadata)
log(format(message, .debug, metadata), logLevel: .debug, metadata: metadata)
}

// MARK: info
@@ -109,7 +109,7 @@ public extension Logger {
func info(_ message: String, file: StaticString = #file, line: UInt = #line, function: StaticString = #function) {
guard enabled(.info) else { return }
let metadata = LogMetadata(file: file, line: line, function: function)
log(format(message, metadata), logLevel: .info, metadata: metadata)
log(format(message, .info, metadata), logLevel: .info, metadata: metadata)
}

// MARK: warn
@@ -123,7 +123,7 @@ public extension Logger {
func warn(_ message: String, file: StaticString = #file, line: UInt = #line, function: StaticString = #function) {
guard enabled(.warn) else { return }
let metadata = LogMetadata(file: file, line: line, function: function)
log(format(message, metadata), logLevel: .warn, metadata: metadata)
log(format(message, .warn, metadata), logLevel: .warn, metadata: metadata)
}

// MARK: error
@@ -141,10 +141,10 @@ public extension Logger {
func error(_ message: String, file: StaticString = #file, line: UInt = #line, function: StaticString = #function) {
guard enabled(.error) else { return }
let metadata = LogMetadata(file: file, line: line, function: function)
log(format(message, metadata), logLevel: .error, metadata: metadata)
log(format(message, .error, metadata), logLevel: .error, metadata: metadata)
}

internal func format(_ message: String, _ metadata: LogMetadata) -> String {
return formatters.reduce(message, { $1.format(message: $0, metadata: metadata) })
internal func format(_ message: String, _ logLevel: LogLevel, _ metadata: LogMetadata) -> String {
return formatters.reduce(message, { $1.format(message: $0, logLevel: logLevel, metadata: metadata) })
}
}
@@ -8,7 +8,7 @@
import Foundation

public typealias LambdaFormatterCompletion = (String, LogMetadata) -> (String)
public typealias LambdaFormatterCompletion = (String, LogLevel, LogMetadata) -> (String)

public class LambdaFormatter: LogFormatter {

@@ -18,8 +18,8 @@ public class LambdaFormatter: LogFormatter {
self.completion = completion
}

public func format(message: String, metadata: LogMetadata) -> String {
return completion(message, metadata)
public func format(message: String, logLevel: LogLevel, metadata: LogMetadata) -> String {
return completion(message, logLevel, metadata)
}

}
@@ -44,7 +44,7 @@ class JSONFormatter: LogFormatter, JSONFormatterConverter {
return JSONSerialization.string(withJSONObject: dict, options: options)
}

func format(message: String, metadata: LogMetadata) -> String {
func format(message: String, logLevel: LogLevel, metadata: LogMetadata) -> String {
guard let string = toJSON(message: message, metadata: metadata) else { return message }
return string
}
@@ -62,12 +62,12 @@ public class JSONBatchFormatter: BatchFormatter {
jsonFormatter = JSONFormatter(converter: converter)
}

public func format(message: String, metadata: LogMetadata) -> String {
return jsonFormatter.format(message: message, metadata: metadata)
public func format(message: String, logLevel: LogLevel, metadata: LogMetadata) -> String {
return jsonFormatter.format(message: message, logLevel: logLevel, metadata: metadata)
}

public func format(batch: [(String, LogMetadata)]) -> String {
return batch.map({ format(message: $0.0, metadata: $0.1) }).joined(separator: "\n")
public func format(batch: [(String, LogLevel, LogMetadata)]) -> String {
return batch.map({ format(message: $0.0, logLevel: $0.1, metadata: $0.2) }).joined(separator: "\n")
}

}
@@ -30,7 +30,7 @@ class SyslogFormatter: LogFormatter {
/// a name describing the calling application or service
var sender: String = Bundle.main.bundleIdentifier ?? "Unknown"

func format(message: String, metadata: LogMetadata) -> String {
func format(message: String, logLevel: LogLevel, metadata: LogMetadata) -> String {
let timestamp = Date().iso8601
return "\(SyslogHeader) \(timestamp) \(SyslogSenderName) \(sender) - - - \(message)"
}
@@ -62,7 +62,7 @@ public class HTTPLogger: Logger {

internal var config: HTTPLoggerConfig?
// TODO: use LogCacheEntry
internal var cache: [(String, LogMetadata)] = []
internal var cache: [(String, LogLevel, LogMetadata)] = []

required public init() {
let queue = OperationQueue()
@@ -77,7 +77,7 @@ public class HTTPLogger: Logger {
}

public func log(_ message: String, logLevel: LogLevel, metadata: LogMetadata) {
cache.append((message, metadata))
cache.append((message, logLevel, metadata))
attemptSend()
}

@@ -27,7 +27,7 @@ class FormatterTests: XCTestCase {

let formatter = BasicLogFormatter()

let string = formatter.format(message: "a", metadata: LogMetadata()); let line = #line
let string = formatter.format(message: "a", logLevel: .info, metadata: LogMetadata()); let line = #line

XCTAssertEqual(string, "[FormatterTests.swift → testBasicLogFormatter():\(line)] a")
}
@@ -36,7 +36,7 @@ class FormatterTests: XCTestCase {

let formatter = BasicLogFormatter(prefix: "a", suffix: "c")

let string = formatter.format(message: "b", metadata: LogMetadata()); let line = #line
let string = formatter.format(message: "b", logLevel: .info, metadata: LogMetadata()); let line = #line

XCTAssertEqual(string, "[FormatterTests.swift → testBasicLogFormatterWithPrefixAndSuffix():\(line)] abc")

@@ -46,7 +46,7 @@ class FormatterTests: XCTestCase {

let formatter = SyslogFormatter()

let formattedMessage = formatter.format(message: "Testing", metadata: LogMetadata())
let formattedMessage = formatter.format(message: "Testing", logLevel: .info, metadata: LogMetadata())

XCTAssertMatches(input: formattedMessage, pattern: "<\\d{2}>\\d \(dateTimeExpr) Cosmic com.apple.dt.xctest.tool - - - Testing")
}
@@ -61,7 +61,7 @@ class FormatterTests: XCTestCase {
]
}

let formattedMessage = formatter.format(message: "Test", metadata: LogMetadata())
let formattedMessage = formatter.format(message: "Test", logLevel: .info, metadata: LogMetadata())

let expectedMessage = "{\"id\":\"123\",\"message\":\"Test\",\"tag\":\"my tag\"}"

@@ -80,32 +80,32 @@ class FormatterTests: XCTestCase {
]
}

let message1 = formatter.format(message: "Message #1", metadata: LogMetadata())
let message1 = formatter.format(message: "Message #1", logLevel: .info, metadata: LogMetadata())
XCTAssertEqual(message1, "{\"id\":1,\"message\":\"Message #1\"}")

let message2 = formatter.format(message: "Message #2", metadata: LogMetadata())
let message2 = formatter.format(message: "Message #2", logLevel: .info, metadata: LogMetadata())
XCTAssertEqual(message2, "{\"id\":2,\"message\":\"Message #2\"}")

let message3 = formatter.format(message: "Message #3", metadata: LogMetadata())
let message3 = formatter.format(message: "Message #3", logLevel: .info, metadata: LogMetadata())
XCTAssertEqual(message3, "{\"id\":3,\"message\":\"Message #3\"}")

}

func testBlockFormatter() {

let blockFormatter = LambdaFormatter { message, _ in
let blockFormatter = LambdaFormatter { message, _, _ in
return "« \(message) »"
}

let formattedMessage = blockFormatter.format(message: "Test", metadata: LogMetadata())
let formattedMessage = blockFormatter.format(message: "Test", logLevel: .info, metadata: LogMetadata())

XCTAssertEqual("« Test »", formattedMessage)
}

func testDateFormatter() {
let dateFormatter = DateLogFormatter()

let formattedMessage = dateFormatter.format(message: "Test", metadata: LogMetadata()); let line = #line
let formattedMessage = dateFormatter.format(message: "Test", logLevel: .info, metadata: LogMetadata()); let line = #line

// TODO
XCTAssertMatches(input: formattedMessage, pattern: "\\[FormatterTests\\.swift → testDateFormatter\\(\\):\(line)\\] \(dateTimeExpr) Test")
@@ -118,9 +118,9 @@ class FormatterTests: XCTestCase {
let batchFormatter = NewLineBatchFormatter()

let formattedMessage = batchFormatter.format(batch: [
("Test1", LogMetadata()),
("Test2", LogMetadata()),
("Test3", LogMetadata())
("Test1", .info, LogMetadata()),
("Test2", .info, LogMetadata()),
("Test3", .info, LogMetadata())
])

XCTAssertEqual("Test1\nTest2\nTest3", formattedMessage)
@@ -136,9 +136,9 @@ class FormatterTests: XCTestCase {
}

let formattedMessage = batchFormatter.format(batch: [
("Test1", LogMetadata()),
("Test2", LogMetadata()),
("Test3", LogMetadata())
("Test1", .info, LogMetadata()),
("Test2", .info, LogMetadata()),
("Test3", .info, LogMetadata())
])

let template: (String) -> String = { "{\"message\":\"\($0)\"}" }
@@ -73,7 +73,7 @@ class ServiceLoggerTests: XCTestCase {
XCTAssertEqual(logger.config?.method, LogglyServiceConfig.method)
XCTAssertEqual(logger.config?.headers[HTTPHeader.ContentType], HTTPHeader.ContentTypeJSON)

let formattedString = logger.batchFormatter.format(message: "Test", metadata: LogMetadata())
let formattedString = logger.batchFormatter.format(message: "Test", logLevel: .info, metadata: LogMetadata())
XCTAssertNotNil(formattedString)

let json = try! JSONSerialization.jsonObject(with: formattedString.data(using: .utf8)!, options: []) as! [String: String]

0 comments on commit e33c775

Please sign in to comment.
You can’t perform that action at this time.