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 5 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
11 changes: 6 additions & 5 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
// swift-tools-version:4.0
// swift-tools-version:5.0

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/apple/swift-metrics.git", from: "1.0.0"),
.package(url: "https://github.com/MrLotU/SwiftPrometheus.git", from: "0.4.0-alpha.1"),
.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")
],
targets: [
.target(name: "VaporMonitoring", dependencies: ["Vapor", "SwiftMetrics", "SwiftPrometheus"]),
.target(name: "VaporMonitoring", dependencies: ["Metrics", "SwiftPrometheus", "Vapor"]),
.target(name: "MonitoringExample", 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.

48 changes: 48 additions & 0 deletions Sources/VaporMonitoring/MetricsMiddleware.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
//
// MetricsMiddleware.swift
// VaporMonitoring
//
// Created by Joe Smith on 07/15/2019.
//

import Metrics
import Vapor

/// Middleware to track in per-request metrics
///
/// Based [off the RED Method](https://www.weave.works/blog/the-red-method-key-metrics-for-microservices-architecture/)
public final class MetricsMiddleware {
public let requestsCounterLabel = "http_requests_total"
public let requestsTimerLabel = "http_requests_duration_seconds"
// private let requestErrorsCounter = Metrics.Counter(label: "http_request_errors_total", dimensions: [(String, String)]()) NEED TO ADD ERRORS

public init() { }
}

extension MetricsMiddleware: Middleware {
public func respond(to request: Request, chainingTo next: Responder) throws -> EventLoopFuture<Response> {
let start = Date()
let response: Future<Response>
do {
response = try next.respond(to: request)
} catch {
response = request.eventLoop.newFailedFuture(error: error)
}
return response.map { response in
let dimensions = [
("method", request.http.method.string),
("path", request.http.url.path),
("status_code", "\(response.http.status.code)")]
Metrics.Counter(label: self.requestsCounterLabel, dimensions: dimensions).increment()
let duration = start.timeIntervalSinceNow * -1
Metrics.Timer(label: self.requestsTimerLabel, dimensions: dimensions).record(duration)
return response
} // should we also handle the failed future too?
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Depending on if we're in front or behind the Error Middleware, we might want to. I'm not sure how this would work in combination with 4xx or 5xx errors. I'll do some research :)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this threads the needle right— if it's been converted to a "response" then we'll properly track the status code, otherwise, we have a separate Error counter which doesn't have the status code at all.

}
}

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