|
13 | 13 | import Foundation
|
14 | 14 |
|
15 | 15 | public final class LoggingScope {
|
| 16 | + /// The name of the current logging subsystem or `nil` if no logging scope is set. |
| 17 | + @TaskLocal fileprivate static var _subsystem: String? |
| 18 | + |
16 | 19 | /// The name of the current logging scope or `nil` if no logging scope is set.
|
17 | 20 | @TaskLocal fileprivate static var _scope: String?
|
18 | 21 |
|
| 22 | + /// The name of the current logging subsystem. |
| 23 | + public static var subsystem: String { |
| 24 | + return _subsystem ?? "org.swift.sourcekit-lsp" |
| 25 | + } |
| 26 | + |
19 | 27 | /// The name of the current logging scope.
|
20 | 28 | public static var scope: String {
|
21 | 29 | return _scope ?? "default"
|
22 | 30 | }
|
23 | 31 | }
|
24 | 32 |
|
| 33 | +/// Logs all messages created from the operation to the given subsystem. |
| 34 | +/// |
| 35 | +/// This overrides the current logging subsystem. |
| 36 | +/// |
| 37 | +/// - Note: Since this stores the logging subsystem in a task-local value, it only works when run inside a task. |
| 38 | +/// Outside a task, this is a no-op. |
| 39 | +public func withLoggingSubsystemAndScope<Result>( |
| 40 | + subsystem: String, |
| 41 | + scope: String?, |
| 42 | + _ operation: () throws -> Result |
| 43 | +) rethrows -> Result { |
| 44 | + return try LoggingScope.$_subsystem.withValue(subsystem) { |
| 45 | + return try LoggingScope.$_scope.withValue(scope, operation: operation) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +/// Same as `withLoggingSubsystemAndScope` but allows the operation to be `async`. |
| 50 | +public func withLoggingSubsystemAndScope<Result>( |
| 51 | + subsystem: String, |
| 52 | + scope: String?, |
| 53 | + _ operation: () async throws -> Result |
| 54 | +) async rethrows -> Result { |
| 55 | + return try await LoggingScope.$_subsystem.withValue(subsystem) { |
| 56 | + return try await LoggingScope.$_scope.withValue(scope, operation: operation) |
| 57 | + } |
| 58 | +} |
| 59 | + |
25 | 60 | /// Create a new logging scope, which will be used as the category in any log messages created from the operation.
|
26 | 61 | ///
|
27 | 62 | /// This overrides the current logging scope.
|
|
0 commit comments