Skip to content

Fix log message #2

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

Open
wants to merge 5 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
4 changes: 2 additions & 2 deletions Package.resolved
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
"repositoryURL": "https://github.com/apple/swift-log.git",
"state": {
"branch": null,
"revision": "74d7b91ceebc85daf387ebb206003f78813f71aa",
"version": "1.2.0"
"revision": "32e8d724467f8fe623624570367e3d50c5638e46",
"version": "1.5.2"
}
}
]
Expand Down
6 changes: 3 additions & 3 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
// swift-tools-version:5.2
// swift-tools-version:5.6
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
name: "swift-log-telegram",
platforms: [
.macOS(.v10_15)
.macOS(.v12)
],
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(name: "LoggingTelegram", targets: ["LoggingTelegram"])
],
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(url: "https://github.com/apple/swift-log.git", from: "1.0.0")
.package(url: "https://github.com/apple/swift-log.git", from: "1.5.2")
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
Expand Down
2 changes: 1 addition & 1 deletion Sources/LoggingTelegram/MarkdownLog.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ struct MarkdownLog: CustomStringConvertible {
+ "*\(message.telegramEscaping())*\n"
+ location.telegramEscaping()
+ (metadata.count > 0 ? "*Metadata*\n" : "")
+ metadata.map { "*\($0.telegramEscaping())*: \($1)" }.joined(separator: "\n")
+ metadata.map { "*\($0.telegramEscaping())*: \($1.telegramEscaping())" }.joined(separator: "\n")
+ (mentionedUsers.count > 0 ? "\n" : "")
+ mentionedUsers.map { "\($0)" }.joined(separator: " ")
}
Expand Down
28 changes: 0 additions & 28 deletions Sources/LoggingTelegram/SynchronousDataTask.swift

This file was deleted.

91 changes: 38 additions & 53 deletions Sources/LoggingTelegram/TelegramLogHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,9 @@ public var telegramLogDefaultLevel: Logger.Level = .critical
/// Forked from `SlackLogHandler`.
public class TelegramLogHandler<T>: LogHandler where T: TelegramId {
private var timestamp: String {
var buffer = [Int8](repeating: 0, count: 255)
var timestamp = time(nil)
let localTime = localtime(&timestamp)
strftime(&buffer, buffer.count, "%Y-%m-%dT%H:%M:%S%z", localTime)
return buffer.withUnsafeBufferPointer {
$0.withMemoryRebound(to: CChar.self) {
String(cString: $0.baseAddress!)
}
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:MM:SS"
return formatter.string(from: Date())
}

/// The log label for the log handler.
Expand Down Expand Up @@ -127,51 +121,42 @@ public class TelegramLogHandler<T>: LogHandler where T: TelegramId {

private func send(_ telegramMessage: Message) {
let payload: Data
do {
payload = try JSONEncoder().encode(telegramMessage)
} catch {
print("Parsing error. ")
return
}

var request = URLRequest(url: api)
request.httpMethod = "POST"
request.httpBody = payload
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

let (data, resp, error) = URLSession.shared.synchronousDataTask(with: request)

guard (resp as? HTTPURLResponse) != nil else {
print("Failed to send Telegram message with receiving error")
return
}

if let error = error {
print("Failed to send Telegram message with connection error: \(error)")
}

guard let returnData = data else {
return
}

let returnStatus: TelegramReturn

do {
returnStatus = try JSONDecoder().decode(TelegramReturn.self, from: returnData)
} catch {
print("Parsing error. ")
return
}
do {
payload = try JSONEncoder().encode(telegramMessage)
} catch {
print("Parsing error. ")
return
}

switch returnStatus {
case .error(let code, let message):
print("Failed to send Telegram message with error: \(code)")
print("Error message: " + message)
return
case .ok:
break
}
// Asynchronous telegram API request execution
var request = URLRequest(url: api)
request.httpMethod = "POST"
request.httpBody = payload
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error {
print("Failed to send Telegram message: \(error)")
return
}

if let data {
guard let status = try? JSONDecoder().decode(TelegramReturn.self, from: data) else {
print("Failed to send Telegram message: Response has incorrect format")
return
}

switch status {
case .error(let code, let message):
print("Failed to send Telegram message with error: \(code)")
print("Error message: " + message)
case .ok:
break
}
}
}
task.resume()
}

struct Message: Encodable {
Expand Down