mirror of
https://github.com/jkaninda/mysql-bkup.git
synced 2025-12-06 13:39:41 +01:00
refactoring of code
This commit is contained in:
@@ -32,3 +32,4 @@ const BackupExample = "backup --dbname database --disable-compression\n" +
|
||||
const MainExample = "mysql-bkup backup --dbname database --disable-compression\n" +
|
||||
"backup --dbname database --storage s3 --path /custom-path\n" +
|
||||
"restore --dbname database --file db_20231219_022941.sql.gz"
|
||||
const traceLog = "trace"
|
||||
|
||||
97
utils/logger.go
Normal file
97
utils/logger.go
Normal file
@@ -0,0 +1,97 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
/*
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 Jonas Kaninda
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
*/
|
||||
|
||||
// Info returns info log
|
||||
func Info(msg string, args ...interface{}) {
|
||||
log.SetOutput(getStd("/dev/stdout"))
|
||||
logWithCaller("INFO", msg, args...)
|
||||
|
||||
}
|
||||
|
||||
// Warn returns warning log
|
||||
func Warn(msg string, args ...interface{}) {
|
||||
log.SetOutput(getStd("/dev/stdout"))
|
||||
logWithCaller("WARN", msg, args...)
|
||||
|
||||
}
|
||||
|
||||
// Error logs error messages
|
||||
func Error(msg string, args ...interface{}) {
|
||||
log.SetOutput(getStd("/dev/stderr"))
|
||||
logWithCaller("ERROR", msg, args...)
|
||||
}
|
||||
|
||||
func Fatal(msg string, args ...interface{}) {
|
||||
log.SetOutput(os.Stdout)
|
||||
logWithCaller("ERROR", msg, args...)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Helper function to format and log messages with file and line number
|
||||
func logWithCaller(level, msg string, args ...interface{}) {
|
||||
// Format message if there are additional arguments
|
||||
formattedMessage := msg
|
||||
if len(args) > 0 {
|
||||
formattedMessage = fmt.Sprintf(msg, args...)
|
||||
}
|
||||
|
||||
// Get the caller's file and line number (skip 2 frames)
|
||||
_, file, line, ok := runtime.Caller(2)
|
||||
if !ok {
|
||||
file = "unknown"
|
||||
line = 0
|
||||
}
|
||||
// Log message with caller information if GOMA_LOG_LEVEL is trace
|
||||
if strings.ToLower(level) != "off" {
|
||||
if strings.ToLower(level) == traceLog {
|
||||
log.Printf("%s: %s (File: %s, Line: %d)\n", level, formattedMessage, file, line)
|
||||
} else {
|
||||
log.Printf("%s: %s\n", level, formattedMessage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getStd(out string) *os.File {
|
||||
switch out {
|
||||
case "/dev/stdout":
|
||||
return os.Stdout
|
||||
case "/dev/stderr":
|
||||
return os.Stderr
|
||||
case "/dev/stdin":
|
||||
return os.Stdin
|
||||
default:
|
||||
return os.Stdout
|
||||
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,6 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/go-mail/mail"
|
||||
"github.com/jkaninda/mysql-bkup/pkg/logger"
|
||||
"html/template"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -56,7 +55,7 @@ func parseTemplate[T any](data T, fileName string) (string, error) {
|
||||
}
|
||||
|
||||
func SendEmail(subject, body string) error {
|
||||
logger.Info("Start sending email notification....")
|
||||
Info("Start sending email notification....")
|
||||
config := loadMailConfig()
|
||||
emails := strings.Split(config.MailTo, ",")
|
||||
m := mail.NewMessage()
|
||||
@@ -68,16 +67,16 @@ func SendEmail(subject, body string) error {
|
||||
d.TLSConfig = &tls.Config{InsecureSkipVerify: config.SkipTls}
|
||||
|
||||
if err := d.DialAndSend(m); err != nil {
|
||||
logger.Error("Error could not send email : %v", err)
|
||||
Error("Error could not send email : %v", err)
|
||||
return err
|
||||
}
|
||||
logger.Info("Email notification has been sent")
|
||||
Info("Email notification has been sent")
|
||||
return nil
|
||||
|
||||
}
|
||||
func sendMessage(msg string) error {
|
||||
|
||||
logger.Info("Sending Telegram notification... ")
|
||||
Info("Sending Telegram notification... ")
|
||||
chatId := os.Getenv("TG_CHAT_ID")
|
||||
body, _ := json.Marshal(map[string]string{
|
||||
"chat_id": chatId,
|
||||
@@ -97,11 +96,11 @@ func sendMessage(msg string) error {
|
||||
}
|
||||
code := response.StatusCode
|
||||
if code == 200 {
|
||||
logger.Info("Telegram notification has been sent")
|
||||
Info("Telegram notification has been sent")
|
||||
return nil
|
||||
} else {
|
||||
body, _ := io.ReadAll(response.Body)
|
||||
logger.Error("Error could not send message, error: %s", string(body))
|
||||
Error("Error could not send message, error: %s", string(body))
|
||||
return fmt.Errorf("error could not send message %s", string(body))
|
||||
}
|
||||
|
||||
@@ -126,11 +125,11 @@ func NotifySuccess(notificationData *NotificationData) {
|
||||
if err == nil {
|
||||
body, err := parseTemplate(*notificationData, "email.tmpl")
|
||||
if err != nil {
|
||||
logger.Error("Could not parse email template: %v", err)
|
||||
Error("Could not parse email template: %v", err)
|
||||
}
|
||||
err = SendEmail(fmt.Sprintf("✅ Database Backup Notification – %s", notificationData.Database), body)
|
||||
if err != nil {
|
||||
logger.Error("Could not send email: %v", err)
|
||||
Error("Could not send email: %v", err)
|
||||
}
|
||||
}
|
||||
// Telegram notification
|
||||
@@ -138,12 +137,12 @@ func NotifySuccess(notificationData *NotificationData) {
|
||||
if err == nil {
|
||||
message, err := parseTemplate(*notificationData, "telegram.tmpl")
|
||||
if err != nil {
|
||||
logger.Error("Could not parse telegram template: %v", err)
|
||||
Error("Could not parse telegram template: %v", err)
|
||||
}
|
||||
|
||||
err = sendMessage(message)
|
||||
if err != nil {
|
||||
logger.Error("Could not send Telegram message: %v", err)
|
||||
Error("Could not send Telegram message: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -170,11 +169,11 @@ func NotifyError(error string) {
|
||||
BackupReference: os.Getenv("BACKUP_REFERENCE"),
|
||||
}, "email-error.tmpl")
|
||||
if err != nil {
|
||||
logger.Error("Could not parse error template: %v", err)
|
||||
Error("Could not parse error template: %v", err)
|
||||
}
|
||||
err = SendEmail("🔴 Urgent: Database Backup Failure Notification", body)
|
||||
if err != nil {
|
||||
logger.Error("Could not send email: %v", err)
|
||||
Error("Could not send email: %v", err)
|
||||
}
|
||||
}
|
||||
// Telegram notification
|
||||
@@ -186,13 +185,13 @@ func NotifyError(error string) {
|
||||
BackupReference: os.Getenv("BACKUP_REFERENCE"),
|
||||
}, "telegram-error.tmpl")
|
||||
if err != nil {
|
||||
logger.Error("Could not parse error template: %v", err)
|
||||
Error("Could not parse error template: %v", err)
|
||||
|
||||
}
|
||||
|
||||
err = sendMessage(message)
|
||||
if err != nil {
|
||||
logger.Error("Could not send telegram message: %v", err)
|
||||
Error("Could not send telegram message: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,6 @@ package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/jkaninda/mysql-bkup/pkg/logger"
|
||||
"github.com/robfig/cron/v3"
|
||||
"github.com/spf13/cobra"
|
||||
"io"
|
||||
@@ -36,7 +35,7 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
var Version = "development"
|
||||
var Version = ""
|
||||
|
||||
// FileExists checks if the file does exist
|
||||
func FileExists(filename string) bool {
|
||||
@@ -112,7 +111,7 @@ func CopyFile(src, dst string) error {
|
||||
}
|
||||
func ChangePermission(filePath string, mod int) {
|
||||
if err := os.Chmod(filePath, fs.FileMode(mod)); err != nil {
|
||||
logger.Fatal("Error changing permissions of %s: %v\n", filePath, err)
|
||||
Fatal("Error changing permissions of %s: %v\n", filePath, err)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -174,7 +173,7 @@ func GetEnvVariable(envName, oldEnvName string) string {
|
||||
if err != nil {
|
||||
return value
|
||||
}
|
||||
logger.Warn("%s is deprecated, please use %s instead! ", oldEnvName, envName)
|
||||
Warn("%s is deprecated, please use %s instead! ", oldEnvName, envName)
|
||||
}
|
||||
}
|
||||
return value
|
||||
@@ -221,7 +220,7 @@ func GetIntEnv(envName string) int {
|
||||
}
|
||||
ret, err := strconv.Atoi(val)
|
||||
if err != nil {
|
||||
logger.Error("Error: %v", err)
|
||||
Error("Error: %v", err)
|
||||
}
|
||||
return ret
|
||||
}
|
||||
@@ -246,7 +245,7 @@ func CronNextTime(cronExpr string) time.Time {
|
||||
// Parse the cron expression
|
||||
schedule, err := cron.ParseStandard(cronExpr)
|
||||
if err != nil {
|
||||
logger.Error("Error parsing cron expression: %s", err)
|
||||
Error("Error parsing cron expression: %s", err)
|
||||
return time.Time{}
|
||||
}
|
||||
// Get the current time
|
||||
|
||||
Reference in New Issue
Block a user