-
Notifications
You must be signed in to change notification settings - Fork 5
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
Yasumoto
wants to merge
7
commits into
vapor-community:master
Choose a base branch
from
Yasumoto:yasumoto-middleware-approach
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 5 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
5c0d570
Use the latest & greatest SwiftPrometheus, and utilize Middleware ins…
Yasumoto 5bc2030
Use new NIO1 alpha
Yasumoto 7b8fc78
Register PrometheusClient
Yasumoto c1fca27
Pin to 0.0.0 version so we don't get old 0.3.0
Yasumoto a4725a5
Use 0.4.0 for SwiftPrometheus
Yasumoto 5cb8c9f
Only track the top-level path, correct duration, add a test
Yasumoto d8ee3bc
Review feedback, more comments, and tidying headers
Yasumoto File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,4 +3,5 @@ Packages | |
*.xcodeproj | ||
Package.pins | ||
Package.resolved | ||
.DS_Store | ||
.DS_Store | ||
.swiftpm |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"]) | ||
] | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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). |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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? | ||
} | ||
} | ||
|
||
extension MetricsMiddleware: ServiceType { | ||
public static func makeService(for container: Container) throws -> MetricsMiddleware { | ||
return MetricsMiddleware() | ||
} | ||
} |
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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 :)
There was a problem hiding this comment.
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.