Skip to content

Commit

Permalink
mudança no modelo de Print de Logs.
Browse files Browse the repository at this point in the history
  • Loading branch information
armando-couto committed Mar 17, 2022
1 parent 4973936 commit b204ee8
Show file tree
Hide file tree
Showing 8 changed files with 65 additions and 40 deletions.
30 changes: 27 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
# Module goutils

Functions used in everyday life that help a lot.

### Dependencia

```shell
go get go.mongodb.org/[email protected]
```

## Installation

```shell script
$ go get github.com/armando-couto/goutils
```

## Methods

### arquivo.go

```go
ListFolderFiles(path string) Return []os.FileInfo
ReadingFiles(path string, fileName string) Return string
Expand All @@ -25,41 +30,48 @@ Backup(path, name, texto string) Return void
```

### array.go

````go
ContainsToStringInArray(a []string, x string) Return int
````

### aws_sqs.go

```go
ConectionSQS() Return *sqs.SQS
TokenGeneratorMessageId() Return string
```

### base64.go

```go
EncodeStringToBase64(value string) Return string
DecodeBase64ToString(value string) Return string
```

### bool.go

```go
ContainsToStringInArrayReturnBool(a []string, x string) Return bool
```

### cpf_cnpj.go

```go
ValidationCPF(cpf string) Return error
ValidationCNPJ(cnpj string) Return error
```

### csv.go

```go
CSVGZExport(StructCsv [][]string, nomeArquivo string) Return error
CSVRead(pathFile string) Return [][]string
GeneratorFilesGen(payload []interface{}, f func([][]string) [][]string, nomeArq string) Return error
GeneratorFilesGen(payload []interface{}, f func ([][]string) [][]string, nomeArq string) Return error
```

### datetime.go

```go
ConvertStringToTimeLayoutDDMMYYYY(value string) Return time.Time
ConvertTimeToStringLayoutDD_MM_YYYY(date time.Time) Return string
Expand All @@ -79,18 +91,20 @@ ConvertStringToTimeLayoutYYYY_MM_DDTHH_MM_SS_000(value string) Return time.Time
ConvertStringToTimeLayoutHHMMSS(value string) Return time.Time
ConvertStringToTimeLayoutHH_MM_SS(value string) Return time.Time
ConvertStringToTimeLayoutDDMMYYYYHHMMSS(d time.Time, h time.Time) Return time.Time
RangeDate(end, start time.Time) func() Return time.Time
RangeDate(end, start time.Time) func () Return time.Time
DatePlusTime(date, timeOfDay time.Time) Returns (time.Time, error)
WeekStartDate(date time.Time) time.Time
WeekEndDate(date time.Time) time.Time
```

### environment.go

```go
Godotenv(key string) Return string
```

### float.go

```go
Subtract(valo1, valor2 float64) Return float64
ConvertFloatToFloatScale2(valor float64) Return float64
Expand All @@ -104,12 +118,14 @@ ConvertFloatToBrMoneyString(value float64) Return string
```

### ftp.go

```go
ListOfAvailableFilesNoFTP(remote string, port string, user string, pass string) Returns (*ftp.ServerConn, error, []string)
GetHostKey(host string, isProduction bool) Return ssh.PublicKey
```

### integer.go

```go
ContainsInt(a []int, x int) Return bool
ConvertStringToInt5Digits(value string) Return int
Expand All @@ -118,23 +134,27 @@ ConvertIntToString(value int) Return string
```

### logger_file.go

```go
CreateFileDayInfo(message string) Return void
CreateFileDayError(message string) Return void
CreateFileDayError(message interface{}) Return void
```

### mysql_connection.go

```go
ConnectionBDMySQL() Return *sql.DB
```

### psql_connection.go

```go
ConnectionBDPostgreSQL() Return *sql.DB
ConnectionBDPostgreSQLORM() Return (DB *gorm.DB)
```

### string.go

```go
RemoveZerosInLeft(value string) Return string
RemoveSpaceString(value string) Return string
Expand All @@ -153,17 +173,20 @@ ParseBinToHex(s string) Return string
```

### struct.go

```go
CheckIfIdIfNotZero(objetoId int) Return interface{}
```

### try_catch.go

```go
Throw(up Exception) Return void
(tcf Block) Do() Return void
```

### validacoes.go

```go
MaskCard6Initials(cardString string) Return string
MaskLastDigits(card string) Return string
Expand All @@ -173,6 +196,7 @@ ValidateTelephone(telefone string) Return string
```

### zip.go

```go
ZipFiles(filename string, files []string) Return error
AddFileToZip(zipWriter *zip.Writer, filename string) Return error
Expand Down
8 changes: 4 additions & 4 deletions aws_s3.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func UpdloadInS3(file multipart.File, path, fileName string) string {
Body: file,
})
if err != nil {
CreateFileDayError(err.Error())
CreateFileDayError(FormatMessage(MessageError{Error: err.Error()}))
return ""
}
CreateFileDayInfo(fmt.Sprint("Upload do Arquivo: ", up.UploadID))
Expand All @@ -60,7 +60,7 @@ func UpdloadInS3Base64(b64 string, path, fileName string) string {

dec, err := base64.StdEncoding.DecodeString(b64)
if err != nil {
CreateFileDayError(err.Error())
CreateFileDayError(FormatMessage(MessageError{Error: err.Error()}))
return ""
}
//file, header, err := c.Request.FormFile("photo")
Expand All @@ -72,7 +72,7 @@ func UpdloadInS3Base64(b64 string, path, fileName string) string {
Body: bytes.NewBuffer(dec),
})
if err != nil {
CreateFileDayError(err.Error())
CreateFileDayError(FormatMessage(MessageError{Error: err.Error()}))
return ""
}
CreateFileDayInfo(fmt.Sprint("Upload do Arquivo: ", up.UploadID))
Expand Down Expand Up @@ -103,7 +103,7 @@ func UpdloadInS3Base64Byte(b64 []byte, path, fileName string) string {
Body: bytes.NewBuffer(b64),
})
if err != nil {
CreateFileDayError(err.Error())
CreateFileDayError(FormatMessage(MessageError{Error: err.Error()}))
return ""
}
CreateFileDayInfo(fmt.Sprint("Upload do Arquivo: ", up.UploadID))
Expand Down
2 changes: 1 addition & 1 deletion base64.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func EncodeStringToBase64(value string) string {
func DecodeBase64ToString(value string) string {
data, err := base64.StdEncoding.DecodeString(value)
if err != nil {
CreateFileDayError("error:" + err.Error())
CreateFileDayError(FormatMessage(MessageError{Error: err.Error()}))
return "ERRONOJSON"
}
return string(data)
Expand Down
4 changes: 2 additions & 2 deletions connection_mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ import (
func ConnectionBDMySQL() *sql.DB {
db, err := sql.Open("mysql", Godotenv("database_mysql"))
if err != nil {
CreateFileDayError(err.Error())
CreateFileDayError(MessageError{File: "ConnectionBDMySQL()", Error: err.Error()})
if db.Ping() != nil {
CreateFileDayError("Erro ping DB")
CreateFileDayError(MessageError{File: "ConnectionBDMySQL()", Error: "Erro ping DB"})
}
}

Expand Down
4 changes: 2 additions & 2 deletions csv.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,15 @@ func CSVGZExport(StructCsv [][]string, nomeArquivo string) error {
func CSVRead(pathFile string) [][]string {
f, err := os.Open(pathFile)
if err != nil {
CreateFileDayError("ERRO: Leitura arquivo CSV:" + err.Error())
CreateFileDayError(FormatMessage(MessageError{Error: "ERRO: Leitura arquivo CSV:" + err.Error()}))
}
defer f.Close()

arqReader := csv.NewReader(f)
arqReader.LazyQuotes = true
lines, err := arqReader.ReadAll()
if err != nil {
CreateFileDayError("ERRO: Leitura arquivo CSV:" + err.Error())
CreateFileDayError(FormatMessage(MessageError{Error: "ERRO: Leitura arquivo CSV:" + err.Error()}))
}
return lines
}
Expand Down
10 changes: 5 additions & 5 deletions file.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (
func ListFolderFiles(path string) []os.FileInfo {
files, err := ioutil.ReadDir(path)
if err != nil {
CreateFileDayError(fmt.Sprint("a pasta '", path, "' não existe!"))
CreateFileDayError(FormatMessage(MessageError{File: "ListFolderFiles(path)", Error: fmt.Sprint("a pasta '", path, "' não existe!")}))
}
return files
}
Expand All @@ -27,7 +27,7 @@ func ReadingFiles(path string, fileName string) string {
file, err := os.Open(fmt.Sprint(path, fileName))
if err != nil {
log.Fatal(err)
CreateFileDayError(fmt.Sprint("O arquivo '", fileName, "' não está mais na pasta!"))
CreateFileDayError(FormatMessage(MessageError{File: "ReadingFiles(path, fileName)", Error: fmt.Sprint("O arquivo '", fileName, "' não está mais na pasta!")}))
}
defer file.Close()

Expand All @@ -40,9 +40,9 @@ func ReadingFiles(path string, fileName string) string {
*/
func RemoveFilesOfPath(path string) {
if os.Remove(path) != nil {
CreateFileDayError("Problema ao remover do diretório local")
CreateFileDayError(FormatMessage(MessageError{Error: "Problema ao remover do diretório local"}))
} else {
CreateFileDayError("Removido do local")
CreateFileDayError(FormatMessage(MessageError{Error: "Removido do local"}))
}
}

Expand Down Expand Up @@ -81,7 +81,7 @@ func CreateArchiveNodirectory(nomeDoArquivo string, conteudo string) error {
*/
func IsError(err error) bool {
if err != nil {
CreateFileDayError(err.Error())
CreateFileDayError(FormatMessage(MessageError{Error: err.Error()}))
}
return err != nil
}
Expand Down
6 changes: 3 additions & 3 deletions ftp.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,17 @@ import (
func ListOfAvailableFilesNoFTP(remote string, port string, user string, pass string) (*ftp.ServerConn, error, []string) {
c, err := ftp.Dial(remote+":"+port, ftp.DialWithTimeout(60*time.Second))
if err != nil {
CreateFileDayError(err.Error())
CreateFileDayError(FormatMessage(MessageError{Error: err.Error()}))
}
err = c.Login(user, pass)
if err != nil {
CreateFileDayError(err.Error())
CreateFileDayError(FormatMessage(MessageError{Error: err.Error()}))
}

//var nome_arquivo string
list, _ := c.NameList("/")
if err := c.Quit(); err != nil {
CreateFileDayError(err.Error())
CreateFileDayError(FormatMessage(MessageError{Error: err.Error()}))
}
return c, err, list
}
Expand Down
41 changes: 21 additions & 20 deletions logger_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,28 +41,29 @@ func CreateFileDayInfo(message string) {
}
}

func CreateFileDayError(message string) {
message = strings.ReplaceAll(message, "\n", "")
if ConvertStringToBool(Godotenv("logger")) {
connection := ConnectionMongoDB()
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
defer cancel()
defer connection.Client().Disconnect(ctx)
_, err := connection.Collection("errors").InsertOne(ctx, MongoObject{Date: time.Now(), Message: message})
if err != nil {
log.Println(err)
}
} else {
f, err := os.OpenFile(fmt.Sprint(time.Now().Format("20060102"), ".log"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Println(err)
}
defer f.Close()
type MessageError struct {
Log *log.Logger
File string
Query string
Error string
Objects interface{}
}

logger := log.New(f, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)
logger.Println(message)
fmt.Println(message)
func CreateFileDayError(message MessageError) {
message.Query = strings.ReplaceAll(message.Query, "\n", "")
f, err := os.OpenFile(fmt.Sprint(time.Now().Format("20060102"), ".log"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Println(err)
}
defer f.Close()

message.Log.Println(message)
fmt.Println(message)
}

func FormatMessage(message MessageError) MessageError {
message.Log.SetFlags(log.LstdFlags | log.Lshortfile)
return message
}

type MongoObject2 struct {
Expand Down

0 comments on commit b204ee8

Please sign in to comment.