асинхронно по-умолчанию

This commit is contained in:
2025-07-04 11:27:02 +03:00
parent 6011b9f200
commit 7d03f7280c
5 changed files with 45 additions and 42 deletions
+6 -10
View File
@@ -1,18 +1,16 @@
# Telegram Logrus Hook # Telegram Logrus Hook
This hook emits log messages (and corresponding fields) to the Telegram API for [logrus](https://git.company.lan/gopkg/logrus). Этот хук для [logrus](https://git.company.lan/gopkg/logrus) отправляет сообщения журнала (и соответствующие поля) в Telegram API.
## Installation ## Установка
Install the package with: Установить пакет командой:
``` ```
go get git.company.lan/gopkg/telegramhook go get git.company.lan/gopkg/telegramhook
``` ```
## Usage ## Использование
See the tests for working examples. Also:
```go ```go
import ( import (
@@ -27,9 +25,8 @@ func main() {
"MyCoolApp", "MyCoolApp",
"MYTELEGRAMTOKEN", "MYTELEGRAMTOKEN",
"@mycoolusername", "@mycoolusername",
telegramhook.WithAsync(true),
telegramhook.WithTimeout(30 * time.Second),
telegramhook.WithLevel(logrus.ErrorLevel), telegramhook.WithLevel(logrus.ErrorLevel),
telegramhook.WithTimeout(30 * time.Second),
) )
if err != nil { if err != nil {
log.Fatalf("Encountered error when creating Telegram hook: %s", err) log.Fatalf("Encountered error when creating Telegram hook: %s", err)
@@ -43,7 +40,7 @@ func main() {
} }
``` ```
Also you can set custom http.Client to use SOCKS5 proxy for example Вы также можете использовать настроенный http.Client, например, использующий SOCKS5-прокси:
```go ```go
import ( import (
@@ -73,7 +70,6 @@ func main() {
"MYTELEGRAMTOKEN", "MYTELEGRAMTOKEN",
"@mycoolusername", "@mycoolusername",
httpClient, httpClient,
telegramhook.WithAsync(true),
telegramhook.WithTimeout(30 * time.Second), telegramhook.WithTimeout(30 * time.Second),
) )
if err != nil { if err != nil {
+5 -2
View File
@@ -1,7 +1,10 @@
module git.company.lan/gopkg/telegramhook module git.company.lan/gopkg/telegramhook
go 1.21.5 go 1.23.4
require git.company.lan/gopkg/logrus v0.0.0-20240403185826-6e11474d0c90 require git.company.lan/gopkg/logrus v0.0.0-20240403185826-6e11474d0c90
require golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect require (
github.com/stretchr/testify v1.8.0 // indirect
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect
)
+6 -2
View File
@@ -6,10 +6,14 @@ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+27 -27
View File
@@ -3,6 +3,7 @@ package telegramhook
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"html" "html"
"net/http" "net/http"
@@ -24,19 +25,12 @@ type TelegramHook struct {
chatId string chatId string
threadId string threadId string
level logrus.Level level logrus.Level
async bool sync bool
} }
// Option defines a method for additional configuration when instantiating TelegramHook // Option defines a method for additional configuration when instantiating TelegramHook
type Option func(*TelegramHook) type Option func(*TelegramHook)
// Async sets logging to telegram as asynchronous
func WithAsync(async bool) Option {
return func(h *TelegramHook) {
h.SetAsync(async)
}
}
// Timeout sets http call timeout for telegram client // Timeout sets http call timeout for telegram client
func WithTimeout(timeout time.Duration) Option { func WithTimeout(timeout time.Duration) Option {
return func(h *TelegramHook) { return func(h *TelegramHook) {
@@ -53,7 +47,14 @@ func WithLevel(level logrus.Level) Option {
} }
} }
// New creates a new instance of a hook targeting the Telegram API. // WithSync sets logging to telegram as synchronous
func WithSync(sync bool) Option {
return func(h *TelegramHook) {
h.SetSync(sync)
}
}
// NewTelegramHook creates a new instance of a hook targeting the Telegram API.
func NewTelegramHook(appName, authToken, chatId, threadId string, options ...Option) (*TelegramHook, error) { func NewTelegramHook(appName, authToken, chatId, threadId string, options ...Option) (*TelegramHook, error) {
client := &http.Client{} client := &http.Client{}
return NewTelegramHookWithClient(appName, authToken, chatId, threadId, client, options...) return NewTelegramHookWithClient(appName, authToken, chatId, threadId, client, options...)
@@ -68,7 +69,7 @@ func NewTelegramHookWithClient(appName, authToken, chatId, threadId string, clie
chatId: chatId, chatId: chatId,
threadId: threadId, threadId: threadId,
level: logrus.ErrorLevel, level: logrus.ErrorLevel,
async: false, sync: false,
} }
for _, opt := range options { for _, opt := range options {
@@ -93,10 +94,10 @@ type apiRequest struct {
// apiResponse encapsulates the response structure received from the Telegram API. // apiResponse encapsulates the response structure received from the Telegram API.
type apiResponse struct { type apiResponse struct {
Ok bool `json:"ok"` Ok bool `json:"ok"`
ErrorCode *int `json:"error_code,omitempty"` ErrorCode *int `json:"error_code,omitempty"`
Desc *string `json:"description,omitempty"` Desc *string `json:"description,omitempty"`
Result *interface{} `json:"result,omitempty"` Result *any `json:"result,omitempty"`
} }
// verifyToken issues a test request to the Telegram API to ensure the provided token is correct and valid. // verifyToken issues a test request to the Telegram API to ensure the provided token is correct and valid.
@@ -172,7 +173,7 @@ func (h *TelegramHook) sendMessage(msg string) error {
msg = fmt.Sprintf("%s: %s", msg, *apiRes.Desc) msg = fmt.Sprintf("%s: %s", msg, *apiRes.Desc)
} }
return fmt.Errorf(msg) return errors.New(msg)
} }
return nil return nil
@@ -222,15 +223,14 @@ func (h *TelegramHook) Levels() []logrus.Level {
func (h *TelegramHook) Fire(entry *logrus.Entry) error { func (h *TelegramHook) Fire(entry *logrus.Entry) error {
msg := h.createMessage(entry) msg := h.createMessage(entry)
if h.Async() { if h.Sync() {
go h.sendMessage(msg) if err := h.sendMessage(msg); err != nil {
return nil fmt.Fprintf(os.Stderr, "Unable to send message, %v", err)
return err
}
} }
if err := h.sendMessage(msg); err != nil { go h.sendMessage(msg)
fmt.Fprintf(os.Stderr, "Unable to send message, %v", err)
return err
}
return nil return nil
} }
@@ -307,15 +307,15 @@ func (h *TelegramHook) SetLevel(level logrus.Level) {
h.level = level h.level = level
} }
// Async // Sync
func (h *TelegramHook) Async() bool { func (h *TelegramHook) Sync() bool {
h.mu.RLock() h.mu.RLock()
defer h.mu.RUnlock() defer h.mu.RUnlock()
return h.async return h.sync
} }
func (h *TelegramHook) SetAsync(async bool) { func (h *TelegramHook) SetSync(sync bool) {
h.mu.Lock() h.mu.Lock()
defer h.mu.Unlock() defer h.mu.Unlock()
h.async = async h.sync = sync
} }
+1 -1
View File
@@ -19,7 +19,7 @@ func TestNewTelegramHook(t *testing.T) {
t.Fatalf("Error on valid Telegram API token: %s", err) t.Fatalf("Error on valid Telegram API token: %s", err)
} }
h, _ := NewTelegramHook("testing", os.Getenv("TELEGRAM_TOKEN"), os.Getenv("TELEGRAM_TARGET"), "") h, _ := NewTelegramHook("testing", os.Getenv("TELEGRAM_TOKEN"), os.Getenv("TELEGRAM_TARGET"), "", WithSync(true))
if err != nil { if err != nil {
t.Fatalf("Error on valid Telegram API token and target: %s", err) t.Fatalf("Error on valid Telegram API token and target: %s", err)
} }