Skip to content

Commit

Permalink
new post: Escrevendo logs para um arquivo customizado
Browse files Browse the repository at this point in the history
  • Loading branch information
tiaguinho committed Oct 26, 2021
1 parent 07fdcfd commit f7e2441
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -4,3 +4,4 @@ Repositório dos snippets usados nos posts do blog [aprendagolang.com.br](https:
## Link dos posts

[Carregando configurações de arquivos TOML](http://aprendagolang.com.br/2021/10/25/carregando-configuracoes-de-arquivos-toml/)
[Escrevendo logs para um arquivo customizado](http://aprendagolang.com.br/2021/10/26/escrevendo-logs-para-um-arquivo-customizado/)
3 changes: 3 additions & 0 deletions log/go.mod
@@ -0,0 +1,3 @@
module github.com/aprendagolang/log

go 1.16
30 changes: 30 additions & 0 deletions log/logs/log.go
@@ -0,0 +1,30 @@
package logs

import (
"log"
"os"
)

// Write escreve uma mensagem de log em um arquivo
func Write(message, filepath string) {
// define um caminho se o filepath não for passado
if filepath == "" {
filepath = "/tmp/my-app.log"
}

// abre o arquivo onde vamos escrever nossa mensagem
file, err := os.OpenFile(filepath, os.O_APPEND|os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
log.Panic(err)
}
defer file.Close()

// seta a saída do log para o arquivo que abrimos
log.SetOutput(file)

// loga data e hora
log.SetFlags(log.LstdFlags)

// escreve a mensagem
log.Println(message)
}
12 changes: 12 additions & 0 deletions log/main.go
@@ -0,0 +1,12 @@
package main

import (
"github.com/aprendagolang/log/logs"
)

func main() {
// escreve no log ola.log
logs.Write("olá mundo!", "./ola.log")
// escreve no log /tmp/my-app.log
logs.Write("funciona!!!", "")
}

0 comments on commit f7e2441

Please sign in to comment.