StarlioX/utils/logger.go

124 lines
1.8 KiB
Go
Raw Permalink Normal View History

package utils
2022-09-25 11:04:32 +03:00
import (
"encoding/json"
2022-10-30 20:12:26 +03:00
"fmt"
2022-09-25 11:04:32 +03:00
"os"
"runtime"
"strings"
2022-09-25 11:04:32 +03:00
"time"
"github.com/rodkranz/fetch"
2022-09-25 11:04:32 +03:00
)
func Logger(text string) {
now := time.Now()
2023-02-18 21:13:38 +03:00
file := string(now.Format("02.01.2006")) + ".log"
if getDatabase() == 0 {
return
}
if !FileExists("logs") {
err := CreateFolder("logs")
2022-09-25 11:04:32 +03:00
if err != nil {
panic(err)
}
}
if !FileExists("./logs/" + file) {
err := CreateFile(file)
if err != nil {
panic(err)
}
}
f, err := os.OpenFile("logs/"+file, os.O_APPEND|os.O_WRONLY, 0600)
2022-09-25 11:04:32 +03:00
if err != nil {
panic(err)
}
2022-10-30 20:12:26 +03:00
_, file, line, ok := runtime.Caller(1)
2022-09-25 11:04:32 +03:00
if !ok {
file = "???"
}
dir, err := os.Getwd()
if err != nil {
Logger(err.Error())
}
if strings.Contains(file, dir) {
2022-10-30 20:12:26 +03:00
file = strings.Replace(file, dir, "", -1)
}
var lineString string
if ok {
lineString = fmt.Sprintf("%d", line)
}
2022-09-25 11:04:32 +03:00
_, err = f.Write([]byte(now.Format("15:04:05") + " | " + text + " [" + file + "] [" + lineString + "]\n"))
2022-09-25 11:04:32 +03:00
if err != nil {
panic(err)
}
}
func FileExists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
func CreateFile(name string) error {
file, err := os.Create("logs/" + name)
2022-09-25 11:04:32 +03:00
if err != nil {
return nil
2022-09-25 11:04:32 +03:00
}
defer func(file *os.File) {
err := file.Close()
2022-09-25 11:04:32 +03:00
if err != nil {
2022-09-25 11:04:32 +03:00
}
}(file)
return nil
}
func CreateFolder(name string) error {
err := os.Mkdir(name, 0755)
if err != nil {
return err
}
2022-09-25 11:04:32 +03:00
return nil
}
func getDatabase() int {
client := fetch.NewDefault()
res, err := client.Get("http://localhost:3000/api/get/settings", nil)
if err != nil {
panic(err)
}
body, err := res.ToString()
if err != nil {
panic(err)
}
type DatabaseStruct struct {
Save_logg int `json:"save_logg"`
}
var Database DatabaseStruct
err = json.Unmarshal([]byte(body), &Database)
if err != nil {
panic(err)
}
return Database.Save_logg
}