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

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
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
```
## Usage
See the tests for working examples. Also:
## Использование
```go
import (
@@ -27,9 +25,8 @@ func main() {
"MyCoolApp",
"MYTELEGRAMTOKEN",
"@mycoolusername",
telegramhook.WithAsync(true),
telegramhook.WithTimeout(30 * time.Second),
telegramhook.WithLevel(logrus.ErrorLevel),
telegramhook.WithTimeout(30 * time.Second),
)
if err != nil {
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
import (
@@ -73,7 +70,6 @@ func main() {
"MYTELEGRAMTOKEN",
"@mycoolusername",
httpClient,
telegramhook.WithAsync(true),
telegramhook.WithTimeout(30 * time.Second),
)
if err != nil {
+5 -2
View File
@@ -1,7 +1,10 @@
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 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/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
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.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/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
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.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 (
"bytes"
"encoding/json"
"errors"
"fmt"
"html"
"net/http"
@@ -24,19 +25,12 @@ type TelegramHook struct {
chatId string
threadId string
level logrus.Level
async bool
sync bool
}
// Option defines a method for additional configuration when instantiating 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
func WithTimeout(timeout time.Duration) Option {
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) {
client := &http.Client{}
return NewTelegramHookWithClient(appName, authToken, chatId, threadId, client, options...)
@@ -68,7 +69,7 @@ func NewTelegramHookWithClient(appName, authToken, chatId, threadId string, clie
chatId: chatId,
threadId: threadId,
level: logrus.ErrorLevel,
async: false,
sync: false,
}
for _, opt := range options {
@@ -93,10 +94,10 @@ type apiRequest struct {
// apiResponse encapsulates the response structure received from the Telegram API.
type apiResponse struct {
Ok bool `json:"ok"`
ErrorCode *int `json:"error_code,omitempty"`
Desc *string `json:"description,omitempty"`
Result *interface{} `json:"result,omitempty"`
Ok bool `json:"ok"`
ErrorCode *int `json:"error_code,omitempty"`
Desc *string `json:"description,omitempty"`
Result *any `json:"result,omitempty"`
}
// 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)
}
return fmt.Errorf(msg)
return errors.New(msg)
}
return nil
@@ -222,15 +223,14 @@ func (h *TelegramHook) Levels() []logrus.Level {
func (h *TelegramHook) Fire(entry *logrus.Entry) error {
msg := h.createMessage(entry)
if h.Async() {
go h.sendMessage(msg)
return nil
if h.Sync() {
if err := h.sendMessage(msg); err != nil {
fmt.Fprintf(os.Stderr, "Unable to send message, %v", err)
return err
}
}
if err := h.sendMessage(msg); err != nil {
fmt.Fprintf(os.Stderr, "Unable to send message, %v", err)
return err
}
go h.sendMessage(msg)
return nil
}
@@ -307,15 +307,15 @@ func (h *TelegramHook) SetLevel(level logrus.Level) {
h.level = level
}
// Async
func (h *TelegramHook) Async() bool {
// Sync
func (h *TelegramHook) Sync() bool {
h.mu.RLock()
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()
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)
}
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 {
t.Fatalf("Error on valid Telegram API token and target: %s", err)
}