Skip to content

Commit

Permalink
enabled swiftlint & fixed issues
Browse files Browse the repository at this point in the history
  • Loading branch information
bryce-b committed Dec 14, 2024
1 parent 85c4a95 commit d5c31f9
Show file tree
Hide file tree
Showing 272 changed files with 6,774 additions and 6,504 deletions.
17 changes: 17 additions & 0 deletions .swiftlint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
included:
- "Sources"
excluded:
- "Sources/Exporters/OpenTelemetryProtocolCommon/proto"
disabled_rules:
- nesting
- line_length
- type_body_length
- identifier_name
- file_length
- force_cast
- type_name
- large_tuple
- function_body_length
- function_parameter_count
- cyclomatic_complexity
- force_try
2 changes: 1 addition & 1 deletion Examples/Datadog Sample/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ sleep(10)

func testTraces() {
let spanProcessor = SimpleSpanProcessor(spanExporter: datadogExporter)

OpenTelemetry.registerTracerProvider(tracerProvider:
TracerProviderBuilder()
.add(spanProcessor: spanProcessor)
Expand Down
16 changes: 6 additions & 10 deletions Examples/Logs Sample/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,15 @@ import Logging
import GRPC
import NIO


func configure() {
let configuration = ClientConnection.Configuration.default(
target: .hostAndPort("localhost", 4317),
eventLoopGroup: MultiThreadedEventLoopGroup(numberOfThreads: 1))
target: .hostAndPort("localhost", 4317),
eventLoopGroup: MultiThreadedEventLoopGroup(numberOfThreads: 1))

OpenTelemetry.registerLoggerProvider(loggerProvider: LoggerProviderBuilder().with(processors: [
BatchLogRecordProcessor(logRecordExporter:OtlpLogExporter(channel: ClientConnection(configuration: configuration)))]).build())

}
OpenTelemetry.registerLoggerProvider(loggerProvider: LoggerProviderBuilder().with(processors: [
BatchLogRecordProcessor(logRecordExporter: OtlpLogExporter(channel: ClientConnection(configuration: configuration)))]).build())
}

configure()

let eventProvider = OpenTelemetry.instance.loggerProvider.loggerBuilder(instrumentationScopeName: "myScope").setEventDomain("device").build()


9 changes: 3 additions & 6 deletions Examples/Network Sample/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,15 @@ import OpenTelemetrySdk
import StdoutExporter
import URLSessionInstrumentation


func simpleNetworkCall() {
let url = URL(string: "http://httpbin.org/get")!
let request = URLRequest(url: url)
let semaphore = DispatchSemaphore(value: 0)

let task = URLSession.shared.dataTask(with: request) { data, _, _ in
if let data = data {
let string = String(decoding: data, as: UTF8.self)
print(string)
let string = String(bytes: data, encoding: .utf8)
print(string as Any)
}
semaphore.signal()
}
Expand All @@ -27,7 +26,6 @@ func simpleNetworkCall() {
semaphore.wait()
}


class SessionDelegate: NSObject, URLSessionDataDelegate, URLSessionTaskDelegate {
let semaphore = DispatchSemaphore(value: 0)

Expand All @@ -39,7 +37,7 @@ let delegate = SessionDelegate()

func simpleNetworkCallWithDelegate() {

let session = URLSession(configuration: .default, delegate: delegate, delegateQueue:nil)
let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)

let url = URL(string: "http://httpbin.org/get")!
let request = URLRequest(url: url)
Expand All @@ -50,7 +48,6 @@ func simpleNetworkCallWithDelegate() {
delegate.semaphore.wait()
}


let spanProcessor = SimpleSpanProcessor(spanExporter: StdoutSpanExporter(isDebug: true))
OpenTelemetry.registerTracerProvider(tracerProvider:
TracerProviderBuilder()
Expand Down
2 changes: 0 additions & 2 deletions Examples/OTLP Exporter/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ OpenTelemetry.registerTracerProvider(tracerProvider:

let tracer = OpenTelemetry.instance.tracerProvider.get(instrumentationName: instrumentationScopeName, instrumentationVersion: instrumentationScopeVersion)


if #available(macOS 10.14, *), #available(iOS 12.0, *) {
let tracerProviderSDK = OpenTelemetry.instance.tracerProvider as? TracerProviderSdk
tracerProviderSDK?.addSpanProcessor(SignPostIntegration())
Expand Down Expand Up @@ -88,7 +87,6 @@ let meterProvider = MeterProviderSdk(metricProcessor: processor, metricExporter:

OpenTelemetry.registerMeterProvider(meterProvider: meterProvider)


let labels1 = ["dim1": "value1"]

var meter = meterProvider.get(instrumentationName: "otlp_example_meter'")
Expand Down
5 changes: 2 additions & 3 deletions Examples/OTLP HTTP Exporter/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,15 @@ func createSpans() {
doWork()
}
Thread.sleep(forTimeInterval: 0.5)

let parentSpan2 = tracer.spanBuilder(spanName: "Another").setSpanKind(spanKind: .client).setActive(true).startSpan()
parentSpan2.setAttribute(key: sampleKey, value: sampleValue)
// do more Work
for _ in 1...3 {
doWork()
}
Thread.sleep(forTimeInterval: 0.5)

parentSpan2.end()
parentSpan1.end()
}
Expand All @@ -78,7 +78,6 @@ let meterProvider = MeterProviderSdk(metricProcessor: processor, metricExporter:

OpenTelemetry.registerMeterProvider(meterProvider: meterProvider)


var meter = meterProvider.get(instrumentationName: "otlp_example_meter'")
var exampleCounter = meter.createIntCounter(name: "otlp_example_counter")
var exampleMeasure = meter.createIntMeasure(name: "otlp_example_measure")
Expand Down
5 changes: 2 additions & 3 deletions Examples/Prometheus Sample/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import PrometheusExporter
print("Hello Prometheus")

//
//You should use here your real local address, change it also in the prometheus.yml file
// You should use here your real local address, change it also in the prometheus.yml file
let localAddress = "192.168.1.28"
//

Expand All @@ -30,7 +30,6 @@ DispatchQueue.global(qos: .default).async {

let processor = MetricProcessorSdk()


let meterProvider = MeterProviderSdk(metricProcessor: processor, metricExporter: promExporter, metricPushInterval: 0.1)
OpenTelemetry.registerMeterProvider(meterProvider: meterProvider)

Expand All @@ -39,7 +38,7 @@ var meter = meterProvider.get(instrumentationName: "MyMeter")
var testCounter = meter.createIntCounter(name: "MyCounter")
var testMeasure = meter.createIntMeasure(name: "MyMeasure")

let boundaries: Array<Int> = [5, 10, 25]
let boundaries: [Int] = [5, 10, 25]
var testHistogram = meter.createIntHistogram(name: "MyHistogram", explicitBoundaries: boundaries, absolute: true)

var testObserver = meter.createIntObserver(name: "MyObservation") { observer in
Expand Down
9 changes: 9 additions & 0 deletions Package.resolved
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,15 @@
"version" : "1.3.0"
}
},
{
"identity" : "swiftlintplugins",
"kind" : "remoteSourceControl",
"location" : "https://github.com/SimplyDanny/SwiftLintPlugins",
"state" : {
"revision" : "f9731bef175c3eea3a0ca960f1be78fcc2bc7853",
"version" : "0.57.1"
}
},
{
"identity" : "thrift-swift",
"kind" : "remoteSourceControl",
Expand Down
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ let package = Package(
.library(name: "ResourceExtension", type: .static, targets: ["ResourceExtension"]),
.library(name: "URLSessionInstrumentation", type: .static, targets: ["URLSessionInstrumentation"]),
.library(name: "SignPostIntegration", type: .static, targets: ["SignPostIntegration"]),
.library(name: "OpenTracingShim-experimental", type: .static, targets: ["OpenTracingShim"]),
.library(name: " -experimental", type: .static, targets: ["OpenTracingShim"]),
.library(name: "SwiftMetricsShim", type: .static, targets: ["SwiftMetricsShim"]),
.library(name: "JaegerExporter", type: .static, targets: ["JaegerExporter"]),
.library(name: "ZipkinExporter", type: .static, targets: ["ZipkinExporter"]),
Expand Down
9 changes: 8 additions & 1 deletion Package@swift-5.9.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import PackageDescription
let package = Package(
name: "opentelemetry-swift",
platforms: [
.macOS(.v10_15),
.macOS(.v12),
.iOS(.v13),
.tvOS(.v13),
.watchOS(.v6),
Expand All @@ -33,6 +33,7 @@ let package = Package(
.package(url: "https://github.com/apple/swift-protobuf.git", from: "1.20.2"),
.package(url: "https://github.com/apple/swift-log.git", from: "1.4.4"),
.package(url: "https://github.com/apple/swift-metrics.git", from: "2.1.1"),
.package(url: "https://github.com/SimplyDanny/SwiftLintPlugins", from: "0.57.1")
],
targets: [
.target(name: "OpenTelemetryApi",
Expand Down Expand Up @@ -289,3 +290,9 @@ extension Package {
return self
}
}

for target in package.targets {
target.plugins = [
.plugin(name: "SwiftLintBuildToolPlugin", package: "SwiftLintPlugins"),
]
}
49 changes: 23 additions & 26 deletions Sources/Bridges/OTelSwiftLog/LogHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,19 @@ let version: String = "1.0.0"

/// A custom log handler to translate swift logs into otel logs
public struct OTelLogHandler: LogHandler {

/// Get or set the configured log level.
///
/// - note: `LogHandler`s must treat the log level as a value type. This means that the change in metadata must
/// only affect this very `LogHandler`. It is acceptable to provide some form of global log level override
/// that means a change in log level on a particular `LogHandler` might not be reflected in any
/// `LogHandler`.
public var logLevel: Logging.Logger.Level = .info

/// loggerProvider to use for the bridge.
private var loggerProvider : LoggerProvider
private var loggerProvider: LoggerProvider
private var logger: OpenTelemetryApi.Logger

// Define metadata for this handler
public var metadata: Logging.Logger.Metadata = [:]
public subscript(metadataKey key: String) -> Logging.Logger.Metadata.Value? {
Expand All @@ -31,15 +31,15 @@ public struct OTelLogHandler: LogHandler {
self.metadata[key] = newValue
}
}

/// create a new OtelLogHandler
/// - Parameter loggerProvider: The logger provider to use in the bridge. Defaults to the global logger provider.
/// - Parameter includeTraceContext : boolean flag used for the logger builder
/// - Parameter attributes: attributes to apply to the logger builder
public init(loggerProvider: LoggerProvider = OpenTelemetryApi.DefaultLoggerProvider.instance,
includeTraceContext : Bool = true,
attributes: [String:AttributeValue] = [String:AttributeValue]()) {
includeTraceContext: Bool = true,
attributes: [String: AttributeValue] = [String: AttributeValue]()) {

self.loggerProvider = loggerProvider
self.logger = self.loggerProvider.loggerBuilder(instrumentationScopeName: bridgeName)
.setInstrumentationVersion(version)
Expand All @@ -49,62 +49,59 @@ public struct OTelLogHandler: LogHandler {
.setIncludeTraceContext(includeTraceContext)
.build()
}

public func log(level: Logging.Logger.Level,
message: Logging.Logger.Message,
metadata: Logging.Logger.Metadata?,
source: String,
file: String,
function: String,
line: UInt) {



// This converts log atrributes to otel attributes
var otelattributes: [String: AttributeValue] = [
"source": AttributeValue.string(source),
"file": AttributeValue.string(file),
"function": AttributeValue.string(function),
"line": AttributeValue.int(Int(line)),
"line": AttributeValue.int(Int(line))
]

// Convert metadata from the method parameter to AttributeValue and assign it to otelattributes
if let metadata = metadata {
let methodMetadata = convertMetadata(metadata)
otelattributes.merge(methodMetadata) { _, new in new }
}

// Convert metadata from the struct property to AttributeValue and merge it with otelattributes
let structMetadata = convertMetadata(self.metadata)
otelattributes.merge(structMetadata) { _, new in new }

// Build the log record and emit it
let event = self.logger.logRecordBuilder().setSeverity(convertSeverity(level: level))
.setBody(AttributeValue.string(message.description))
.setAttributes(otelattributes)

if let context = OpenTelemetry.instance.contextProvider.activeSpan?.context {
_ = event.setSpanContext(context)
}
event.emit()

}




}

func convertMetadata(_ metadata: Logging.Logger.Metadata) -> [String: AttributeValue] {
var convertedAttributes: [String: AttributeValue] = [:]

// Iterate over each key-value pair in the metadata dictionary
for (key, value) in metadata {
// Convert each value to AttributeValue
let attributeValue = convertToAttributeValue(value)

// Store the converted value with its corresponding key in the attributes dictionary
convertedAttributes[key] = attributeValue
}

return convertedAttributes
}

Expand All @@ -126,11 +123,11 @@ func convertToAttributeValue(_ value: Logging.Logger.Metadata.Value) -> Attribut
return AttributeValue(str)
case .stringConvertible(let strConvertable):
return AttributeValue(strConvertable.description)

}
}

func convertSeverity(level: Logging.Logger.Level) -> OpenTelemetryApi.Severity{
func convertSeverity(level: Logging.Logger.Level) -> OpenTelemetryApi.Severity {
switch level {
case .trace:
return OpenTelemetryApi.Severity.trace
Expand All @@ -145,6 +142,6 @@ func convertSeverity(level: Logging.Logger.Level) -> OpenTelemetryApi.Severity{
case .error:
return OpenTelemetryApi.Severity.error
case .critical:
return OpenTelemetryApi.Severity.error2 //should this be fatal instead?
return OpenTelemetryApi.Severity.error2 // should this be fatal instead?
}
}
Loading

0 comments on commit d5c31f9

Please sign in to comment.