SkillAgentSearch skills...

SwiftMetrics

Swift Application Metrics instruments the Swift runtime for performance monitoring, providing the monitoring data programatically via an API or visually with an Eclipse Client.

Install / Use

/learn @RuntimeTools/SwiftMetrics

README

Build Status codebeat badge codecov.io macOS Linux Apache 2  Slack Status Homepage

Application Metrics for Swift

Application Metrics for Swift instruments the Swift runtime for performance monitoring, providing the monitoring data programatically via an API or visually with its built-in dashboard.

Application Metrics for Swift provides the following built-in data collection sources:

Source | Description :-------------------|:------------------------------------------- Environment | Machine and runtime environment information CPU | Process and system CPU Memory | Process and system memory usage Latency | Dispatch Queue latency

SwiftMetricsKitura adds the additional collection source:

Source | Description :-------------------|:------------------------------------------- HTTP | HTTP metric information

Getting Started

Prerequisites

The Application Metrics for Swift agent supports the following runtime environments:

  • Swift v4.2 GA on:
    • 64-bit runtime on Linux (Ubuntu 14.04, 16.04)
    • 64-bit runtime on macOS (x64)
  • Swift v4.1 GA on:
    • 64-bit runtime on Linux (Ubuntu 14.04, 16.04)
    • 64-bit runtime on macOS (x64)
  • Swift v4 GA on:
    • 64-bit runtime on Linux (Ubuntu 14.04, 16.04)
    • 64-bit runtime on macOS (x64)
  • Swift v3.1.1 GA using SwiftMetrics version 1.2.5 on:
    • 64-bit runtime on Linux (Ubuntu 14.04, 15.10)
    • 64-bit runtime on macOS (x64)

<a name="install"></a>

Installation

Application Metrics for Swift can be installed by adding a dependency into your Package.swift file and updating your targets to include SwiftMetrics as a dependency:

   dependencies: [
      .package(url: "https://github.com/RuntimeTools/SwiftMetrics.git", from: "2.4.0")
   ]
   ...
   targets: [
      .target(name: "MyApp", dependencies: ["SwiftMetrics"], path: "Sources")]

Swift Package manager will automatically clone the code required and build it during compilation of your program:

  • Linux: swift build
  • macOS: swift build -Xlinker -lc++

<a name="config"></a>

Configuring Application Metrics for Swift

Once Application Metrics for Swift is added as a dependency to your Swift application, you should find a configuration file inside the .build folder, .build/checkouts/SwiftMetrics.git--<id>/swiftmetrics.properties (or the Packages directory for older versions of Swift, Packages/SwiftMetrics-<version>/swiftmetrics.properties). This is used to configure connection options, logging and data source options.

Application Metrics for Swift will attempt to load swiftmetrics.properties from one of the following locations (in order):

  1. The current working directory.
  2. The .build/checkouts/SwiftMetrics.git--<id> directory (or Packages/SwiftMetrics-<version> for older versions of Swift).

Please note that the default configuration has minimal logging enabled.

Running Application Metrics for Swift

<a name="run-local"></a>

Modifying your application

To load SwiftMetrics and get the base monitoring API, add the following to the start-up code for your application:

import SwiftMetrics

let sm = try SwiftMetrics()
let monitoring = sm.monitor()

If you would like to monitor Kitura HTTP data as well, then use the following instead:

import SwiftMetrics
import SwiftMetricsKitura

let sm = try SwiftMetrics()
SwiftMetricsKitura(swiftMetricsInstance: sm)
let monitoring = sm.monitor()

Application Metrics for Swift Dashboard

To use the built in dashboard, you add the following code to your application

import SwiftMetrics
import SwiftMetricsDash

// Enable SwiftMetrics Monitoring
let sm = try SwiftMetrics()   

// Pass SwiftMetrics to the dashboard for visualising
let smd = try SwiftMetricsDash(swiftMetricsInstance : sm)  

By default, SwiftMetricsDash will start its own Kitura server and serve the page up under http://<hostname>:<port>/swiftmetrics-dash

The port being used is logged to the console when your application starts:

  • SwiftMetricsDash : Starting on port 8080

Prometheus Support

To use SwiftMetrics to provide a Prometheus endpoint, you add the following code to your application

import SwiftMetrics
import SwiftMetricsPrometheus

// Enable SwiftMetrics Monitoring
let sm = try SwiftMetrics()   

// Pass SwiftMetrics to SwiftMetricsPrometheus
let smp = try SwiftMetricsPrometheus(swiftMetricsInstance : sm)

By default, SwiftMetricsPrometheus will provide the Prometheus endpoint under http://<hostname>:<port>/metrics

The port being used is logged to the console when your application starts:

  • SwiftMetricsPrometheus : Starting on port 8080

Application Metrics for Swift Agent

SwiftMetrics() returns the Application Metrics for Swift Agent - this runs parallel to your code and receives and emits data about your application to any connected clients. The sm.monitor() call returns a Application Metrics for Swift Local Client, connected to the Agent sm over a local connection.

You can then use the monitoring object to register callbacks and request information about the application:

monitoring.on({ (env: InitData) in
   for (key, value) in env {
      print("\(key): \(value)\n")
   }
})

func processCPU(cpu: CPUData) {
   print("\nThis is a custom CPU event response.\n cpu.timeOfSample = \(cpu.timeOfSample),\n cpu.percentUsedByApplication = \(cpu.percentUsedByApplication),\n cpu.percentUsedBySystem = \(cpu.percentUsedBySystem).\n")
}

monitoring.on(processCPU)

In order to monitor your own custom data, you need to implement a struct that implements the base SwiftMetrics data protocol, SMData. This has no required fields so you can put in just the data you're interested in.

private struct SnoozeData: SMData {
   let cycleCount: Int
}

private func snoozeMessage(data: SnoozeData) {
   print("\nAlarm has been ignored for \(data.cycleCount) seconds!\n")
}

monitoring.on(snoozeMessage)

sm.emitData(SnoozeData(cycleCount: 40))

//prints "Alarm has been ignored for 40 seconds!"

<a name="api-doc"></a>

API Documentation

SwiftMetrics.start()

Starts the Application Metrics for Swift Agent. If the agent is already running this function does nothing.

SwiftMetrics.stop()

Stops the Application Metrics for Swift Agent. If the agent is not running this function does nothing.

SwiftMetrics.setPluginSearch(toDirectory: URL)

Sets the directory that Application Metrics for Swift will look in for data source / connector plugins.

SwiftMetrics.monitor() -> SwiftMonitor

Creates a Application Metrics for Swift Local Client instance, connected to the Application Metrics for Swift Agent specified by 'SwiftMetrics'. This can subsequently be used to get environment data and subscribe to data generated by the Agent.. This function will start the Application Metrics for Swift Agent if it is not already running.

SwiftMetrics.emitData<T: SMData( _: T)

Allows you to emit custom Data specifying the type of Data as a string. Data to pass into the event must implement the SMData protocol.

SwiftMonitor.getEnvironmentData() -> [ String : String ]

Requests a Dictionary object containing all of the available environment information for the running application. If called before the 'initialized' event has been emitted, this will contain either incomplete data or no data.

SwiftMonitor.on<T: SMData>((T) -> ())

If you supply a closure that takes either a pre-supplied API struct or your own custom struct that implements the SMData protocol, and returns nothing, then that closure will run when the data in question is emitted.

SwiftMetricsKitura(swiftMetricsInstance: SwiftMetrics) (when importing SwiftMetricsKitura)

Creates a SwiftMetricsKitura instance, which will monitor Kitura HTTP metrics and emit them via the SwiftMetrics instance specified.

SwiftMetricsBluemix(swiftMetricsInstance: SwiftMetrics) (when importing SwiftMetricsBluemix)

Creates a SwiftMetricsBluemix instance, which will send metrics to the [Auto Scale service][4]

<a name="api-structs"></a>

API Data Structures

All of the following structures implement the SMData protocol to identify them as available to be used by SwiftMetrics.

public protocol SMData {
}

CPU data structure

Emitted when a CPU monitoring sample is taken.

  • public struct CPUData: SMData
    • timeOfSample (Int) the system time in milliseconds since epoch when the sample was taken.
    • percentUsedByApplication (Float) the percentage of CPU used by the Swift application itself. This is a value between 0.0 and 1.0.
    • percentUsedBySystem (Float) the percentage of CPU used by the system a

Related Skills

View on GitHub
GitHub Stars157
CategoryOperations
Updated4d ago
Forks50

Languages

Swift

Security Score

85/100

Audited on Mar 28, 2026

No findings