Skip to content
This repository has been archived by the owner on Sep 13, 2023. It is now read-only.

Commit

Permalink
Merge pull request #13 from palavrapasse/11-enhancement-telegram-writ…
Browse files Browse the repository at this point in the history
…er-to-keep-logger-message-format

enhancement: telegram writer to keep logger message format
  • Loading branch information
rutesantos4 authored Jan 7, 2023
2 parents dc153c2 + c025575 commit ef0808f
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 30 deletions.
43 changes: 13 additions & 30 deletions pkg/telegramclient.go
Original file line number Diff line number Diff line change
@@ -1,49 +1,32 @@
package pkg

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"log"
)

const messageType = "application/json"

type TelegramClient struct {
url string
chatId string
logs []string
loggers []*log.Logger
}

func NewTelegramClient(botToken, chatId string) TelegramClient {

url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", botToken)

return TelegramClient{
url: url,
logs: levelPrefix,
chatId: chatId,
tw := TelegramWriter{
botToken: botToken,
chatId: chatId,
}
}

func (tc TelegramClient) Write(ar Record) {
log := tc.logs[ar.Level]

body, err := json.Marshal(map[string]string{
"chat_id": tc.chatId,
"text": fmt.Sprintf("%s%s", log, ar.Message),
})
loggers := make([]*log.Logger, len(levelPrefix))

if err != nil {
return
for i, v := range levelPrefix {
loggers[i] = log.New(tw, v, defaultLoggerFlag)
}

response, err := http.Post(tc.url, messageType, bytes.NewBuffer(body))

if err != nil {
return
return TelegramClient{
loggers: loggers,
}
}

defer response.Body.Close()

func (tc TelegramClient) Write(ar Record) {
tc.loggers[ar.Level].Println(ar.Message)
}
37 changes: 37 additions & 0 deletions pkg/telegramwriter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package pkg

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)

type TelegramWriter struct {
botToken string
chatId string
}

func (tw TelegramWriter) Write(p []byte) (n int, err error) {

body, err := json.Marshal(map[string]string{
"chat_id": tw.chatId,
"text": string(p[:]),
})

if err != nil {
return 0, err
}

url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", tw.botToken)

response, err := http.Post(url, messageType, bytes.NewBuffer(body))

if err != nil {
return 0, err
}

defer response.Body.Close()

return len(p), nil
}

0 comments on commit ef0808f

Please sign in to comment.