Log file.. Where...? [SOLVED]

When I use;

log.Println()

Where can I find this log? I’m sorry, I’m new to GO and still got too many doubts…

Tnx.

package main

import (
	"bytes"
	"fmt"
	"log"
)

func main() {
	var buf bytes.Buffer
	logger := log.New(&buf, "logger: ", log.Lshortfile)
	logger.Print("Hello, log file!")

	fmt.Print(&buf)
}

https://golang.org/pkg/log/#Println

1 Like

Lucas tu é do Brasil?

Yeah, I’m from brazil, :blush:

example using log and Println()

main.go

package main

import (
	"middleware"
	"fmt"
	"net/http"
)

func hello(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Executing...")
	w.Write([]byte("Hello"))
}

func main() {
	
	logger := middleware.CreateLogger("logger")
	http.Handle("/", middleware.Time(logger, hello))
	http.ListenAndServe(":4000", nil)
}

middleware.go

package middleware

import (
	"net/http"
	"time"
	"log"
	"os"
)

func CreateLogger(filename string) *log.Logger {
	file, err := os.OpenFile(filename+".log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		panic(err)
	}
	logger := log.New(file, "", log.Ldate|log.Ltime|log.Lshortfile)
	return logger
}

func Time(logger *log.Logger, next http.HandlerFunc) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		next.ServeHTTP(w, r)
		elapsed := time.Since(start)
        // Println calls l.Output to print to the logger.
        // Arguments are handled in the manner of fmt.Println.
		logger.Println(elapsed)
	})
}
1 Like

Ah então é um arquivo comum… Pensei que fosse algum log específico, sem precisar da rotina pra criar/escrever em um arquivo…

Você não precisa necessariamente escrever em um arquivo, mas nesse exemplo é com escrita de arquivo, no primeiro exemplo somente tem a saida dele, trabalhando com buffer e fmt.

Eu tô tendo muita dificuldade aqui pra fazer uma simples conversão! Tô com esse trecho de código aqui;

		//TESTE
		runtime.ReadMemStats(&m)
		fmt.Println("INICIO;\r\n" + m.Alloc)
		//TESTE

Esse m.Alloc é do tipo Uint64, não tô conseguindo converter isso pra string de jeito nenhum, já pesquisei e achei várias formas de como converter isso mas nenhuma compila…

package main

import (
	"fmt"
)

var teste uint64

func main() {
	teste = 67
	fmt.Println("INICIO;\r\n" + string(teste))
}

Agora não sei o que você tem armazenado na sua variable m.Alloc porque o número vai ser convertido para um caracterer como pode ver abaixo na struct string

// string is the set of all strings of 8-bit bytes, conventionally but not
// necessarily representing UTF-8-encoded text. A string may be empty, but
// not nil. Values of string type are immutable.
type string string

É o número de memória alocada.

or using this:

package main

import (
	"fmt"
	"strconv"
)

var teste uint64

var teste2 int

func main() {
	teste = 67
	teste2 = 90

	fmt.Println("INICIO;\r\n" + string(teste))

	fmt.Println("INICIO;\r\n" + strconv.Itoa(teste2))
}

more details:
https://golang.org/pkg/strconv/

Consegui Lucas valeu. Abraço.

:smiley:

1 Like

It prints to Stderr

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.