Skip to content

Commit c77eb54

Browse files
committed
Start replacing ad-hoc logging with swift-log adoption
We had a lot of all-over-the-place logging which pretended to be loggers or just println + debug and info prefixes etc. This is getting out of hand and we should adopt a consistent logging mechanism. The way to do this in Swift is swift-log, there's no reason anymore to reinvent the wheel about it. The dependency is small and likely to be present in most libs. Especially the source gen we need not be concnerned about using swift-log. Runtime does not have to use it. This is just some initial steps, separated out from #397
1 parent cc0ff8f commit c77eb54

File tree

5 files changed

+40
-21
lines changed

5 files changed

+40
-21
lines changed

Package.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,7 @@ let package = Package(
205205
.package(url: "https://github.com/swiftlang/swift-syntax", from: "602.0.0"),
206206
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.0"),
207207
.package(url: "https://github.com/apple/swift-system", from: "1.4.0"),
208+
.package(url: "https://github.com/apple/swift-log", from: "1.2.0"),
208209

209210
// // FIXME: swift-subprocess stopped supporting 6.0 when it moved into a package;
210211
// // we'll need to drop 6.0 as well, but currently blocked on doing so by swiftpm plugin pending design questions
@@ -395,6 +396,7 @@ let package = Package(
395396
.target(
396397
name: "SwiftJavaToolLib",
397398
dependencies: [
399+
.product(name: "Logging", package: "swift-log"),
398400
.product(name: "SwiftBasicFormat", package: "swift-syntax"),
399401
.product(name: "SwiftSyntax", package: "swift-syntax"),
400402
.product(name: "SwiftSyntaxBuilder", package: "swift-syntax"),
@@ -418,6 +420,7 @@ let package = Package(
418420
.executableTarget(
419421
name: "SwiftJavaTool",
420422
dependencies: [
423+
.product(name: "Logging", package: "swift-log"),
421424
.product(name: "SwiftBasicFormat", package: "swift-syntax"),
422425
.product(name: "SwiftSyntax", package: "swift-syntax"),
423426
.product(name: "SwiftSyntaxBuilder", package: "swift-syntax"),

Sources/SwiftJavaTool/Commands/ConfigureCommand.swift

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
//
1313
//===----------------------------------------------------------------------===//
1414

15+
import Logging
1516
import ArgumentParser
1617
import Foundation
1718
import SwiftJavaToolLib
@@ -27,6 +28,9 @@ import SwiftJavaShared
2728

2829
extension SwiftJava {
2930
struct ConfigureCommand: SwiftJavaBaseAsyncParsableCommand, HasCommonOptions, HasCommonJVMOptions {
31+
32+
static let log: Logging.Logger = Logger(label: "swift-java:\(configuration.commandName!)")
33+
3034
static let configuration = CommandConfiguration(
3135
commandName: "configure",
3236
abstract: "Configure and emit a swift-java.config file based on an input dependency or jar file")
@@ -63,7 +67,7 @@ extension SwiftJava {
6367
extension SwiftJava.ConfigureCommand {
6468
mutating func runSwiftJavaCommand(config: inout Configuration) async throws {
6569
let classpathEntries = self.configureCommandJVMClasspath(
66-
searchDirs: [self.effectiveSwiftModuleURL], config: config)
70+
searchDirs: [self.effectiveSwiftModuleURL], config: config, log: Self.log)
6771

6872
let jvm =
6973
try self.makeJVM(classpathEntries: classpathEntries)

Sources/SwiftJavaTool/Commands/WrapJavaCommand.swift

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,18 @@
1414

1515
import Foundation
1616
import ArgumentParser
17+
import Logging
1718
import SwiftJavaToolLib
1819
import SwiftJava
1920
import JavaUtilJar
20-
import SwiftJavaToolLib
2121
import SwiftJavaConfigurationShared
2222

2323
extension SwiftJava {
2424

2525
struct WrapJavaCommand: SwiftJavaBaseAsyncParsableCommand, HasCommonOptions, HasCommonJVMOptions {
26+
27+
static let log: Logging.Logger = .init(label: "swift-java:\(configuration.commandName!)")
28+
2629
static let configuration = CommandConfiguration(
2730
commandName: "wrap-java",
2831
abstract: "Wrap Java classes with corresponding Swift bindings.")
@@ -74,7 +77,7 @@ extension SwiftJava.WrapJavaCommand {
7477
print("[trace][swift-java] INPUT: \(input)")
7578

7679
var classpathEntries = self.configureCommandJVMClasspath(
77-
searchDirs: classpathSearchDirs, config: config)
80+
searchDirs: classpathSearchDirs, config: config, log: Self.log)
7881

7982
// Load all of the dependent configurations and associate them with Swift modules.
8083
let dependentConfigs = try loadDependentConfigs(dependsOn: self.dependsOn).map { moduleName, config in

Sources/SwiftJavaTool/CommonOptions.swift

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import SwiftJava
2020
import JavaUtilJar
2121
import JavaNet
2222
import SwiftSyntax
23+
import Logging
2324
import SwiftJavaConfigurationShared
2425
import SwiftJavaShared
2526

@@ -43,7 +44,7 @@ extension SwiftJava {
4344
var inputSwift: String? = nil
4445

4546
@Option(name: .shortAndLong, help: "Configure the level of logs that should be printed")
46-
var logLevel: Logger.Level = .info
47+
var logLevel: JExtractSwiftLib.Logger.Level = .info
4748
}
4849

4950
struct CommonJVMOptions: ParsableArguments {
@@ -78,46 +79,46 @@ extension HasCommonJVMOptions {
7879
/// swift-java.classpath files as configured.
7980
/// Parameters:
8081
/// - searchDirs: search directories where we can find swift.java.classpath files to include in the configuration
81-
func configureCommandJVMClasspath(searchDirs: [Foundation.URL], config: Configuration) -> [String] {
82+
func configureCommandJVMClasspath(searchDirs: [Foundation.URL], config: Configuration, log: Logging.Logger) -> [String] {
8283
// Form a class path from all of our input sources:
8384
// * Command-line option --classpath
8485
let classpathOptionEntries: [String] = self.classpathEntries
8586
let classpathFromEnv = ProcessInfo.processInfo.environment["CLASSPATH"]?.split(separator: ":").map(String.init) ?? []
86-
print("[debug][swift-java] Base classpath from CLASSPATH environment: \(classpathFromEnv)")
87+
log.debug("Base classpath from CLASSPATH environment: \(classpathFromEnv)")
8788
let classpathFromConfig: [String] = config.classpath?.split(separator: ":").map(String.init) ?? []
88-
print("[debug][swift-java] Base classpath from config: \(classpathFromConfig)")
89+
log.debug("Base classpath from config: \(classpathFromConfig)")
8990

9091
var classpathEntries: [String] = classpathFromConfig
9192

9293
for searchDir in searchDirs {
9394
let classPathFilesSearchDirectory = searchDir.path
94-
print("[debug][swift-java] Search *.swift-java.classpath in: \(classPathFilesSearchDirectory)")
95+
log.debug("Search *.swift-java.classpath in: \(classPathFilesSearchDirectory)")
9596
let foundSwiftJavaClasspath = findSwiftJavaClasspaths(in: classPathFilesSearchDirectory)
9697

97-
print("[debug][swift-java] Classpath from *.swift-java.classpath files: \(foundSwiftJavaClasspath)")
98+
log.debug("Classpath from *.swift-java.classpath files: \(foundSwiftJavaClasspath)")
9899
classpathEntries += foundSwiftJavaClasspath
99100
}
100101

101102
if !classpathOptionEntries.isEmpty {
102-
print("[debug][swift-java] Classpath from options: \(classpathOptionEntries)")
103+
log.debug("Classpath from options: \(classpathOptionEntries)")
103104
classpathEntries += classpathOptionEntries
104105
} else {
105106
// * Base classpath from CLASSPATH env variable
106-
print("[debug][swift-java] Classpath from environment: \(classpathFromEnv)")
107+
log.debug("Classpath from environment: \(classpathFromEnv)")
107108
classpathEntries += classpathFromEnv
108109
}
109110

110111
let extraClasspath = self.commonJVMOptions.classpath
111112
let extraClasspathEntries = extraClasspath.split(separator: ":").map(String.init)
112-
print("[debug][swift-java] Extra classpath: \(extraClasspathEntries)")
113+
log.debug("Extra classpath: \(extraClasspathEntries)")
113114
classpathEntries += extraClasspathEntries
114115

115116
// Bring up the Java VM when necessary
116117

117-
// if logLevel >= .debug {
118+
if log.logLevel >= .debug {
118119
let classpathString = classpathEntries.joined(separator: ":")
119-
print("[debug][swift-java] Initialize JVM with classpath: \(classpathString)")
120-
// }
120+
log.debug("Initialize JVM with classpath: \(classpathString)")
121+
}
121122

122123
return classpathEntries
123124
}

Sources/SwiftJavaTool/SwiftJavaBaseAsyncParsableCommand.swift

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,13 @@ import SwiftSyntax
2424
import SwiftSyntaxBuilder
2525
import SwiftJavaConfigurationShared
2626
import SwiftJavaShared
27+
import Logging
2728

2829
protocol SwiftJavaBaseAsyncParsableCommand: AsyncParsableCommand {
29-
var logLevel: Logger.Level { get set }
30+
31+
var log: Logging.Logger { get }
32+
33+
var logLevel: JExtractSwiftLib.Logger.Level { get set }
3034

3135
/// Must be implemented with an `@OptionGroup` in Command implementations
3236
var commonOptions: SwiftJava.CommonOptions { get set }
@@ -45,21 +49,21 @@ extension SwiftJavaBaseAsyncParsableCommand {
4549

4650
extension SwiftJavaBaseAsyncParsableCommand {
4751
public mutating func run() async {
48-
print("[info][swift-java] Run \(Self.self): \(CommandLine.arguments.joined(separator: " "))")
49-
print("[info][swift-java] Current work directory: \(URL(fileURLWithPath: ".").path)")
52+
self.log.info("Run \(Self.self): \(CommandLine.arguments.joined(separator: " "))")
53+
self.log.info("Current work directory: \(URL(fileURLWithPath: ".").path)")
5054

5155
do {
5256
var config = try readInitialConfiguration(command: self)
5357
try await runSwiftJavaCommand(config: &config)
5458
} catch {
5559
// We fail like this since throwing out of the run often ends up hiding the failure reason when it is executed as SwiftPM plugin (!)
5660
let message = "Failed with error: \(error)"
57-
print("[error][java-swift] \(message)")
61+
self.log.error("\(message)")
5862
fatalError(message)
5963
}
6064

6165
// Just for debugging so it is clear which command has finished
62-
print("[debug][swift-java] " + "Done: ".green + CommandLine.arguments.joined(separator: " ").green)
66+
self.log.debug("\("Done: ".green) \(CommandLine.arguments.joined(separator: " ").green)")
6367
}
6468
}
6569

@@ -95,7 +99,11 @@ extension SwiftJavaBaseAsyncParsableCommand {
9599

96100

97101
extension SwiftJavaBaseAsyncParsableCommand {
98-
var logLevel: Logger.Level {
102+
var log: Logging.Logger { // FIXME: replace with stored property inside specific commands
103+
.init(label: "swift-java")
104+
}
105+
106+
var logLevel: JExtractSwiftLib.Logger.Level {
99107
get {
100108
self.commonOptions.logLevel
101109
}

0 commit comments

Comments
 (0)