Skip to content

Commit

Permalink
Use HTTPClient.shared #2
Browse files Browse the repository at this point in the history
Use `HTTPClient.shared`
  • Loading branch information
MahdiBM authored Apr 12, 2024
2 parents c024555 + 55ddbbe commit aba0eaf
Show file tree
Hide file tree
Showing 7 changed files with 103 additions and 100 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ concurrency:
cancel-in-progress: true
on:
pull_request: { types: [opened, reopened, synchronize, ready_for_review] }
push: { branches: [ main ] }
push: { branches: [main] }

jobs:
tests:
uses: vapor/ci/.github/workflows/run-unit-tests.yml@reusable-workflows
uses: vapor/ci/.github/workflows/run-unit-tests.yml@main
with:
with_coverage: true
with_tsan: true
with_public_api_check: true
coverage_ignores: '/Tests/'
coverage_ignores: "/Tests/"
50 changes: 46 additions & 4 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// swift-tools-version: 5.7
// swift-tools-version: 5.9

import PackageDescription

Expand All @@ -19,21 +19,63 @@ let package = Package(
dependencies: [
.package(url: "https://github.com/apple/swift-nio.git", from: "2.49.0"),
.package(url: "https://github.com/apple/swift-log.git", from: "1.5.2"),
.package(url: "https://github.com/DiscordBM/DiscordBM.git", from: "1.0.0-beta.62"),
.package(url: "https://github.com/swift-server/async-http-client.git", from: "1.21.0"),
.package(url: "https://github.com/DiscordBM/DiscordBM.git", from: "1.0.0-rc.1"),
],
targets: [
.target(
name: "DiscordLogger",
dependencies: [
.product(name: "NIOCore", package: "swift-nio"),
.product(name: "Logging", package: "swift-log"),
.product(name: "AsyncHTTPClient", package: "async-http-client"),
.product(name: "DiscordHTTP", package: "DiscordBM"),
.product(name: "DiscordUtilities", package: "DiscordBM"),
]
],
swiftSettings: swiftSettings
),
.testTarget(
name: "DiscordLoggerTests",
dependencies: ["DiscordLogger"]
dependencies: ["DiscordLogger"],
swiftSettings: swiftSettings
),
]
)

var featureFlags: [SwiftSetting] {
[
/// `-enable-upcoming-feature` flags will get removed in the future
/// and we'll need to remove them from here too.

/// https://github.com/apple/swift-evolution/blob/main/proposals/0335-existential-any.md
/// Require `any` for existential types.
.enableUpcomingFeature("ExistentialAny"),

/// https://github.com/apple/swift-evolution/blob/main/proposals/0274-magic-file.md
/// Nicer `#file`.
.enableUpcomingFeature("ConciseMagicFile"),

/// https://github.com/apple/swift-evolution/blob/main/proposals/0286-forward-scan-trailing-closures.md
/// This one shouldn't do much to be honest, but shouldn't hurt as well.
.enableUpcomingFeature("ForwardTrailingClosures"),

/// https://github.com/apple/swift-evolution/blob/main/proposals/0354-regex-literals.md
/// `BareSlashRegexLiterals` not enabled since we don't use regex anywhere.

/// https://github.com/apple/swift-evolution/blob/main/proposals/0384-importing-forward-declared-objc-interfaces-and-protocols.md
/// `ImportObjcForwardDeclarations` not enabled because it's objc-related.
]
}

var experimentalFeatureFlags: [SwiftSetting] {
[
/// `DiscordBM` passes the `complete` level.
///
/// `minimal` / `targeted` / `complete`
.enableExperimentalFeature("StrictConcurrency=complete"),
]
}

var swiftSettings: [SwiftSetting] {
featureFlags + experimentalFeatureFlags
}
71 changes: 0 additions & 71 deletions Package@swift-5.8.swift

This file was deleted.

15 changes: 3 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,10 @@ Vapor community's [Penny bot](https://github.com/vapor/penny-bot) serves as a go
Penny uses `DiscordLogger` to send a select group of important logs to an internal channel, making it easy for maintainers to receive notifications about any potential issues.

## How To Use

> Make sure you have **Xcode 14.1 or above**. Lower Xcode 14 versions have known issues that cause problems for libraries.

Make sure you've added [swift-log](https://github.com/apple/swift-log) and [AsyncHTTPClient](https://github.com/swift-server/async-http-client) to your dependancies.
```swift
import DiscordLogger
import Logging
import AsyncHTTPClient

/// Make an `HTTPClient`.
/// If you've already made an `HTTPClient` somewhere else, you should use that instead.
let httpClient = HTTPClient(eventLoopGroupProvider: .createNew)

/// Configure the Discord Logging Manager.
DiscordGlobalConfiguration.logManager = await DiscordLogManager(httpClient: httpClient)

/// Bootstrap the `LoggingSystem`. After this, all your `Logger`s will automagically start using `DiscordLogHandler`.
/// Do not use a `Task { }` to avoid possible bugs. Wait before the `LoggingSystem` is bootstrapped.
Expand All @@ -60,8 +49,10 @@ Here is an example of a decently-configured `DiscordLogManager`:
> Read `DiscordLogManager.Configuration.init` documentation for full info.
```swift
let mySpecialHTTPClient: HTTPClient = ...

DiscordGlobalConfiguration.logManager = await DiscordLogManager(
httpClient: httpClient,
httpClient: mySpecialHTTPClient,
configuration: .init(
aliveNotice: .init(
address: try .url(<#Your Webhook URL#>),
Expand Down
2 changes: 1 addition & 1 deletion Sources/DiscordLogger/DiscordLogHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ public struct DiscordLogHandler: LogHandler {
)
)

let attachmentDisabled = logManager.configuration.sendFullLogAsAttachment.isDisabled
let attachmentDisabled = logManager.configuration.sendFullLogsAsAttachment.isDisabled
let attachment = attachmentDisabled ? nil : LogInfo(
level: level,
message: "\(message)",
Expand Down
53 changes: 47 additions & 6 deletions Sources/DiscordLogger/DiscordLogManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ public actor DiscordLogManager {

let frequency: Duration
let aliveNotice: AliveNotice?
let sendFullLogAsAttachment: LogAttachmentPolicy
let sendFullLogsAsAttachment: LogAttachmentPolicy
let mentions: [Logger.Level: [String]]
let colors: [Logger.Level: DiscordColor]
let excludeMetadata: Set<Logger.Level>
Expand All @@ -117,7 +117,7 @@ public actor DiscordLogManager {
/// - frequency: The frequency of the log-sendings. e.g. if its set to 30s, logs will only be sent once-in-30s. Should not be lower than 10s, because of Discord rate-limits.
/// - aliveNotice: Configuration for sending "I am alive" messages every once in a while. Note that alive notices are delayed until it's been `interval`-time past last message.
/// e.g. `Logger(label: "Fallback", factory: StreamLogHandler.standardOutput(label:))`
/// - sendFullLogAsAttachment: Whether or not to send the full log as an attachment.
/// - sendFullLogsAsAttachment: Whether or not to send the full log as an attachment.
/// The normal logs might need to truncate some stuff when sending as embeds, due to Discord limits.
/// - mentions: ID of users/roles to be mentioned for each log-level.
/// - colors: Color of the embeds to be used for each log-level.
Expand All @@ -129,7 +129,7 @@ public actor DiscordLogManager {
public init(
frequency: Duration = .seconds(10),
aliveNotice: AliveNotice? = nil,
sendFullLogAsAttachment: LogAttachmentPolicy = .disabled,
sendFullLogsAsAttachment: LogAttachmentPolicy = .disabled,
mentions: [Logger.Level: Mention] = [:],
colors: [Logger.Level: DiscordColor] = [
.critical: .purple,
Expand All @@ -148,7 +148,7 @@ public actor DiscordLogManager {
) {
self.frequency = frequency
self.aliveNotice = aliveNotice
self.sendFullLogAsAttachment = sendFullLogAsAttachment
self.sendFullLogsAsAttachment = sendFullLogsAsAttachment
self.mentions = mentions.mapValues { $0.toMentionStrings() }
self.colors = colors
self.excludeMetadata = excludeMetadata
Expand All @@ -157,6 +157,47 @@ public actor DiscordLogManager {
self.disabledInDebug = disabledInDebug
self.maxStoredLogsCount = maxStoredLogsCount
}

/// - Parameters:
/// - frequency: The frequency of the log-sendings. e.g. if its set to 30s, logs will only be sent once-in-30s. Should not be lower than 10s, because of Discord rate-limits.
/// - aliveNotice: Configuration for sending "I am alive" messages every once in a while. Note that alive notices are delayed until it's been `interval`-time past last message.
/// e.g. `Logger(label: "Fallback", factory: StreamLogHandler.standardOutput(label:))`
/// - sendFullLogAsAttachment: Whether or not to send the full log as an attachment.
/// The normal logs might need to truncate some stuff when sending as embeds, due to Discord limits.
/// - mentions: ID of users/roles to be mentioned for each log-level.
/// - colors: Color of the embeds to be used for each log-level.
/// - excludeMetadata: Excludes all metadata for these log-levels.
/// - extraMetadata: Will log `source`, `file`, `function` and `line` as well.
/// - disabledLogLevels: `Logger.Level`s to never be logged.
/// - disabledInDebug: Whether or not to disable logging in DEBUG.
/// - maxStoredLogsCount: If there are more logs than this count, the log manager will start removing the oldest un-sent logs to reduce memory consumption.
@available(
*,
unavailable,
renamed: "init(frequency:aliveNotice:sendFullLogsAsAttachment:mentions:colors:excludeMetadata:extraMetadata:disabledLogLevels:disabledInDebug:maxStoredLogsCount:)"
)
public init(
frequency: Duration = .seconds(10),
aliveNotice: AliveNotice? = nil,
sendFullLogAsAttachment: LogAttachmentPolicy = .disabled,
mentions: [Logger.Level: Mention] = [:],
colors: [Logger.Level: DiscordColor] = [
.critical: .purple,
.error: .red,
.warning: .orange,
.trace: .brown,
.debug: .yellow,
.notice: .green,
.info: .blue,
],
excludeMetadata: Set<Logger.Level> = [],
extraMetadata: Set<Logger.Level> = [],
disabledLogLevels: Set<Logger.Level> = [],
disabledInDebug: Bool = false,
maxStoredLogsCount: Int = 1_000
) {
fatalError()
}
}

struct Log: CustomStringConvertible {
Expand Down Expand Up @@ -184,7 +225,7 @@ public actor DiscordLogManager {
private var aliveNoticeTask: Task<Void, Never>?

public init(
httpClient: HTTPClient,
httpClient: HTTPClient = .shared,
configuration: Configuration = Configuration()
) async {
/// Will only ever send requests to a webhook endpoint
Expand Down Expand Up @@ -393,7 +434,7 @@ public actor DiscordLogManager {
}

private func makeAttachmentData(attachments: [LogInfo?]) -> (name: String, data: ByteBuffer)? {
if let formatter = self.configuration.sendFullLogAsAttachment.formatter {
if let formatter = self.configuration.sendFullLogsAsAttachment.formatter {
let attachments: [LogContainer] = attachments
.enumerated()
.filter({ $0.element != nil })
Expand Down
6 changes: 3 additions & 3 deletions Tests/DiscordLoggerTests/DiscordLogger.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class DiscordLoggerTests: XCTestCase {
client: self.client,
configuration: .init(
frequency: .seconds(5),
sendFullLogAsAttachment: .enabled,
sendFullLogsAsAttachment: .enabled,
mentions: [
.trace: .role("33333333"),
.notice: .user("22222222"),
Expand Down Expand Up @@ -120,7 +120,7 @@ class DiscordLoggerTests: XCTestCase {
client: self.client,
configuration: .init(
frequency: .milliseconds(100),
sendFullLogAsAttachment: .enabled(
sendFullLogsAsAttachment: .enabled(
formatter: .json(
withJSONExtension: true,
calendar: .init(identifier: .persian),
Expand Down Expand Up @@ -202,7 +202,7 @@ class DiscordLoggerTests: XCTestCase {
client: self.client,
configuration: .init(
frequency: .milliseconds(100),
sendFullLogAsAttachment: .enabled(
sendFullLogsAsAttachment: .enabled(
formatter: .json(
withJSONExtension: true,
calendar: .init(identifier: .persian),
Expand Down

0 comments on commit aba0eaf

Please sign in to comment.