Skip to content

Commit

Permalink
Add a logger to the app and logLevel parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
adam-fowler committed Apr 10, 2024
1 parent 5f075b0 commit ec4da62
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 3 deletions.
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -2,6 +2,7 @@
/.build
/.swiftpm
/.vscode
/.devContainer
/Packages
/*.xcodeproj
xcuserdata/
Expand Down
11 changes: 11 additions & 0 deletions Sources/App/App.swift
@@ -1,5 +1,6 @@
import ArgumentParser
import Hummingbird
import Logging

@main
struct App: AsyncParsableCommand, AppArguments {
Expand All @@ -9,8 +10,18 @@ struct App: AsyncParsableCommand, AppArguments {
@Option(name: .shortAndLong)
var port: Int = 8080

@Option(name: .shortAndLong)
var logLevel: Logger.Level?

func run() async throws {
let app = buildApplication(self)
try await app.runService()
}
}

/// Extend `Logger.Level` so it can be used as an argument
#if compiler(>=6.0)
extension Logger.Level: @retroactive ExpressibleByArgument {}
#else
extension Logger.Level: ExpressibleByArgument {}
#endif
13 changes: 11 additions & 2 deletions Sources/App/Application+build.swift
@@ -1,16 +1,24 @@
import Hummingbird
import Logging

/// Application arguments protocol. We use a protocol so we can call
/// `HBApplication.configure` inside Tests as well as in the App executable.
/// `buildApplication` inside Tests as well as in the App executable.
/// Any variables added here also have to be added to `App` in App.swift and
/// `TestArguments` in AppTest.swift
public protocol AppArguments {
var hostname: String { get }
var port: Int { get }
var logLevel: Logger.Level? { get }
}

public func buildApplication(_ arguments: some AppArguments) -> some ApplicationProtocol {
let logger = {
var logger = Logger(label: "HB")
logger.logLevel = arguments.logLevel ?? .info
return logger
}()
let router = Router()
// Add health route
router.get("/health") { _,_ -> HTTPResponse.Status in
return .ok
}
Expand All @@ -19,7 +27,8 @@ public func buildApplication(_ arguments: some AppArguments) -> some Application
configuration: .init(
address: .hostname(arguments.hostname, port: arguments.port),
serverName: "Hummingbird"
)
),
logger: logger
)
return app
}
5 changes: 4 additions & 1 deletion Tests/AppTests/AppTests.swift
@@ -1,12 +1,15 @@
@testable import App
import Hummingbird
import HummingbirdTesting
import Logging
import XCTest

@testable import App

final class AppTests: XCTestCase {
struct TestArguments: AppArguments {
let hostname = "127.0.0.1"
let port = 0
let logLevel: Logger.Level? = .trace
}

func testApp() async throws {
Expand Down

0 comments on commit ec4da62

Please sign in to comment.