Skip to content

Commit ec4da62

Browse files
committed
Add a logger to the app and logLevel parameter
1 parent 5f075b0 commit ec4da62

File tree

4 files changed

+27
-3
lines changed

4 files changed

+27
-3
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
/.build
33
/.swiftpm
44
/.vscode
5+
/.devContainer
56
/Packages
67
/*.xcodeproj
78
xcuserdata/

Sources/App/App.swift

+11
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import ArgumentParser
22
import Hummingbird
3+
import Logging
34

45
@main
56
struct App: AsyncParsableCommand, AppArguments {
@@ -9,8 +10,18 @@ struct App: AsyncParsableCommand, AppArguments {
910
@Option(name: .shortAndLong)
1011
var port: Int = 8080
1112

13+
@Option(name: .shortAndLong)
14+
var logLevel: Logger.Level?
15+
1216
func run() async throws {
1317
let app = buildApplication(self)
1418
try await app.runService()
1519
}
1620
}
21+
22+
/// Extend `Logger.Level` so it can be used as an argument
23+
#if compiler(>=6.0)
24+
extension Logger.Level: @retroactive ExpressibleByArgument {}
25+
#else
26+
extension Logger.Level: ExpressibleByArgument {}
27+
#endif

Sources/App/Application+build.swift

+11-2
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,24 @@
11
import Hummingbird
2+
import Logging
23

34
/// Application arguments protocol. We use a protocol so we can call
4-
/// `HBApplication.configure` inside Tests as well as in the App executable.
5+
/// `buildApplication` inside Tests as well as in the App executable.
56
/// Any variables added here also have to be added to `App` in App.swift and
67
/// `TestArguments` in AppTest.swift
78
public protocol AppArguments {
89
var hostname: String { get }
910
var port: Int { get }
11+
var logLevel: Logger.Level? { get }
1012
}
1113

1214
public func buildApplication(_ arguments: some AppArguments) -> some ApplicationProtocol {
15+
let logger = {
16+
var logger = Logger(label: "HB")
17+
logger.logLevel = arguments.logLevel ?? .info
18+
return logger
19+
}()
1320
let router = Router()
21+
// Add health route
1422
router.get("/health") { _,_ -> HTTPResponse.Status in
1523
return .ok
1624
}
@@ -19,7 +27,8 @@ public func buildApplication(_ arguments: some AppArguments) -> some Application
1927
configuration: .init(
2028
address: .hostname(arguments.hostname, port: arguments.port),
2129
serverName: "Hummingbird"
22-
)
30+
),
31+
logger: logger
2332
)
2433
return app
2534
}

Tests/AppTests/AppTests.swift

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
1-
@testable import App
21
import Hummingbird
32
import HummingbirdTesting
3+
import Logging
44
import XCTest
55

6+
@testable import App
7+
68
final class AppTests: XCTestCase {
79
struct TestArguments: AppArguments {
810
let hostname = "127.0.0.1"
911
let port = 0
12+
let logLevel: Logger.Level? = .trace
1013
}
1114

1215
func testApp() async throws {

0 commit comments

Comments
 (0)