Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use the latest & greatest SwiftPrometheus, and utilize Middleware #5

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ Packages
*.xcodeproj
Package.pins
Package.resolved
.DS_Store
.DS_Store
.swiftpm
16 changes: 9 additions & 7 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
// swift-tools-version:4.0
// swift-tools-version:4.2

import PackageDescription

let package = Package(
name: "VaporMonitoring",
products: [
.library(name: "VaporMonitoring", targets: ["VaporMonitoring"])
.library(name: "VaporMonitoring", targets: ["VaporMonitoring"]),
.executable(name: "MonitoringExample", targets: ["MonitoringExample"])
],
dependencies: [
.package(url: "https://github.com/vapor/vapor.git", from: "3.1.0"),
.package(url: "https://github.com/RuntimeTools/SwiftMetrics.git", from: "2.3.0"),
.package(url: "https://github.com/MrLotU/SwiftPrometheus.git", from: "0.2.0")
.package(url: "https://github.com/apple/swift-metrics.git", from: "1.2.0"),
.package(url: "https://github.com/Yasumoto/SwiftPrometheus.git", .branch("nio1")),
.package(url: "https://github.com/vapor/vapor.git", from: "3.0.0")
],
targets: [
.target(name: "VaporMonitoring", dependencies: ["Vapor", "SwiftMetrics", "SwiftPrometheus"]),
.target(name: "MonitoringExample", dependencies: ["VaporMonitoring"])
.target(name: "VaporMonitoring", dependencies: ["Metrics", "SwiftPrometheus", "Vapor"]),
.target(name: "MonitoringExample", dependencies: ["VaporMonitoring"]),
.testTarget(name: "VaporMonitoringTests", dependencies: ["VaporMonitoring"])
]
)
51 changes: 36 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,36 +1,57 @@
# VaporMonitoring
[![Vapor 3](https://img.shields.io/badge/vapor-3.0-blue.svg?style=flat)](https://vapor.codes)
[![Swift 4.1](https://img.shields.io/badge/swift-4.2-orange.svg?style=flat)](http://swift.org)
[![Swift 4.2](https://img.shields.io/badge/swift-4.2-orange.svg?style=flat)](http://swift.org)

##
## Introduction

`VaporMonitoring` is a Vapor 3 package for monitoring and providing metrics for your Vapor application. Built on top op [SwiftMetrics](https://github.com/RuntimeTools/SwiftMetrics) and [SwiftPrometheus](https://github.com/MrLotU/SwiftPrometheus). Vapor Monitoring provides the default SwiftMetrics metrics along with request specific metrics. Metrics are exposed using Prometheus.
`VaporMonitoring` is a Vapor 3 package for monitoring and providing metrics for your Vapor application. Built on top of [the `swift-metrics` package](https://github.com/apple/swift-metrics) it also provides a helper to bootstrap [SwiftPrometheus](https://github.com/MrLotU/SwiftPrometheus). `VaporMonitoring` provides middleware which will [track metrics using the `RED` method for your application](https://www.weave.works/blog/the-red-method-key-metrics-for-microservices-architecture/):

1. Request Count
2. Error Count
3. Duration of each request

It breaks these out by URL path, status code, and method for fine-grained insight.

## Installation

Vapor Monitoring can be installed using SPM

```swift
.package(url: "https://github.com/vapor-community/VaporMonitoring.git", from: "2.0.0")
.package(url: "https://github.com/vapor-community/VaporMonitoring.git", from: "3.0.0")
```

## Usage
Vapor Monitoring is easy to use, it requires only a few lines of code.

Vapor Monitoring requires a few things to work correclty, a `MonitoredRouter` and a `MonitoredResponder` are the most important ones.
### `MetricsMiddleware`

Most folks will want easy integration with `swift-metrics`, in which case you should use `MetricsMiddleware`.

Once you've brought the package into your project, you'll need to `import VaporMonitoring` in your `Configure.swift` file. Inside, you'll create a `MetricsMiddleware`:

To set up your monitoring, in your `Configure.swift` file, add the following:
```swift
let router = try VaporMonitoring.setupMonitoring(&config, &services)
services.register(router, as: Router.self)
services.register(MetricsMiddleware(), as: MetricsMiddleware.self)

var middlewares = MiddlewareConfig()
middlewares.use(MetricsMiddleware.self)
// Add other middleware, such as the Vapor-provided
middlewares.use(ErrorMiddleware.self)
services.register(middlewares)
```

What this does is load VaporMonitoring with the default configuration. This includes adding all required services to your apps services & setting some configuration prefferences to use the `MonitoredResponder` and `MonitoredRouter`.
This will place the monitoring inside your application, tracking incoming requests + outgoing responses, and calculating how long it takes for each to complete.

*Note*: Place the `MetricsMiddleware` in your `MiddlewareConfig` as early as possible (preferably first) so you can track the entire duration.

By default, your prometheus metrics will be served at `host:port/metrics` and routes that don't have a routing closure, will be ignored to avoid exploding your prometheus logs. You can however customize this.
### Prometheus Integration

If you'd like to take advantage of a Prometheus installation, you'll need to export the `/metrics` endpoint in your list of routes:

To customize your monitoring, add this to `Configure.swift`
```swift
let monitoringConfg = MonitoringConfig(prometheusRoute: "customRoute", onlyBuiltinRoutes: false)
let router = try VaporMonitoring.setupMonitoring(&config, &services, monitoringConfg)
let router = EngineRouter.default()
try routes(router)
let prometheusService = VaporPrometheus(router: router, route: "metrics")
services.register(prometheusService)
services.register(router, as: Router.self)
```
In this case, you'd have your prometheus metrics at `host:port/customRoute`.

This will bootstrap `SwiftPrometheus` as your chosen backend, and also export metrics on `/metrics` (by default).
13 changes: 6 additions & 7 deletions Sources/MonitoringExample/main.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import Vapor
import VaporMonitoring
import SwiftMetrics

public func routes(_ router: Router) throws {
// Basic "Hello, world!" example
Expand All @@ -11,16 +10,16 @@ public func routes(_ router: Router) throws {

/// Called before your application initializes.
public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
/// Register routes to the router

let mConfig = MonitoringConfig(prometheusRoute: "metrics", onlyBuiltinRoutes: true)
let router = try VaporMonitoring.setupMonitoring(&config, &services, mConfig)

services.register(MetricsMiddleware(), as: MetricsMiddleware.self)
var middlewares = MiddlewareConfig()
middlewares.use(MetricsMiddleware.self)
middlewares.use(ErrorMiddleware.self)
services.register(middlewares)


let router = EngineRouter.default()
try routes(router)
let prometheusService = VaporPrometheus(router: router, services: &services)
services.register(prometheusService)
services.register(router, as: Router.self)
}

Expand Down
57 changes: 0 additions & 57 deletions Sources/VaporMonitoring/Extensions.swift

This file was deleted.

61 changes: 61 additions & 0 deletions Sources/VaporMonitoring/MetricsMiddleware.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import Metrics
import Vapor

/// Middleware to track in per-request metrics
///
/// This middleware is "backend-agnostic" and can be used with any `swift-metrics`-compatible
/// implementation. It is based
/// [off the RED Method](https://www.weave.works/blog/the-red-method-key-metrics-for-microservices-architecture/)
public final class MetricsMiddleware {
let requestsCounterLabel = "http_requests_total"
let requestsTimerLabel = "http_requests_duration_seconds"
let requestErrorsLabel = "http_request_errors_total"

public init() { }
}

// We track the start time of each request, then when it comes "back out" and toward the client
// we can specify the total duration of the request.
extension MetricsMiddleware: Middleware {
public func respond(to request: Request, chainingTo next: Responder) throws -> EventLoopFuture<Response> {
let start = Date().timeIntervalSince1970
let response: Future<Response>
do {
response = try next.respond(to: request)
} catch {
response = request.eventLoop.newFailedFuture(error: error)
}

_ = response.map { response in
self.updateMetrics(for: request, responseCounterName: self.requestsCounterLabel, start: start, statusCode: response.http.status.code)
}.mapIfError { error in
self.updateMetrics(for: request, responseCounterName: self.requestErrorsLabel, start: start)
}

return response
}

private func updateMetrics(for request: Request, responseCounterName: String, start: Double, statusCode: UInt? = nil) {
let topLevel = String(request.http.url.path.split(separator: "/").first ?? "/")
var counterDimensions = [
("method", request.http.method.string),
("path", topLevel)]
if let statusCode = statusCode {
counterDimensions.append(("status_code", "\(statusCode)"))
}
let timerDimensions = [
("method", request.http.method.string),
("path", topLevel)]
let end = Date().timeIntervalSince1970
let duration = end - start

Metrics.Counter(label: responseCounterName, dimensions: counterDimensions).increment()
Metrics.Timer(label: self.requestsTimerLabel, dimensions: timerDimensions, preferredDisplayUnit: .seconds).recordSeconds(duration)
}
}

extension MetricsMiddleware: ServiceType {
public static func makeService(for container: Container) throws -> MetricsMiddleware {
return MetricsMiddleware()
}
}
60 changes: 0 additions & 60 deletions Sources/VaporMonitoring/Responder+Monitoring.swift

This file was deleted.

64 changes: 0 additions & 64 deletions Sources/VaporMonitoring/Router+Monitoring.swift

This file was deleted.

Loading