Skip to content

Commit 7258998

Browse files
Merge pull request #3729 from SwiftPackageIndex/simplify-LoggerClient-2
Simplify logger client 2
2 parents 1a6e362 + 4df525d commit 7258998

16 files changed

+72
-83
lines changed

Sources/App/Commands/Alerting.swift

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,10 @@ enum Alerting {
4242
}
4343

4444
func run(using context: CommandContext, signature: Signature) async throws {
45+
prepareDependencies {
46+
$0.logger = Logger(component: "alerting")
47+
}
4548
@Dependency(\.logger) var logger
46-
logger.set(to: Logger(component: "alerting"))
4749

4850
logger.info("Running alerting...")
4951

Sources/App/Commands/Analyze.swift

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,13 @@ enum Analyze {
2828
var help: String { "Run package analysis (fetching git repository and inspecting content)" }
2929

3030
func run(using context: CommandContext, signature: SPICommand.Signature) async throws {
31+
prepareDependencies {
32+
$0.logger = Logger(component: "analyze")
33+
}
34+
@Dependency(\.logger) var logger
35+
3136
let client = context.application.client
3237
let db = context.application.db
33-
@Dependency(\.logger) var logger
34-
logger.set(to: Logger(component: "analyze"))
3538

3639
Analyze.resetMetrics()
3740

@@ -251,7 +254,7 @@ extension Analyze {
251254
attributes: nil)
252255
} catch {
253256
let error = AppError.genericError(nil, "Failed to create checkouts directory: \(error.localizedDescription)")
254-
logger.logger.report(error: error)
257+
logger.report(error: error)
255258
}
256259
}
257260

Sources/App/Commands/Ingestion.swift

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,10 +82,13 @@ enum Ingestion {
8282
var help: String { "Run package ingestion (fetching repository metadata)" }
8383

8484
func run(using context: CommandContext, signature: SPICommand.Signature) async {
85+
prepareDependencies {
86+
$0.logger = Logger(component: "ingest")
87+
}
88+
@Dependency(\.logger) var logger
89+
8590
let client = context.application.client
8691
let db = context.application.db
87-
@Dependency(\.logger) var logger
88-
logger.set(to: Logger(component: "ingest"))
8992

9093
Self.resetMetrics()
9194

Sources/App/Commands/ReAnalyzeVersions.swift

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,14 +43,16 @@ enum ReAnalyzeVersions {
4343
var help: String { "Run version re-analysis" }
4444

4545
func run(using context: CommandContext, signature: Signature) async throws {
46-
let limit = signature.limit ?? defaultLimit
46+
prepareDependencies {
47+
$0.logger = Logger(component: "re-analyze-versions")
48+
}
49+
@Dependency(\.logger) var logger
50+
@Dependency(\.date.now) var now
4751

52+
let limit = signature.limit ?? defaultLimit
4853
let client = context.application.client
4954
let db = context.application.db
50-
@Dependency(\.logger) var logger
51-
logger.set(to: Logger(component: "re-analyze-versions"))
5255

53-
@Dependency(\.date.now) var now
5456
if let id = signature.packageId {
5557
logger.info("Re-analyzing versions (id: \(id)) ...")
5658
do {

Sources/App/Commands/Reconcile.swift

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,23 +23,23 @@ struct ReconcileCommand: AsyncCommand {
2323
var help: String { "Reconcile package list with server" }
2424

2525
func run(using context: CommandContext, signature: Signature) async throws {
26+
prepareDependencies{
27+
$0.logger = Logger(component: "reconcile")
28+
}
2629
@Dependency(\.logger) var logger
27-
logger.set(to: Logger(component: "reconcile"))
2830

2931
logger.info("Reconciling...")
3032

3133
do {
32-
try await reconcile(client: context.application.client,
33-
database: context.application.db)
34+
try await reconcile(client: context.application.client, database: context.application.db)
3435
} catch {
3536
logger.error("\(error)")
3637
}
3738

3839
logger.info("done.")
3940

4041
do {
41-
try await AppMetrics.push(client: context.application.client,
42-
jobName: "reconcile")
42+
try await AppMetrics.push(client: context.application.client, jobName: "reconcile")
4343
} catch {
4444
logger.warning("\(error)")
4545
}

Sources/App/Commands/TriggerBuilds.swift

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,10 @@ struct TriggerBuildsCommand: AsyncCommand {
5555
}
5656

5757
func run(using context: CommandContext, signature: Signature) async throws {
58+
prepareDependencies {
59+
$0.logger = Logger(component: "trigger-builds")
60+
}
5861
@Dependency(\.logger) var logger
59-
logger.set(to: Logger(component: "trigger-builds"))
6062

6163
Self.resetMetrics()
6264

Sources/App/Core/Dependencies/LoggerClient.swift

Lines changed: 18 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -13,72 +13,39 @@
1313
// limitations under the License.
1414

1515
import Dependencies
16-
import DependenciesMacros
16+
import IssueReporting
1717
import Logging
18-
import Synchronization
1918

2019

21-
@DependencyClient
22-
struct LoggerClient {
23-
var log: @Sendable (_ level: Logging.Logger.Level, Logging.Logger.Message) -> Void
24-
var set: @Sendable (_ to: Logging.Logger) -> Void
25-
}
26-
27-
28-
extension LoggerClient {
29-
func critical(_ message: Logging.Logger.Message) { log(.critical, message) }
30-
func debug(_ message: Logging.Logger.Message) { log(.debug, message) }
31-
func error(_ message: Logging.Logger.Message) { log(.error, message) }
32-
func info(_ message: Logging.Logger.Message) { log(.info, message) }
33-
func warning(_ message: Logging.Logger.Message) { log(.warning, message) }
34-
func trace(_ message: Logging.Logger.Message) { log(.trace, message) }
35-
func report(error: Error, file: String = #fileID, function: String = #function, line: UInt = #line) {
36-
logger.report(error: error, file: file, function: function, line: line)
20+
private enum LoggerClient: DependencyKey {
21+
static var liveValue: Logger {
22+
reportIssue("The default logger is being used. Override this dependency in the entry point of your app.")
23+
return Logging.Logger(label: "default")
3724
}
38-
var logger: Logging.Logger { Self._logger.withLock { $0 } }
3925
}
4026

4127

42-
#if DEBUG
43-
extension LoggerClient {
44-
func set(to handler: LogHandler?) {
45-
if let handler {
46-
let logger = Logger(label: "test", factory: { _ in handler })
47-
set(to: logger)
48-
}
49-
}
50-
51-
static var noop: Self {
52-
.init(log: { _, _ in }, set: { _ in })
28+
extension LoggerClient: TestDependencyKey {
29+
static var testValue: Logger {
30+
unimplemented("testValue"); return .init(label: "test")
5331
}
5432
}
55-
#endif
5633

5734

58-
extension LoggerClient: DependencyKey {
59-
static var liveValue: Self {
60-
.init(
61-
log: { level, message in
62-
_logger.withLock { $0.log(level: level, message) }
63-
},
64-
set: { logger in
65-
_logger.withLock { $0 = logger }
66-
}
67-
)
35+
extension DependencyValues {
36+
public var logger: Logger {
37+
get { self[LoggerClient.self] }
38+
set { self[LoggerClient.self] = newValue }
6839
}
69-
70-
private static let _logger = Mutex(Logging.Logger(component: "default"))
7140
}
7241

7342

74-
extension LoggerClient: TestDependencyKey {
75-
static var testValue: Self { liveValue }
76-
}
77-
43+
#if DEBUG
44+
extension Logger {
45+
static var noop: Self { .init(label: "noop") { _ in SwiftLogNoOpLogHandler() } }
7846

79-
extension DependencyValues {
80-
var logger: LoggerClient {
81-
get { self[LoggerClient.self] }
82-
set { self[LoggerClient.self] = newValue }
47+
static func testLogger(_ handler: LogHandler) -> Self {
48+
.init(label: "test", factory: { _ in handler })
8349
}
8450
}
51+
#endif

Sources/App/Core/Dependencies/ShellClient.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ extension ShellClient: DependencyKey {
4242
run: { command, path in
4343
@Dependency(\.logger) var logger
4444
do {
45-
let res = try await ShellOut.shellOut(to: command, at: path, logger: logger.logger)
45+
let res = try await ShellOut.shellOut(to: command, at: path, logger: logger)
4646
if !res.stderr.isEmpty {
4747
logger.warning("stderr: \(res.stderr)")
4848
}

Sources/App/configure.swift

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,7 @@ public func configure(_ app: Application, databasePort: Int? = nil) async throws
2727
let _ = Bundle(path: "/Applications/InjectionIII.app/Contents/Resources/macOSInjection.bundle")?.load()
2828
#endif
2929

30-
@Dependency(\.logger) var logger
3130
app.logger.component = "server"
32-
logger.set(to: app.logger)
3331

3432
// It will be tempting to uncomment/re-add these lines in the future. We should not enable
3533
// server-side compression as long as we pass requests through Cloudflare, which compresses

Tests/AppTests/AnalyzeErrorTests.swift

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ extension AllTests.AnalyzeErrorTests {
6666
try await withDependencies {
6767
$0.environment.loadSPIManifest = { _ in nil }
6868
$0.fileManager.fileExists = { @Sendable _ in true }
69-
$0.logger.set(to: capturingLogger)
69+
$0.logger = .testLogger(capturingLogger)
7070
$0.shell.run = { @Sendable cmd, path in
7171
switch cmd {
7272
case _ where cmd.description.contains("git clone https://github.com/foo/1"):
@@ -100,7 +100,7 @@ extension AllTests.AnalyzeErrorTests {
100100
try await withDependencies {
101101
$0.environment.loadSPIManifest = { _ in nil }
102102
$0.fileManager.fileExists = { @Sendable _ in true }
103-
$0.logger.set(to: capturingLogger)
103+
$0.logger = .testLogger(capturingLogger)
104104
} operation: {
105105
// setup
106106
let pkg = try await Package.find(badPackageID, on: app.db).unwrap()
@@ -130,7 +130,7 @@ extension AllTests.AnalyzeErrorTests {
130130
try await withDependencies {
131131
$0.environment.loadSPIManifest = { _ in nil }
132132
$0.fileManager.fileExists = { @Sendable _ in true }
133-
$0.logger.set(to: capturingLogger)
133+
$0.logger = .testLogger(capturingLogger)
134134
$0.shell.run = { @Sendable cmd, path in
135135
switch cmd {
136136
case .gitCheckout(branch: "main", quiet: true) where path.hasSuffix("foo-1"):
@@ -166,7 +166,7 @@ extension AllTests.AnalyzeErrorTests {
166166
}
167167
return true
168168
}
169-
$0.logger.set(to: capturingLogger)
169+
$0.logger = .testLogger(capturingLogger)
170170
} operation: {
171171
// MUT
172172
try await Analyze.analyze(client: app.client,

0 commit comments

Comments
 (0)